Programs & Examples On #Facilities

<Django object > is not JSON serializable

simplejson and json don't work with django objects well.

Django's built-in serializers can only serialize querysets filled with django objects:

data = serializers.serialize('json', self.get_queryset())
return HttpResponse(data, content_type="application/json")

In your case, self.get_queryset() contains a mix of django objects and dicts inside.

One option is to get rid of model instances in the self.get_queryset() and replace them with dicts using model_to_dict:

from django.forms.models import model_to_dict

data = self.get_queryset()

for item in data:
   item['product'] = model_to_dict(item['product'])

return HttpResponse(json.simplejson.dumps(data), mimetype="application/json")

Hope that helps.

What is System, out, println in System.out.println() in Java

Whenever you're confused, I would suggest consulting the Javadoc as the first place for your clarification.

From the javadoc about System, here's what the doc says:

public final class System
extends Object

The System class contains several useful class fields and methods. It cannot be instantiated.
Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.

Since:
JDK1.0

Regarding System.out

public static final PrintStream out
The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user.
For simple stand-alone Java applications, a typical way to write a line of output data is:

     System.out.println(data)

Having issues with a MySQL Join that needs to meet multiple conditions

You can group conditions with parentheses. When you are checking if a field is equal to another, you want to use OR. For example WHERE a='1' AND (b='123' OR b='234').

SELECT u.*
FROM rooms AS u
JOIN facilities_r AS fu
ON fu.id_uc = u.id_uc AND (fu.id_fu='4' OR fu.id_fu='3')
WHERE vizibility='1'
GROUP BY id_uc
ORDER BY u_premium desc, id_uc desc

posting hidden value

I'm not sure what you just did there, but from what I can tell this is what you're asking for:

bookingfacilities.php

<form action="successfulbooking.php" method="post">
    <input type="hidden" name="date" value="<?php echo $date; ?>">  
    <input type="submit" value="Submit Form">
</form>

successfulbooking.php

<?php
    $date = $_POST['date'];
    // add code here
?>

Not sure what you want to do with that third page(booking_now.php) too.

Plot a legend outside of the plotting area in base graphics?

Another solution, besides the ondes already mentioned (using layout or par(xpd=TRUE)) is to overlay your plot with a transparent plot over the entire device and then add the legend to that.

The trick is to overlay a (empty) graph over the complete plotting area and adding the legend to that. We can use the par(fig=...) option. First we instruct R to create a new plot over the entire plotting device:

par(fig=c(0, 1, 0, 1), oma=c(0, 0, 0, 0), mar=c(0, 0, 0, 0), new=TRUE)

Setting oma and mar is needed since we want to have the interior of the plot cover the entire device. new=TRUE is needed to prevent R from starting a new device. We can then add the empty plot:

plot(0, 0, type='n', bty='n', xaxt='n', yaxt='n')

And we are ready to add the legend:

legend("bottomright", ...)

will add a legend to the bottom right of the device. Likewise, we can add the legend to the top or right margin. The only thing we need to ensure is that the margin of the original plot is large enough to accomodate the legend.

Putting all this into a function;

add_legend <- function(...) {
  opar <- par(fig=c(0, 1, 0, 1), oma=c(0, 0, 0, 0), 
    mar=c(0, 0, 0, 0), new=TRUE)
  on.exit(par(opar))
  plot(0, 0, type='n', bty='n', xaxt='n', yaxt='n')
  legend(...)
}

And an example. First create the plot making sure we have enough space at the bottom to add the legend:

par(mar = c(5, 4, 1.4, 0.2))
plot(rnorm(50), rnorm(50), col=c("steelblue", "indianred"), pch=20)

Then add the legend

add_legend("topright", legend=c("Foo", "Bar"), pch=20, 
   col=c("steelblue", "indianred"),
   horiz=TRUE, bty='n', cex=0.8)

Resulting in:

Example figure shown legend in top margin

Do you (really) write exception safe code?

Some of us prefer languages like Java which force us to declare all the exceptions thrown by methods, instead of making them invisible as in C++ and C#.

When done properly, exceptions are superior to error return codes, if for no other reason than you don't have to propagate failures up the call chain manually.

That being said, low-level API library programming should probably avoid exception handling, and stick to error return codes.

It's been my experience that it's difficult to write clean exception handling code in C++. I end up using new(nothrow) a lot.

Travel/Hotel API's?

Try Tixik.com and their API there. They have a very different data that big players, really good coverage mostly in Europe and good API conditions.

cannot call member function without object

If you want to call them like that, you should declare them static.

WPF chart controls

Free tools supporting panning / zooming:

Free tools without built in pan / zoom support:

Paid tools with built in pan / zoom support:

Full Disclosure: I have been heavily involved in development of Visiblox, hence I know that library in much more detail than the others.

How do I shrink my SQL Server Database?

This may seem bizarre, but it's worked for me and I have written a C# program to automate this.

Step 1: Truncate the transaction log (Back up only the transaction log, turning on the option to remove inactive transactions)

Step 2: Run a database shrink, moving all the pages to the start of the files

Step 3: Truncate the transaction log again, as step 2 adds log entries

Step 4: Run a database shrink again.

My stripped down code, which uses the SQL DMO library, is as follows:

SQLDatabase.TransactionLog.Truncate();
SQLDatabase.Shrink(5, SQLDMO.SQLDMO_SHRINK_TYPE.SQLDMOShrink_NoTruncate);
SQLDatabase.TransactionLog.Truncate();
SQLDatabase.Shrink(5, SQLDMO.SQLDMO_SHRINK_TYPE.SQLDMOShrink_Default);

Reading the selected value from asp:RadioButtonList using jQuery

Try the below code:

<script type="text/javascript">
    $(document).ready(function () {

        $(".ratingButtons").buttonset();

    });
 </script>


<asp:RadioButtonList ID="RadioButtonList1" RepeatDirection="Horizontal" runat="server"
            AutoPostBack="True" DataSourceID="SqlDataSourceSizes"     DataTextField="ProdSize"
            CssClass="ratingButtons" DataValueField="_ProdSizeID" Font-Size="X-Small" 
            ForeColor="#666666">
</asp:RadioButtonList>

Efficiently replace all accented characters in a string?

For the lads using TypeScript and those who don't want to deal with string prototypes, here is a typescript version of Ed.'s answer:

    // Usage example:
    "Some string".replace(/[^a-zA-Z0-9-_]/g, char => ToLatinMap.get(char) || '')

    // Map:
    export let ToLatinMap: Map<string, string> = new Map<string, string>([
        ["Á", "A"],
        ["A", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["A", "A"],
        ["Â", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["Ä", "A"],
        ["A", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["À", "A"],
        ["?", "A"],
        ["?", "A"],
        ["A", "A"],
        ["A", "A"],
        ["Å", "A"],
        ["?", "A"],
        ["?", "A"],
        ["?", "A"],
        ["Ã", "A"],
        ["?", "AA"],
        ["Æ", "AE"],
        ["?", "AE"],
        ["?", "AE"],
        ["?", "AO"],
        ["?", "AU"],
        ["?", "AV"],
        ["?", "AV"],
        ["?", "AY"],
        ["?", "B"],
        ["?", "B"],
        ["?", "B"],
        ["?", "B"],
        ["?", "B"],
        ["?", "B"],
        ["C", "C"],
        ["C", "C"],
        ["Ç", "C"],
        ["?", "C"],
        ["C", "C"],
        ["C", "C"],
        ["?", "C"],
        ["?", "C"],
        ["D", "D"],
        ["?", "D"],
        ["?", "D"],
        ["?", "D"],
        ["?", "D"],
        ["?", "D"],
        ["?", "D"],
        ["?", "D"],
        ["?", "D"],
        ["Ð", "D"],
        ["?", "D"],
        ["?", "DZ"],
        ["?", "DZ"],
        ["É", "E"],
        ["E", "E"],
        ["E", "E"],
        ["?", "E"],
        ["?", "E"],
        ["Ê", "E"],
        ["?", "E"],
        ["?", "E"],
        ["?", "E"],
        ["?", "E"],
        ["?", "E"],
        ["?", "E"],
        ["Ë", "E"],
        ["E", "E"],
        ["?", "E"],
        ["?", "E"],
        ["È", "E"],
        ["?", "E"],
        ["?", "E"],
        ["E", "E"],
        ["?", "E"],
        ["?", "E"],
        ["E", "E"],
        ["?", "E"],
        ["?", "E"],
        ["?", "E"],
        ["?", "ET"],
        ["?", "F"],
        ["ƒ", "F"],
        ["?", "G"],
        ["G", "G"],
        ["G", "G"],
        ["G", "G"],
        ["G", "G"],
        ["G", "G"],
        ["?", "G"],
        ["?", "G"],
        ["G", "G"],
        ["?", "H"],
        ["?", "H"],
        ["?", "H"],
        ["H", "H"],
        ["?", "H"],
        ["?", "H"],
        ["?", "H"],
        ["?", "H"],
        ["H", "H"],
        ["Í", "I"],
        ["I", "I"],
        ["I", "I"],
        ["Î", "I"],
        ["Ï", "I"],
        ["?", "I"],
        ["I", "I"],
        ["?", "I"],
        ["?", "I"],
        ["Ì", "I"],
        ["?", "I"],
        ["?", "I"],
        ["I", "I"],
        ["I", "I"],
        ["I", "I"],
        ["I", "I"],
        ["?", "I"],
        ["?", "D"],
        ["?", "F"],
        ["?", "G"],
        ["?", "R"],
        ["?", "S"],
        ["?", "T"],
        ["?", "IS"],
        ["J", "J"],
        ["?", "J"],
        ["?", "K"],
        ["K", "K"],
        ["K", "K"],
        ["?", "K"],
        ["?", "K"],
        ["?", "K"],
        ["?", "K"],
        ["?", "K"],
        ["?", "K"],
        ["?", "K"],
        ["L", "L"],
        ["?", "L"],
        ["L", "L"],
        ["L", "L"],
        ["?", "L"],
        ["?", "L"],
        ["?", "L"],
        ["?", "L"],
        ["?", "L"],
        ["?", "L"],
        ["?", "L"],
        ["?", "L"],
        ["?", "L"],
        ["L", "L"],
        ["?", "LJ"],
        ["?", "M"],
        ["?", "M"],
        ["?", "M"],
        ["?", "M"],
        ["N", "N"],
        ["N", "N"],
        ["N", "N"],
        ["?", "N"],
        ["?", "N"],
        ["?", "N"],
        ["?", "N"],
        ["?", "N"],
        ["?", "N"],
        ["?", "N"],
        ["?", "N"],
        ["Ñ", "N"],
        ["?", "NJ"],
        ["Ó", "O"],
        ["O", "O"],
        ["O", "O"],
        ["Ô", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["Ö", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["O", "O"],
        ["?", "O"],
        ["Ò", "O"],
        ["?", "O"],
        ["O", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["O", "O"],
        ["?", "O"],
        ["?", "O"],
        ["O", "O"],
        ["O", "O"],
        ["O", "O"],
        ["Ø", "O"],
        ["?", "O"],
        ["Õ", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "O"],
        ["?", "OI"],
        ["?", "OO"],
        ["?", "E"],
        ["?", "O"],
        ["?", "OU"],
        ["?", "P"],
        ["?", "P"],
        ["?", "P"],
        ["?", "P"],
        ["?", "P"],
        ["?", "P"],
        ["?", "P"],
        ["?", "Q"],
        ["?", "Q"],
        ["R", "R"],
        ["R", "R"],
        ["R", "R"],
        ["?", "R"],
        ["?", "R"],
        ["?", "R"],
        ["?", "R"],
        ["?", "R"],
        ["?", "R"],
        ["?", "R"],
        ["?", "R"],
        ["?", "C"],
        ["?", "E"],
        ["S", "S"],
        ["?", "S"],
        ["Š", "S"],
        ["?", "S"],
        ["S", "S"],
        ["S", "S"],
        ["?", "S"],
        ["?", "S"],
        ["?", "S"],
        ["?", "S"],
        ["T", "T"],
        ["T", "T"],
        ["?", "T"],
        ["?", "T"],
        ["?", "T"],
        ["?", "T"],
        ["?", "T"],
        ["?", "T"],
        ["?", "T"],
        ["T", "T"],
        ["T", "T"],
        ["?", "A"],
        ["?", "L"],
        ["?", "M"],
        ["?", "V"],
        ["?", "TZ"],
        ["Ú", "U"],
        ["U", "U"],
        ["U", "U"],
        ["Û", "U"],
        ["?", "U"],
        ["Ü", "U"],
        ["U", "U"],
        ["U", "U"],
        ["U", "U"],
        ["U", "U"],
        ["?", "U"],
        ["?", "U"],
        ["U", "U"],
        ["?", "U"],
        ["Ù", "U"],
        ["?", "U"],
        ["U", "U"],
        ["?", "U"],
        ["?", "U"],
        ["?", "U"],
        ["?", "U"],
        ["?", "U"],
        ["?", "U"],
        ["U", "U"],
        ["?", "U"],
        ["U", "U"],
        ["U", "U"],
        ["U", "U"],
        ["?", "U"],
        ["?", "U"],
        ["?", "V"],
        ["?", "V"],
        ["?", "V"],
        ["?", "V"],
        ["?", "VY"],
        ["?", "W"],
        ["W", "W"],
        ["?", "W"],
        ["?", "W"],
        ["?", "W"],
        ["?", "W"],
        ["?", "W"],
        ["?", "X"],
        ["?", "X"],
        ["Ý", "Y"],
        ["Y", "Y"],
        ["Ÿ", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["?", "Y"],
        ["Z", "Z"],
        ["Ž", "Z"],
        ["?", "Z"],
        ["?", "Z"],
        ["Z", "Z"],
        ["?", "Z"],
        ["?", "Z"],
        ["?", "Z"],
        ["?", "Z"],
        ["?", "IJ"],
        ["Œ", "OE"],
        ["?", "A"],
        ["?", "AE"],
        ["?", "B"],
        ["?", "B"],
        ["?", "C"],
        ["?", "D"],
        ["?", "E"],
        ["?", "F"],
        ["?", "G"],
        ["?", "G"],
        ["?", "H"],
        ["?", "I"],
        ["?", "R"],
        ["?", "J"],
        ["?", "K"],
        ["?", "L"],
        ["?", "L"],
        ["?", "M"],
        ["?", "N"],
        ["?", "O"],
        ["?", "OE"],
        ["?", "O"],
        ["?", "OU"],
        ["?", "P"],
        ["?", "R"],
        ["?", "N"],
        ["?", "R"],
        ["?", "S"],
        ["?", "T"],
        ["?", "E"],
        ["?", "R"],
        ["?", "U"],
        ["?", "V"],
        ["?", "W"],
        ["?", "Y"],
        ["?", "Z"],
        ["á", "a"],
        ["a", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["a", "a"],
        ["â", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["ä", "a"],
        ["a", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["à", "a"],
        ["?", "a"],
        ["?", "a"],
        ["a", "a"],
        ["a", "a"],
        ["?", "a"],
        ["?", "a"],
        ["å", "a"],
        ["?", "a"],
        ["?", "a"],
        ["?", "a"],
        ["ã", "a"],
        ["?", "aa"],
        ["æ", "ae"],
        ["?", "ae"],
        ["?", "ae"],
        ["?", "ao"],
        ["?", "au"],
        ["?", "av"],
        ["?", "av"],
        ["?", "ay"],
        ["?", "b"],
        ["?", "b"],
        ["?", "b"],
        ["?", "b"],
        ["?", "b"],
        ["?", "b"],
        ["b", "b"],
        ["?", "b"],
        ["?", "o"],
        ["c", "c"],
        ["c", "c"],
        ["ç", "c"],
        ["?", "c"],
        ["c", "c"],
        ["?", "c"],
        ["c", "c"],
        ["?", "c"],
        ["?", "c"],
        ["d", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["?", "d"],
        ["d", "d"],
        ["?", "d"],
        ["?", "d"],
        ["i", "i"],
        ["?", "j"],
        ["?", "j"],
        ["?", "j"],
        ["?", "dz"],
        ["?", "dz"],
        ["é", "e"],
        ["e", "e"],
        ["e", "e"],
        ["?", "e"],
        ["?", "e"],
        ["ê", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "e"],
        ["ë", "e"],
        ["e", "e"],
        ["?", "e"],
        ["?", "e"],
        ["è", "e"],
        ["?", "e"],
        ["?", "e"],
        ["e", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "e"],
        ["e", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "e"],
        ["?", "et"],
        ["?", "f"],
        ["ƒ", "f"],
        ["?", "f"],
        ["?", "f"],
        ["?", "g"],
        ["g", "g"],
        ["g", "g"],
        ["g", "g"],
        ["g", "g"],
        ["g", "g"],
        ["?", "g"],
        ["?", "g"],
        ["?", "g"],
        ["g", "g"],
        ["?", "h"],
        ["?", "h"],
        ["?", "h"],
        ["h", "h"],
        ["?", "h"],
        ["?", "h"],
        ["?", "h"],
        ["?", "h"],
        ["?", "h"],
        ["?", "h"],
        ["h", "h"],
        ["?", "hv"],
        ["í", "i"],
        ["i", "i"],
        ["i", "i"],
        ["î", "i"],
        ["ï", "i"],
        ["?", "i"],
        ["?", "i"],
        ["?", "i"],
        ["ì", "i"],
        ["?", "i"],
        ["?", "i"],
        ["i", "i"],
        ["i", "i"],
        ["?", "i"],
        ["?", "i"],
        ["i", "i"],
        ["?", "i"],
        ["?", "d"],
        ["?", "f"],
        ["?", "g"],
        ["?", "r"],
        ["?", "s"],
        ["?", "t"],
        ["?", "is"],
        ["j", "j"],
        ["j", "j"],
        ["?", "j"],
        ["?", "j"],
        ["?", "k"],
        ["k", "k"],
        ["k", "k"],
        ["?", "k"],
        ["?", "k"],
        ["?", "k"],
        ["?", "k"],
        ["?", "k"],
        ["?", "k"],
        ["?", "k"],
        ["?", "k"],
        ["l", "l"],
        ["l", "l"],
        ["?", "l"],
        ["l", "l"],
        ["l", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["?", "l"],
        ["l", "l"],
        ["?", "lj"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "m"],
        ["?", "m"],
        ["?", "m"],
        ["?", "m"],
        ["?", "m"],
        ["?", "m"],
        ["n", "n"],
        ["n", "n"],
        ["n", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["?", "n"],
        ["ñ", "n"],
        ["?", "nj"],
        ["ó", "o"],
        ["o", "o"],
        ["o", "o"],
        ["ô", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["ö", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["o", "o"],
        ["?", "o"],
        ["ò", "o"],
        ["?", "o"],
        ["o", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["o", "o"],
        ["?", "o"],
        ["?", "o"],
        ["o", "o"],
        ["o", "o"],
        ["ø", "o"],
        ["?", "o"],
        ["õ", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "o"],
        ["?", "oi"],
        ["?", "oo"],
        ["?", "e"],
        ["?", "e"],
        ["?", "o"],
        ["?", "o"],
        ["?", "ou"],
        ["?", "p"],
        ["?", "p"],
        ["?", "p"],
        ["?", "p"],
        ["?", "p"],
        ["?", "p"],
        ["?", "p"],
        ["?", "p"],
        ["?", "p"],
        ["?", "q"],
        ["?", "q"],
        ["?", "q"],
        ["?", "q"],
        ["r", "r"],
        ["r", "r"],
        ["r", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "c"],
        ["?", "c"],
        ["?", "e"],
        ["?", "r"],
        ["s", "s"],
        ["?", "s"],
        ["š", "s"],
        ["?", "s"],
        ["s", "s"],
        ["s", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["?", "s"],
        ["g", "g"],
        ["?", "o"],
        ["?", "o"],
        ["?", "u"],
        ["t", "t"],
        ["t", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["?", "t"],
        ["t", "t"],
        ["?", "t"],
        ["t", "t"],
        ["?", "th"],
        ["?", "a"],
        ["?", "ae"],
        ["?", "e"],
        ["?", "g"],
        ["?", "h"],
        ["?", "h"],
        ["?", "h"],
        ["?", "i"],
        ["?", "k"],
        ["?", "l"],
        ["?", "m"],
        ["?", "m"],
        ["?", "oe"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "r"],
        ["?", "t"],
        ["?", "v"],
        ["?", "w"],
        ["?", "y"],
        ["?", "tz"],
        ["ú", "u"],
        ["u", "u"],
        ["u", "u"],
        ["û", "u"],
        ["?", "u"],
        ["ü", "u"],
        ["u", "u"],
        ["u", "u"],
        ["u", "u"],
        ["u", "u"],
        ["?", "u"],
        ["?", "u"],
        ["u", "u"],
        ["?", "u"],
        ["ù", "u"],
        ["?", "u"],
        ["u", "u"],
        ["?", "u"],
        ["?", "u"],
        ["?", "u"],
        ["?", "u"],
        ["?", "u"],
        ["?", "u"],
        ["u", "u"],
        ["?", "u"],
        ["u", "u"],
        ["?", "u"],
        ["u", "u"],
        ["u", "u"],
        ["?", "u"],
        ["?", "u"],
        ["?", "ue"],
        ["?", "um"],
        ["?", "v"],
        ["?", "v"],
        ["?", "v"],
        ["?", "v"],
        ["?", "v"],
        ["?", "v"],
        ["?", "v"],
        ["?", "vy"],
        ["?", "w"],
        ["w", "w"],
        ["?", "w"],
        ["?", "w"],
        ["?", "w"],
        ["?", "w"],
        ["?", "w"],
        ["?", "w"],
        ["?", "x"],
        ["?", "x"],
        ["?", "x"],
        ["ý", "y"],
        ["y", "y"],
        ["ÿ", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["?", "y"],
        ["z", "z"],
        ["ž", "z"],
        ["?", "z"],
        ["?", "z"],
        ["?", "z"],
        ["z", "z"],
        ["?", "z"],
        ["?", "z"],
        ["?", "z"],
        ["?", "z"],
        ["?", "z"],
        ["?", "z"],
        ["z", "z"],
        ["?", "z"],
        ["?", "ff"],
        ["?", "ffi"],
        ["?", "ffl"],
        ["?", "fi"],
        ["?", "fl"],
        ["?", "ij"],
        ["œ", "oe"],
        ["?", "st"],
        ["?", "a"],
        ["?", "e"],
        ["?", "i"],
        ["?", "j"],
        ["?", "o"],
        ["?", "r"],
        ["?", "u"],
        ["?", "v"],
        ["?", "x"],
    ]);

Can I use Twitter Bootstrap and jQuery UI at the same time?

The data-role="none" is the key to make them work together. You can apply to the elements you want bootstrap to touch but jquery mobile to ignore. like this input type="text" class="form-control" placeholder="Search" data-role="none"

In oracle, how do I change my session to display UTF8?

The character set is part of the locale, which is determined by the value of NLS_LANG. As the documentation makes clear this is an operating system variable:

NLS_LANG is set as an environment variable on UNIX platforms. NLS_LANG is set in the registry on Windows platforms.

Now we can use ALTER SESSION to change the values for a couple of locale elements, NLS_LANGUAGE and NLS_TERRITORY. But not, alas, the character set. The reason for this discrepancy is - I think - that the language and territory simply effect how Oracle interprets the stored data, e.g. whether to display a comma or a period when displaying a large number. Wheareas the character set is concerned with how the client application renders the displayed data. This information is picked up by the client application at startup time, and cannot be changed from within.

Django - "no module named django.core.management"

sudo pip install django --upgrade 

did the trick for me.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"

Most likely your problem was because of <scope>test</scope> (in some cases also <scope>provided</scope>), as mentioned @thangaraj.

Documentation says:

This scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases. Test dependencies aren’t transitive and are only present for test and execution classpaths.

So, if you don't need dependecies for test purposes then you can use instead of (what you will see in mvnrepository):

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-nop -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-nop</artifactId>
    <version>1.7.24</version>
    <scope>test</scope>
</dependency>

Without any scopes (by default would be compile scope when no other scope is provided):

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-nop -->
<dependency>  
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-nop</artifactId>
   <version>1.7.25</version>
</dependency>

This is the same as:

 <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-nop -->
 <dependency>  
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-nop</artifactId>
   <version>1.7.25</version>
   <scope>compile</scope>
 </dependency>

What's the difference between struct and class in .NET?

+------------------------+------------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------+
|                        |                                                Struct                                                |                                               Class                                               |
+------------------------+------------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------+
| Type                   | Value-type                                                                                           | Reference-type                                                                                    |
| Where                  | On stack / Inline in containing type                                                                 | On Heap                                                                                           |
| Deallocation           | Stack unwinds / containing type gets deallocated                                                     | Garbage Collected                                                                                 |
| Arrays                 | Inline, elements are the actual instances of the value type                                          | Out of line, elements are just references to instances of the reference type residing on the heap |
| Aldel Cost             | Cheap allocation-deallocation                                                                        | Expensive allocation-deallocation                                                                 |
| Memory usage           | Boxed when cast to a reference type or one of the interfaces they implement,                         | No boxing-unboxing                                                                                |
|                        | Unboxed when cast back to value type                                                                 |                                                                                                   |
|                        | (Negative impact because boxes are objects that are allocated on the heap and are garbage-collected) |                                                                                                   |
| Assignments            | Copy entire data                                                                                     | Copy the reference                                                                                |
| Change to an instance  | Does not affect any of its copies                                                                    | Affect all references pointing to the instance                                                    |
| Mutability             | Should be immutable                                                                                  | Mutable                                                                                           |
| Population             | In some situations                                                                                   | Majority of types in a framework should be classes                                                |
| Lifetime               | Short-lived                                                                                          | Long-lived                                                                                        |
| Destructor             | Cannot have                                                                                          | Can have                                                                                          |
| Inheritance            | Only from an interface                                                                               | Full support                                                                                      |
| Polymorphism           | No                                                                                                   | Yes                                                                                               |
| Sealed                 | Yes                                                                                                  | When have sealed keyword                                                                          |
| Constructor            | Can not have explicit parameterless constructors                                                     | Any constructor                                                                                   |
| Null-assignments       | When marked with nullable question mark                                                              | Yes (+ When marked with nullable question mark in C# 8+)                                          |
| Abstract               | No                                                                                                   | When have abstract keyword                                                                        |
| Member Access Modifiers| public, private, internal                                                                            | public, protected, internal, protected internal, private protected                                |
+------------------------+------------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------+

jquery animate background position

You can change the image background position using setInterval method, see demo here: http://jquerydemo.com/demo/animate-background-image.aspx

How do I install Python OpenCV through Conda?

If you want to install opencv 3.4.0, there, unfortunately, is not this version inside conda. You need to use pip instead.

pip install opencv-python==3.4.0.12

What is the difference between DSA and RSA?

Referring, https://web.archive.org/web/20140212143556/http://courses.cs.tamu.edu:80/pooch/665_spring2008/Australian-sec-2006/less19.html

RSA
RSA encryption and decryption are commutative
hence it may be used directly as a digital signature scheme
given an RSA scheme {(e,R), (d,p,q)}
to sign a message M, compute:
S = M power d (mod R)
to verify a signature, compute:
M = S power e(mod R) = M power e.d(mod R) = M(mod R)

RSA can be used both for encryption and digital signatures, simply by reversing the order in which the exponents are used: the secret exponent (d) to create the signature, the public exponent (e) for anyone to verify the signature. Everything else is identical.

DSA (Digital Signature Algorithm)
DSA is a variant on the ElGamal and Schnorr algorithms. It creates a 320 bit signature, but with 512-1024 bit security again rests on difficulty of computing discrete logarithms has been quite widely accepted.

DSA Key Generation
firstly shared global public key values (p,q,g) are chosen:
choose a large prime p = 2 power L
where L= 512 to 1024 bits and is a multiple of 64
choose q, a 160 bit prime factor of p-1
choose g = h power (p-1)/q
for any h<p-1, h(p-1)/q(mod p)>1
then each user chooses a private key and computes their public key:
choose x<q
compute y = g power x(mod p)

DSA key generation is related to, but somewhat more complex than El Gamal. Mostly because of the use of the secondary 160-bit modulus q used to help speed up calculations and reduce the size of the resulting signature.

DSA Signature Creation and Verification

to sign a message M
generate random signature key k, k<q
compute
r = (g power k(mod p))(mod q)
s = k-1.SHA(M)+ x.r (mod q)
send signature (r,s) with message

to verify a signature, compute:
w = s-1(mod q)
u1= (SHA(M).w)(mod q)
u2= r.w(mod q)
v = (g power u1.y power u2(mod p))(mod q)
if v=r then the signature is verified

Signature creation is again similar to ElGamal with the use of a per message temporary signature key k, but doing calc first mod p, then mod q to reduce the size of the result. Note that the use of the hash function SHA is explicit here. Verification also consists of comparing two computations, again being a bit more complex than, but related to El Gamal.
Note that nearly all the calculations are mod q, and hence are much faster.
But, In contrast to RSA, DSA can be used only for digital signatures

DSA Security
The presence of a subliminal channel exists in many schemes (any that need a random number to be chosen), not just DSA. It emphasises the need for "system security", not just a good algorithm.

In Bash, how do I add a string after each line in a file?

If your sed allows in place editing via the -i parameter:

sed -e 's/$/string after each line/' -i filename

If not, you have to make a temporary file:

typeset TMP_FILE=$( mktemp )

touch "${TMP_FILE}"
cp -p filename "${TMP_FILE}"
sed -e 's/$/string after each line/' "${TMP_FILE}" > filename

How to check if a specific key is present in a hash or not?

You can always use Hash#key? to check if the key is present in a hash or not.

If not it will return you false

hash =  { one: 1, two:2 }

hash.key?(:one)
#=> true

hash.key?(:four)
#=> false

Traversing text in Insert mode

You could use imap to map any key in insert mode to one of the cursor keys. Like so:

imap h <Left>

Now h works like in normal mode, moving the cursor. (Mapping h in this way is obviously a bad choice)

Having said that I do not think the standard way of moving around in text using VIM is "not productive". There are lots of very powerful ways of traversing the text in normal mode (like using w and b, or / and ?, or f and F, etc.)

Calling Non-Static Method In Static Method In Java

Constructor is a special method which in theory is the "only" non-static method called by any static method. else its not allowed.

PDO's query vs execute

query runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.

execute runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute will also perform better if you are repeating a query multiple times. Example of prepared statements:

$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories);
$sth->bindParam(':colour', $colour);
$sth->execute();
// $calories or $color do not need to be escaped or quoted since the
//    data is separated from the query

Best practice is to stick with prepared statements and execute for increased security.

See also: Are PDO prepared statements sufficient to prevent SQL injection?

Extract substring using regexp in plain bash

Quick 'n dirty, regex-free, low-robustness chop-chop technique

string="US/Central - 10:26 PM (CST)"
etime="${string% [AP]M*}"
etime="${etime#* - }"

How to return data from PHP to a jQuery ajax call

It's an argument passed to your success function:

$.ajax({
  type: "POST",
  url: "somescript.php",
  datatype: "html",
  data: dataString,
  success: function(data) {
    alert(data);
    }
});

The full signature is success(data, textStatus, XMLHttpRequest), but you can use just he first argument if it's a simple string coming back. As always, see the docs for a full explanation :)

How to bind bootstrap popover on dynamic elements

Update

If your popover is going to have a selector that is consistent then you can make use of selector property of popover constructor.

var popOverSettings = {
    placement: 'bottom',
    container: 'body',
    html: true,
    selector: '[rel="popover"]', //Sepcify the selector here
    content: function () {
        return $('#popover-content').html();
    }
}

$('body').popover(popOverSettings);

Demo

Other ways:

  1. (Standard Way) Bind the popover again to the new items being inserted. Save the popoversettings in an external variable.
  2. Use Mutation Event/Mutation Observer to identify if a particular element has been inserted on to the ul or an element.

Source

var popOverSettings = { //Save the setting for later use as well
    placement: 'bottom',
    container: 'body',
    html: true,
    //content:" <div style='color:red'>This is your div content</div>"
    content: function () {
        return $('#popover-content').html();
    }

}

$('ul').on('DOMNodeInserted', function () { //listed for new items inserted onto ul
    $(event.target).popover(popOverSettings);
});

$("button[rel=popover]").popover(popOverSettings);
$('.pop-Add').click(function () {
    $('ul').append("<li class='project-name'>     <a>project name 2        <button class='pop-function' rel='popover'></button>     </a>   </li>");
});

But it is not recommended to use DOMNodeInserted Mutation Event for performance issues as well as support. This has been deprecated as well. So your best bet would be to save the setting and bind after you update with new element.

Demo

Another recommended way is to use MutationObserver instead of MutationEvent according to MDN, but again support in some browsers are unknown and performance a concern.

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
// create an observer instance
var observer = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
        $(mutation.addedNodes).popover(popOverSettings);
    });
});

// configuration of the observer:
var config = {
     attributes: true, 
     childList: true, 
     characterData: true
};

// pass in the target node, as well as the observer options
observer.observe($('ul')[0], config);

Demo

How do I check if an HTML element is empty using jQuery?

White space and line breaks are the main issues with using :empty selector. Careful, in CSS the :empty pseudo class behaves the same way. I like this method:

if ($someElement.children().length == 0){
     someAction();
}

How to include "zero" / "0" results in COUNT aggregate?

The problem with a LEFT JOIN is that if there are no appointments, it will still return one row with a null, which when aggregated by COUNT will become 1, and it will appear that the person has one appointment when actually they have none. I think this will give the correct results:

SELECT person.person_id,
(SELECT COUNT(*) FROM appointment WHERE person.person_id = appointment.person_id) AS 'Appointments'
FROM person;

How to convert unsigned long to string

The standard approach is to use sprintf(buffer, "%lu", value); to write a string rep of value to buffer. However, overflow is a potential problem, as sprintf will happily (and unknowingly) write over the end of your buffer.

This is actually a big weakness of sprintf, partially fixed in C++ by using streams rather than buffers. The usual "answer" is to allocate a very generous buffer unlikely to overflow, let sprintf output to that, and then use strlen to determine the actual string length produced, calloc a buffer of (that size + 1) and copy the string to that.

This site discusses this and related problems at some length.

Some libraries offer snprintf as an alternative which lets you specify a maximum buffer size.

Fix GitLab error: "you are not allowed to push code to protected branches on this project"?

Simple solution for this problem to have quick chat with person who has owner role in gitlab. He can push one file READ.md or similar to just start with. Later, everything will be working as earlier.

Error when testing on iOS simulator: Couldn't register with the bootstrap server

Well, no answers but at least one more test to make. Open Terminal and run this command: "ps-Ael | grep Z". If you get two entries, one "(clang)" and the other your app or company name, you're hosed - reboot.

If you are a developer, enter a short bug and tell Apple how absolutely annoying having to reboot is, and mention they can dup this bug to "rdar://10401934" which I just entered.

David

Faster way to zero memory than with memset?

That's an interesting question. I made this implementation that is just slightly faster (but hardly measurable) when 32-bit release compiling on VC++ 2012. It probably can be improved on a lot. Adding this in your own class in a multithreaded environment would probably give you even more performance gains since there are some reported bottleneck problems with memset() in multithreaded scenarios.

// MemsetSpeedTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include "Windows.h"
#include <time.h>

#pragma comment(lib, "Winmm.lib") 
using namespace std;

/** a signed 64-bit integer value type */
#define _INT64 __int64

/** a signed 32-bit integer value type */
#define _INT32 __int32

/** a signed 16-bit integer value type */
#define _INT16 __int16

/** a signed 8-bit integer value type */
#define _INT8 __int8

/** an unsigned 64-bit integer value type */
#define _UINT64 unsigned _INT64

/** an unsigned 32-bit integer value type */
#define _UINT32 unsigned _INT32

/** an unsigned 16-bit integer value type */
#define _UINT16 unsigned _INT16

/** an unsigned 8-bit integer value type */
#define _UINT8 unsigned _INT8

/** maximum allo

wed value in an unsigned 64-bit integer value type */
    #define _UINT64_MAX 18446744073709551615ULL

#ifdef _WIN32

/** Use to init the clock */
#define TIMER_INIT LARGE_INTEGER frequency;LARGE_INTEGER t1, t2;double elapsedTime;QueryPerformanceFrequency(&frequency);

/** Use to start the performance timer */
#define TIMER_START QueryPerformanceCounter(&t1);

/** Use to stop the performance timer and output the result to the standard stream. Less verbose than \c TIMER_STOP_VERBOSE */
#define TIMER_STOP QueryPerformanceCounter(&t2);elapsedTime=(t2.QuadPart-t1.QuadPart)*1000.0/frequency.QuadPart;wcout<<elapsedTime<<L" ms."<<endl;
#else
/** Use to init the clock */
#define TIMER_INIT clock_t start;double diff;

/** Use to start the performance timer */
#define TIMER_START start=clock();

/** Use to stop the performance timer and output the result to the standard stream. Less verbose than \c TIMER_STOP_VERBOSE */
#define TIMER_STOP diff=(clock()-start)/(double)CLOCKS_PER_SEC;wcout<<fixed<<diff<<endl;
#endif    


void *MemSet(void *dest, _UINT8 c, size_t count)
{
    size_t blockIdx;
    size_t blocks = count >> 3;
    size_t bytesLeft = count - (blocks << 3);
    _UINT64 cUll = 
        c 
        | (((_UINT64)c) << 8 )
        | (((_UINT64)c) << 16 )
        | (((_UINT64)c) << 24 )
        | (((_UINT64)c) << 32 )
        | (((_UINT64)c) << 40 )
        | (((_UINT64)c) << 48 )
        | (((_UINT64)c) << 56 );

    _UINT64 *destPtr8 = (_UINT64*)dest;
    for (blockIdx = 0; blockIdx < blocks; blockIdx++) destPtr8[blockIdx] = cUll;

    if (!bytesLeft) return dest;

    blocks = bytesLeft >> 2;
    bytesLeft = bytesLeft - (blocks << 2);

    _UINT32 *destPtr4 = (_UINT32*)&destPtr8[blockIdx];
    for (blockIdx = 0; blockIdx < blocks; blockIdx++) destPtr4[blockIdx] = (_UINT32)cUll;

    if (!bytesLeft) return dest;

    blocks = bytesLeft >> 1;
    bytesLeft = bytesLeft - (blocks << 1);

    _UINT16 *destPtr2 = (_UINT16*)&destPtr4[blockIdx];
    for (blockIdx = 0; blockIdx < blocks; blockIdx++) destPtr2[blockIdx] = (_UINT16)cUll;

    if (!bytesLeft) return dest;

    _UINT8 *destPtr1 = (_UINT8*)&destPtr2[blockIdx];
    for (blockIdx = 0; blockIdx < bytesLeft; blockIdx++) destPtr1[blockIdx] = (_UINT8)cUll;

    return dest;
}

int _tmain(int argc, _TCHAR* argv[])
{
    TIMER_INIT

    const size_t n = 10000000;
    const _UINT64 m = _UINT64_MAX;
    const _UINT64 o = 1;
    char test[n];
    {
        cout << "memset()" << endl;
        TIMER_START;

        for (int i = 0; i < m ; i++)
            for (int j = 0; j < o ; j++)
                memset((void*)test, 0, n);  

        TIMER_STOP;
    }
    {
        cout << "MemSet() took:" << endl;
        TIMER_START;

        for (int i = 0; i < m ; i++)
            for (int j = 0; j < o ; j++)
                MemSet((void*)test, 0, n);

        TIMER_STOP;
    }

    cout << "Done" << endl;
    int wait;
    cin >> wait;
    return 0;
}

Output is as follows when release compiling for 32-bit systems:

memset() took:
5.569000
MemSet() took:
5.544000
Done

Output is as follows when release compiling for 64-bit systems:

memset() took:
2.781000
MemSet() took:
2.765000
Done

Here you can find the source code Berkley's memset(), which I think is the most common implementation.

Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

There are a few functions like:

NSStringFromCGPoint  
NSStringFromCGSize  
NSStringFromCGRect  
NSStringFromCGAffineTransform  
NSStringFromUIEdgeInsets

An example:

NSLog(@"rect1: %@", NSStringFromCGRect(rect1));

scp from remote host to local host

There must be a user in the AllowUsers section, in the config file /etc/ssh/ssh_config, in the remote machine. You might have to restart sshd after editing the config file.

And then you can copy for example the file "test.txt" from a remote host to the local host

scp [email protected]:test.txt /local/dir


@cool_cs you can user ~ symbol ~/Users/djorge/Desktop if it's your home dir.

In UNIX, absolute paths must start with '/'.

How to select specific columns in laravel eloquent

you can also used findOrFail() method here it's good to used

if the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these method not give a 500 error..

ModelName::findOrFail($id, ['firstName', 'lastName']);

Run javascript script (.js file) in mongodb including another file inside js

Use Load function

load(filename)

You can directly call any .js file from the mongo shell, and mongo will execute the JavaScript.

Example : mongo localhost:27017/mydb myfile.js

This executes the myfile.js script in mongo shell connecting to mydb database with port 27017 in localhost.

For loading external js you can write

load("/data/db/scripts/myloadjs.js")

Suppose we have two js file myFileOne.js and myFileTwo.js

myFileOne.js

print('From file 1');
load('myFileTwo.js');     // Load other js file .

myFileTwo.js

print('From file 2');

MongoShell

>mongo myFileOne.js

Output

From file 1
From file 2

Can I get div's background-image url?

I think that using a regular expression for this is faulty mainly due to

  • The simplicity of the task
  • Running a regular expression is always more cpu intensive/longer than cutting a string.

Since the url(" and ") components are constant, trim your string like so:

$("#id").click(function() {
     var bg = $(this).css('background-image').trim();
     var res = bg.substring(5, bg.length - 2);
     alert(res);
});

CSS3's border-radius property and border-collapse:collapse don't mix. How can I use border-radius to create a collapsed table with rounded corners?

I always do this way using Sass

table {
  border-radius: 0.25rem;
  thead tr:first-child th {
    &:first-child {
      border-top-left-radius: 0.25rem;
    }
    &:last-child {
      border-top-right-radius: 0.25rem;
    }
  }
  tbody tr:last-child td {
    &:first-child {
      border-bottom-left-radius: 0.25rem;
    }
    &:last-child {
      border-bottom-right-radius: 0.25rem;
    }
  }
}

Generate preview image from Video file?

I recommend php-ffmpeg library.

Extracting image

You can extract a frame at any timecode using the FFMpeg\Media\Video::frame method.

This code returns a FFMpeg\Media\Frame instance corresponding to the second 42. You can pass any FFMpeg\Coordinate\TimeCode as argument, see dedicated documentation below for more information.

$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(42));
$frame->save('image.jpg');

If you want to extract multiple images from the video, you can use the following filter:

$video
    ->filters()
    ->extractMultipleFrames(FFMpeg\Filters\Video\ExtractMultipleFramesFilter::FRAMERATE_EVERY_10SEC, '/path/to/destination/folder/')
    ->synchronize();

$video
    ->save(new FFMpeg\Format\Video\X264(), '/path/to/new/file');

By default, this will save the frames as jpg images.

You are able to override this using setFrameFileType to save the frames in another format:

$frameFileType = 'jpg'; // either 'jpg', 'jpeg' or 'png'
$filter = new ExtractMultipleFramesFilter($frameRate, $destinationFolder);
$filter->setFrameFileType($frameFileType);

$video->addFilter($filter);

GET URL parameter in PHP

To make sure you're always on the safe side, without getting all kinds of unwanted code insertion use FILTERS:

echo filter_input(INPUT_GET,"link",FILTER_SANITIZE_STRING);

More reading on php.net function filter_input, or check out the description of the different filters

Why is Event.target not Element in Typescript?

I use this:

onClick({ target }: MouseEvent) => {
    const targetDivElement: HTMLDivElement = target as HTMLDivElement;
    
    const listFullHeight: number = targetDivElement.scrollHeight;
    const listVisibleHeight: number = targetDivElement.offsetHeight;
    const listTopScroll: number = targetDivElement.scrollTop;
}

Resize background image in div using css

With the background-size property in those browsers which support this very new feature of CSS.

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)

You need to enable virtualization using BIOS setup.

step 1. Restart your PC and when your PC booting up then press your BIOS setup key (F1 or F2 or google it your BIOS setup key).

step 2. Go to the security menu.

step 3. Select virtualization and enable it.

Note:- BIOS setup depends on PC Manufacturer-brand.

jQuery Ajax PUT with parameters

Can you provide an example, because put should work fine as well?

Documentation -

The type of request to make ("POST" or "GET"); the default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

Have the example in fiddle and the form parameters are passed fine (as it is put it will not be appended to url) -

$.ajax({
  url: '/echo/html/',
  type: 'PUT',
  data: "name=John&location=Boston",
  success: function(data) {
    alert('Load was performed.');
  }
});

Demo tested from jQuery 1.3.2 onwards on Chrome.

Batchfile to create backup and rename with timestamp

See if this is what you want to do:

@echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime  ^| find "."') do set dt=%%a
set YYYY=%dt:~0,4%
set MM=%dt:~4,2%
set DD=%dt:~6,2%
set HH=%dt:~8,2%
set Min=%dt:~10,2%
set Sec=%dt:~12,2%

set stamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%

copy "F:\Folder\File 1.xlsx" "F:\Folder\Archive\File 1 - %stamp%.xlsx"

#define macro for debug printing in C?

So, when using gcc, I like:

#define DBGI(expr) ({int g2rE3=expr; fprintf(stderr, "%s:%d:%s(): ""%s->%i\n", __FILE__,  __LINE__, __func__, #expr, g2rE3); g2rE3;})

Because it can be inserted into code.

Suppose you're trying to debug

printf("%i\n", (1*2*3*4*5*6));

720

Then you can change it to:

printf("%i\n", DBGI(1*2*3*4*5*6));

hello.c:86:main(): 1*2*3*4*5*6->720
720

And you can get an analysis of what expression was evaluated to what.

It's protected against the double-evaluation problem, but the absence of gensyms does leave it open to name-collisions.

However it does nest:

DBGI(printf("%i\n", DBGI(1*2*3*4*5*6)));

hello.c:86:main(): 1*2*3*4*5*6->720
720
hello.c:86:main(): printf("%i\n", DBGI(1*2*3*4*5*6))->4

So I think that as long as you avoid using g2rE3 as a variable name, you'll be OK.

Certainly I've found it (and allied versions for strings, and versions for debug levels etc) invaluable.

Select Pandas rows based on list index

ind_list = [1, 3]
df.ix[ind_list]

should do the trick! When I index with data frames I always use the .ix() method. Its so much easier and more flexible...

UPDATE This is no longer the accepted method for indexing. The ix method is deprecated. Use .iloc for integer based indexing and .loc for label based indexing.

Server certificate verification failed: issuer is not trusted

during command line works. I'm using Ant to commit an artifact after build completes. Experienced the same issue... Manually excepting the cert did not work (Jenkins is funny that way). Add these options to your svn command:

--non-interactive

--trust-server-cert

The executable was signed with invalid entitlements

Code signing entitlements are no longer necessary for Ad Hoc builds in Xcode 4 - see details notes in Apple Technical Note TN2250

How to recover Git objects damaged by hard disk failure?

Here are two functions that may help if your backup is corrupted, or you have a few partially corrupted backups as well (this may happen if you backup the corrupted objects).

Run both in the repo you're trying to recover.

Standard warning: only use if you're really desperate and you have backed up your (corrupted) repo. This might not resolve anything, but at least should highlight the level of corruption.

fsck_rm_corrupted() {
    corrupted='a'
    while [ "$corrupted" ]; do
        corrupted=$(                                  \
        git fsck --full --no-dangling 2>&1 >/dev/null \
            | grep 'stored in'                          \
            | sed -r 's:.*(\.git/.*)\).*:\1:'           \
        )
        echo "$corrupted"
        rm -f "$corrupted"
    done
}

if [ -z "$1" ]  || [ ! -d "$1" ]; then
    echo "'$1' is not a directory. Please provide the directory of the git repo"
    exit 1
fi

pushd "$1" >/dev/null
fsck_rm_corrupted
popd >/dev/null

and

unpack_rm_corrupted() {
    corrupted='a'
    while [ "$corrupted" ]; do
        corrupted=$(                                  \
        git unpack-objects -r < "$1" 2>&1 >/dev/null \
            | grep 'stored in'                          \
            | sed -r 's:.*(\.git/.*)\).*:\1:'           \
        )
        echo "$corrupted"
        rm -f "$corrupted"
    done
}

if [ -z "$1" ]  || [ ! -d "$1" ]; then
    echo "'$1' is not a directory. Please provide the directory of the git repo"
    exit 1
fi

for p in $1/objects/pack/pack-*.pack; do
    echo "$p"
    unpack_rm_corrupted "$p"
done

Download files from server php

To read directory contents you can use readdir() and use a script, in my example download.php, to download files

if ($handle = opendir('/path/to/your/dir/')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "<a href='download.php?file=".$entry."'>".$entry."</a>\n";
        }
    }
    closedir($handle);
}

In download.php you can force browser to send download data, and use basename() to make sure client does not pass other file name like ../config.php

$file = basename($_GET['file']);
$file = '/path/to/your/dir/'.$file;

if(!file_exists($file)){ // file does not exist
    die('file not found');
} else {
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$file");
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: binary");

    // read the file from disk
    readfile($file);
}

How to get First and Last record from a sql query?

First record:

SELECT <some columns> FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date ASC
LIMIT 1

Last record:

SELECT <some columns> FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date DESC
LIMIT 1

How to import JsonConvert in C# application?

After instaling the package you need to add the newtonsoft.json.dll into assemble path by runing the flowing command.

Before we can use our assembly, we have to add it to the global assembly cache (GAC). Open the Visual Studio 2008 Command Prompt again (for Vista/Windows7/etc. open it as Administrator). And execute the following command. gacutil /i d:\myMethodsForSSIS\myMethodsForSSIS\bin\Release\myMethodsForSSIS.dll

flow this link for more informATION http://microsoft-ssis.blogspot.com/2011/05/referencing-custom-assembly-inside.html

Prevent BODY from scrolling when a modal is opened

Sadly none of the answers above fixed my issues.

In my situation, the web page originally has a scroll bar. Whenever I click the modal, the scroll bar won't disappear and the header will move to right a bit.

Then I tried to add .modal-open{overflow:auto;} (which most people recommended). It indeed fixed the issues: the scroll bar appears after I open the modal. However, another side effect comes out which is that "background below the header will move to the left a bit, together with another long bar behind the modal"

Long bar behind modal

Luckily, after I add {padding-right: 0 !important;}, everything is fixed perfectly. Both the header and body background didn't move and the modal still keeps the scrollbar.

Fixed image

Hope this can help those who are still stuck with this issue. Good luck!

Printing newlines with print() in R

You can do this:

cat("File not supplied.\nUsage: ./program F=filename\n")

Notice that cat has a return value of NULL.

How to set a dropdownlist item as selected in ASP.NET?

This is a very nice and clean example:(check this great tutorial for a full explanation link)

public static IEnumerable<SelectListItem> ToSelectListItems(
              this IEnumerable<Album> albums, int selectedId)
{
    return 
        albums.OrderBy(album => album.Name)
              .Select(album => 
                  new SelectListItem
                  {
                    Selected = (album.ID == selectedId),
                    Text = album.Name,
                    Value = album.ID.ToString()
                   });
}

In this MSDN link you can read de DropDownList method documentation.

Hope it helps.

Calculating the position of points in a circle

Here is an R version based on the @Pirijan answer above.

points <- 8
radius <- 10
center_x <- 5
center_y <- 5

drawCirclePoints <- function(points, radius, center_x, center_y) {
  slice <- 2 * pi / points
  angle <- slice * seq(0, points, by = 1)

  newX <- center_x + radius * cos(angle)
  newY <- center_y + radius * sin(angle)

  plot(newX, newY)
}

drawCirclePoints(points, radius, center_x, center_y)

How to solve "The specified service has been marked for deletion" error

steps to follow:

step-1 goto the location C:\Windows\Microsoft.NET\Framework\v4.0.30319

step-2 run command: installutil /u full-path/servicename.exe

step-3 close services panel and reopen it

step-4 run command: installutil full-path/servicename.exe

PHP how to get local IP of system

A reliable way to get the external IP address of the local machine would be to query the routing table, although we have no direct way to do it in PHP.

However we can get the system to do it for us by binding a UDP socket to a public address, and getting its address:

$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_connect($sock, "8.8.8.8", 53);
socket_getsockname($sock, $name); // $name passed by reference

// This is the local machine's external IP address
$localAddr = $name;

socket_connect will not cause any network traffic because it's an UDP socket.

How to install pkg config in windows?

  1. Install mingw64 from https://sourceforge.net/projects/mingw-w64/. Avoid program files/(x86) folder for installation. Ex. c:/mingw-w64
  2. Download pkg-config__win64.zip from here
  3. Extract above zip file and copy paste all the files from pkg-config/bin folder to mingw-w64. In my case its 'C:\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin'
  4. Now set path = C:\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin taddaaa you are done.

If you find any security issue then follow steps as well

  1. Search for windows defender security center in system
  2. Navigate to apps & browser control> Exploit protection settings> Program setting> Click on '+add program customize'
  3. Select add program by name
  4. Enter program name: pkgconf.exe
  5. OK
  6. Now check all the settings and set it all the settings to off and apply.

Thats DONE!

ORACLE and TRIGGERS (inserted, updated, deleted)

The NEW values (or NEW_BUFFER as you have renamed them) are only available when INSERTING and UPDATING. For DELETING you would need to use OLD (OLD_BUFFER). So your trigger would become:

CREATE or REPLACE TRIGGER test001
  AFTER INSERT OR DELETE OR UPDATE ON tabletest001
  REFERENCING OLD AS old_buffer NEW AS new_buffer 
  FOR EACH ROW WHEN (new_buffer.field1 = 'HBP00' OR old_buffer.field1 = 'HBP00') 

You may need to add logic inside the trigger to cater for code that updates field1 from 'HBP000' to something else.

Jquery select this + class

Maybe something like: $(".subclass", this);

Creating a zero-filled pandas data frame

It's best to do this with numpy in my opinion

import numpy as np
import pandas as pd
d = pd.DataFrame(np.zeros((N_rows, N_cols)))

Getting the Facebook like/share count for a given URL

UPDATE: This solution is no longer valid. FQLs are deprecated since August 7th, 2016.


https://api.facebook.com/method/fql.query?query=select%20%20like_count%20from%20link_stat%20where%20url=%22http://www.techlila.com%22

Also http://api.facebook.com/restserver.php?method=links.getStats&urls=http://www.techlila.com will show you all the data like 'Share Count', 'Like Count' and 'Comment Count' and total of all these.

Change the URL (i.e. http://www.techlila.com) as per your need.

This is the correct URL, I'm getting right results.

EDIT (May 2017): as of v2.9 you can make a graph API call where ID is the URL and select the 'engagement' field, below is a link with the example from the graph explorer.

https://developers.facebook.com/tools/explorer/?method=GET&path=%3Fid%3Dhttp%3A%2F%2Fcomunidade.edp.pt%26fields%3Dengagement&version=v2.9

Get cookie by name

Get cookie by name just pass the name of cookie to below function

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i <ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

How to update values using pymongo?

in python the operators should be in quotes: db.ProductData.update({'fromAddress':'http://localhost:7000/'}, {"$set": {'fromAddress': 'http://localhost:5000/'}},{"multi": True})

Mean of a column in a data frame, given the column's name

I think what you are being asked to do (or perhaps asking yourself?) is take a character value which matches the name of a column in a particular dataframe (possibly also given as a character). There are two tricks here. Most people learn to extract columns with the "$" operator and that won't work inside a function if the function is passed a character vecor. If the function is also supposed to accept character argument then you will need to use the get function as well:

 df1 <- data.frame(a=1:10, b=11:20)
 mean_col <- function( dfrm, col ) mean( get(dfrm)[[ col ]] )
 mean_col("df1", "b")
 # [1] 15.5

There is sort of a semantic boundary between ordinary objects like character vectors and language objects like the names of objects. The get function is one of the functions that lets you "promote" character values to language level evaluation. And the "$" function will NOT evaluate its argument in a function, so you need to use"[[". "$" only is useful at the console level and needs to be completely avoided in functions.

What is a tracking branch?

TL;DR Remember, all git branches are themselves used for tracking the history of a set of files. Therefore, isn't every branch actually a "tracking branch", because that's what these branches are used for: to track the history of files over time. Thus we should probably be calling normal git "branches", "tracking-branches", but we don't. Instead we shorten their name to just "branches".

So that's partly why the term "tracking-branches" is so terribly confusing: to the uninitiated it can easily mean 2 different things.

In git the term "Tracking-branch" is a short name for the more complete term: "Remote-tracking-branch".

It's probably better at first if you substitute the more formal terms until you get more comfortable with these concepts.

Let's rephrase your question to this:

What is a "Remote-tracking-branch?"

The key word here is 'Remote', so skip down to where you get confused and I'll describe what a Remote Tracking branch is and how it's used.


To better understand git terminology, including branches and tracking, which can initially be very confusing, I think it's easiest if you first get crystal clear on what git is and the basic structure of how it works. Without a solid understand like this I promise you'll get lost in the many details, as git has lots of complexity; (translation: lots of people use it for very important things).

The following is an introduction/overview, but you might find this excellent article also informative.


WHAT GIT IS, AND WHAT IT'S FOR

A git repository is like a family photo album: It holds historical snapshots showing how things were in past times. A "snapshot" being a recording of something, at a given moment in time.

A git repository is not limited to holding human family photos. It, rather can be used to record and organize anything that is evolving or changing over time.

The basic idea is to create a book so we can easily look backwards in time,

  • to compare past times, with now, or other moments in time, and
  • to re-create the past.

When you get mired down in the complexity and terminology, try to remember that a git repository is first and foremost, a repository of snapshots, and just like a photo album, it's used to both store and organize these snapshots.


SNAPSHOTS AND TRACKING

tracked - to follow a person or animal by looking for proof that they have been somewhere (dictionary.cambridge.org)

In git, "your project" refers to a directory tree of files (one or more, possibly organized into a tree structure using sub-directories), which you wish to keep a history of.

Git, via a 3 step process, records a "snapshot" of your project's directory tree at a given moment in time.

Each git snapshot of your project, is then organized by "links" pointing to previous snapshots of your project.

One by one, link-by-link, we can look backwards in time to find any previous snapshot of you, or your heritage.

For example, we can start with today's most recent snapshot of you, and then using a link, seek backwards in time, for a photo of you taken perhaps yesterday or last week, or when you were a baby, or even who your mother was, etc.

This is refereed to as "tracking; in this example it is tracking your life, or seeing where you have left a footprint, and where you have come from.


COMMITS

A commit is similar to one page in your photo album with a single snapshot, in that its not just the snapshot contained there, but also has the associated meta information about that snapshot. It includes:

  • an address or fixed place where we can find this commit, similar to its page number,
  • one snapshot of your project (of your file directory tree) at a given moment in time,
  • a caption or comment saying what the snapshot is of, or for,
  • the date and time of that snapshot,
  • who took the snapshot, and finally,
  • one, or more, links backwards in time to previous, related snapshots like to yesterday's snapshot, or to our parent or parents. In other words "links" are similar to pointers to the page numbers of other, older photos of myself, or when I am born to my immediate parents.

A commit is the most important part of a well organized photo album.


THE FAMILY TREE OVER TIME, WITH BRANCHES AND MERGES

Disambiguation: "Tree" here refers not to a file directory tree, as used above, but rather to a family tree of related parent and child commits over time.

The git family tree structure is modeled on our own, human family trees.

In what follows to help understand links in a simple way, I'll refer to:

  • a parent-commit as simply a "parent", and
  • a child-commit as simply a "child" or "children" if plural.

You should understand this instinctively, as it is based on the tree of life:

  • A parent might have one or more children pointing back in time at them, and
  • children always have one or more parents they point to.

Thus all commits except brand new commits, (you could say "juvenile commits"), have one or more children pointing back at them.

  • With no children are pointing to a parent, then this commit is only a "growing tip", or where the next child will be born from.

  • With just one child pointing at a parent, this is just a simple, single parent <-- child relationship.

Line diagram of a simple, single parent chain linking backwards in time:

(older) ... <--link1-- Commit1 <--link2-- Commit2 <--link3-- Commit3 (newest)

BRANCHES

branch - A "branch" is an active line of development. The most recent commit on a branch is referred to as the tip of that branch. The tip of the branch is referenced by a branch head, which moves forward as additional development is done on the branch. A single Git repository can track an arbitrary number of branches, but your working tree is associated with just one of them (the "current" or "checked out" branch), and HEAD points to that branch. (gitglossary)

A git branch also refers to two things:

  • a name given to a growing tip, (an identifier), and
  • the actual branch in the graph of links between commits.

More than one child pointing --at a--> parent, is what git calls "branching".

NOTE: In reality any child, of any parent, weather first, second, or third, etc., can be seen as their own little branch, with their own growing tip. So a branch is not necessarily a long thing with many nodes, rather it is a little thing, created with just one or more commits from a given parent.

The first child of a parent might be said to be part of that same branch, whereas the successive children of that parent are what are normally called "branches".

In actuality, all children (not just the first) branch from it's parent, or you could say link, but I would argue that each link is actually the core part of a branch.

Formally, a git "branch" is just a name, like 'foo' for example, given to a specific growing tip of a family hierarchy. It's one type of what they call a "ref". (Tags and remotes which I'll explain later are also refs.)

ref - A name that begins with refs/ (e.g. refs/heads/master) that points to an object name or another ref (the latter is called a symbolic ref). For convenience, a ref can sometimes be abbreviated when used as an argument to a Git command; see gitrevisions(7) for details. Refs are stored in the repository.

The ref namespace is hierarchical. Different subhierarchies are used for different purposes (e.g. the refs/heads/ hierarchy is used to represent local branches). There are a few special-purpose refs that do not begin with refs/. The most notable example is HEAD. (gitglossary)

(You should take a look at the file tree inside your .git directory. It's where the structure of git is saved.)

So for example, if your name is Tom, then commits linked together that only include snapshots of you, might be the branch we name "Tom".

So while you might think of a tree branch as all of it's wood, in git a branch is just a name given to it's growing tips, not to the whole stick of wood leading up to it.

The special growing tip and it's branch which an arborist (a guy who prunes fruit trees) would call the "central leader" is what git calls "master".

The master branch always exists.

Line diagram of: Commit1 with 2 children (or what we call a git "branch"):

                parent      children

                        +-- Commit <-- Commit <-- Commit (Branch named 'Tom')
                       /
                      v
(older) ... <-- Commit1 <-- Commit                       (Branch named 'master')    

Remember, a link only points from child to parent. There is no link pointing the other way, i.e. from old to new, that is from parent to child.

So a parent-commit has no direct way to list it's children-commits, or in other words, what was derived from it.


MERGING

Children have one or more parents.

  • With just one parent this is just a simple parent <-- child commit.

  • With more than one parent this is what git calls "merging". Each child can point back to more than one parent at the same time, just as in having both a mother AND father, not just a mother.

Line diagram of: Commit2 with 2 parents (or what we call a git "merge", i.e. Procreation from multiple parents):

                parents     child

           ... <-- Commit
                        v
                         \
(older) ... <-- Commit1 <-- Commit2  

REMOTE

This word is also used to mean 2 different things:

  • a remote repository, and
  • the local alias name for a remote repository, i.e. a name which points using a URL to a remote repository.

remote repository - A repository which is used to track the same project but resides somewhere else. To communicate with remotes, see fetch or push. (gitglossary)

(The remote repository can even be another git repository on our own computer.) Actually there are two URLS for each remote name, one for pushing (i.e. uploading commits) and one for pulling (i.e. downloading commits) from that remote git repository.

A "remote" is a name (an identifier) which has an associated URL which points to a remote git repository. (It's been described as an alias for a URL, although it's more than that.)

You can setup multiple remotes if you want to pull or push to multiple remote repositories.

Though often you have just one, and it's default name is "origin" (meaning the upstream origin from where you cloned).

origin - The default upstream repository. Most projects have at least one upstream project which they track. By default origin is used for that purpose. New upstream updates will be fetched into remote-tracking branches named origin/name-of-upstream-branch, which you can see using git branch -r. (gitglossary)

Origin represents where you cloned the repository from.
That remote repository is called the "upstream" repository, and your cloned repository is called the "downstream" repository.

upstream - In software development, upstream refers to a direction toward the original authors or maintainers of software that is distributed as source code wikipedia

upstream branch - The default branch that is merged into the branch in question (or the branch in question is rebased onto). It is configured via branch..remote and branch..merge. If the upstream branch of A is origin/B sometimes we say "A is tracking origin/B". (gitglossary)

This is because most of the water generally flows down to you.
From time to time you might push some software back up to the upstream repository, so it can then flow down to all who have cloned it.

REMOTE TRACKING BRANCH

A remote-tracking-branch is first, just a branch name, like any other branch name.

It points at a local growing tip, i.e. a recent commit in your local git repository.

But note that it effectively also points to the same commit in the remote repository that you cloned the commit from.

remote-tracking branch - A ref that is used to follow changes from another repository. It typically looks like refs/remotes/foo/bar (indicating that it tracks a branch named bar in a remote named foo), and matches the right-hand-side of a configured fetch refspec. A remote-tracking branch should not contain direct modifications or have local commits made to it. (gitglossary)

Say the remote you cloned just has 2 commits, like this: parent42 <== child-of-4, and you clone it and now your local git repository has the same exact two commits: parent4 <== child-of-4.
Your remote tracking branch named origin now points to child-of-4.

Now say that a commit is added to the remote, so it looks like this: parent42 <== child-of-4 <== new-baby. To update your local, downstream repository you'll need to fetch new-baby, and add it to your local git repository. Now your local remote-tracking-branch points to new-baby. You get the idea, the concept of a remote-tracking-branch is simply to keep track of what had previously been the tip of a remote branch that you care about.


TRACKING IN ACTION

First we begin tracking a file with git.

enter image description here

Here are the basic commands involved with file tracking:

$ mkdir mydir &&  cd mydir &&  git init             # create a new git repository

$ git branch                                        # this initially reports no branches
                                                    #  (IMHO this is a bug!)

$ git status -bs       # -b = branch; -s = short    # master branch is empty
## No commits yet on master

# ...
$ touch foo                                         # create a new file

$ vim foo                                           # modify it (OPTIONAL)


$ git add         foo; commit -m 'your description'  # start tracking foo 
$ git rm  --index foo; commit -m 'your description'  # stop  tracking foo 
$ git rm          foo; commit -m 'your description'  # stop  tracking foo & also delete foo

REMOTE TRACKING IN ACTION

$ git pull    # Essentially does:  get fetch; git merge    # to update our clone

There is much more to learn about fetch, merge, etc, but this should get you off in the right direction I hope.

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

How to send json data in POST request using C#

This works for me.

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new 

StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
                {
                    Username = "myusername",
                    Password = "password"
                });

    streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

Downloading a file from spring controllers

If you:

  • Don't want to load the whole file into a byte[] before sending to the response;
  • Want/need to send/download it via InputStream;
  • Want to have full control of the Mime Type and file name sent;
  • Have other @ControllerAdvice picking up exceptions for you (or not).

The code below is what you need:

@RequestMapping(value = "/stuff/{stuffId}", method = RequestMethod.GET)
public ResponseEntity<FileSystemResource> downloadStuff(@PathVariable int stuffId)
                                                                      throws IOException {
    String fullPath = stuffService.figureOutFileNameFor(stuffId);
    File file = new File(fullPath);
    long fileLength = file.length(); // this is ok, but see note below

    HttpHeaders respHeaders = new HttpHeaders();
    respHeaders.setContentType("application/pdf");
    respHeaders.setContentLength(fileLength);
    respHeaders.setContentDispositionFormData("attachment", "fileNameIwant.pdf");

    return new ResponseEntity<FileSystemResource>(
        new FileSystemResource(file), respHeaders, HttpStatus.OK
    );
}

More on setContentLength(): First of all, the content-length header is optional per the HTTP 1.1 RFC. Still, if you can provide a value, it is better. To obtain such value, know that File#length() should be good enough in the general case, so it is a safe default choice.
In very specific scenarios, though, it can be slow, in which case you should have it stored previously (e.g. in the DB), not calculated on the fly. Slow scenarios include: if the file is very large, specially if it is on a remote system or something more elaborated like that - a database, maybe.



InputStreamResource

If your resource is not a file, e.g. you pick the data up from the DB, you should use InputStreamResource. Example:

    InputStreamResource isr = new InputStreamResource(new FileInputStream(file));
    return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);

Module AppRegistry is not registered callable module (calling runApplication)

1.Close Emülator

2.npm start -- --reset-cache

3.XCode -> Product -> Clean Build Folder

4.npx react-native run-ios

open resource with relative path in Java

Use this:

resourcesloader.class.getClassLoader().getResource("/path/to/file").**getPath();**

Immediate exit of 'while' loop in C++

cin >> choice;
while(choice!=99) {
    cin>>gNum;
    cin >> choice
}

You don't need a break, in that case.

Set disable attribute based on a condition for Html.TextBoxFor

I achieved it using some extension methods

private const string endFieldPattern = "^(.*?)>";

    public static MvcHtmlString IsDisabled(this MvcHtmlString htmlString, bool disabled)
    {
        string rawString = htmlString.ToString();
        if (disabled)
        {
            rawString = Regex.Replace(rawString, endFieldPattern, "$1 disabled=\"disabled\">");
        }

        return new MvcHtmlString(rawString);
    }

    public static MvcHtmlString IsReadonly(this MvcHtmlString htmlString, bool @readonly)
    {
        string rawString = htmlString.ToString();
        if (@readonly)
        {
            rawString = Regex.Replace(rawString, endFieldPattern, "$1 readonly=\"readonly\">");
        }

        return new MvcHtmlString(rawString);
    }

and then....

@Html.TextBoxFor(model => model.Name, new { @class= "someclass"}).IsDisabled(Model.ExpireDate == null)

How to set the default value of an attribute on a Laravel model

You can set Default attribute in Model also>

protected $attributes = [
        'status' => self::STATUS_UNCONFIRMED,
        'role_id' => self::ROLE_PUBLISHER,
    ];

You can find the details in these links

1.) How to set a default attribute value for a Laravel / Eloquent model?

2.) https://laracasts.com/index.php/discuss/channels/eloquent/eloquent-help-generating-attribute-values-before-creating-record


You can also Use Accessors & Mutators for this You can find the details in the Laravel documentation 1.) https://laravel.com/docs/4.2/eloquent#accessors-and-mutators

2.) https://scotch.io/tutorials/automatically-format-laravel-database-fields-with-accessors-and-mutators

3.) Universal accessors and mutators in Laravel 4

get the data of uploaded file in javascript

The example below is based on the html5rocks solution. It uses the browser's FileReader() function. Newer browsers only.

See http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files

In this example, the user selects an HTML file. It uploaded into the <textarea>.

<form enctype="multipart/form-data">
<input id="upload" type=file   accept="text/html" name="files[]" size=30>
</form>

<textarea class="form-control" rows=35 cols=120 id="ms_word_filtered_html"></textarea>

<script>
function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // use the 1st file from the list
    f = files[0];

    var reader = new FileReader();

    // Closure to capture the file information.
    reader.onload = (function(theFile) {
        return function(e) {

          jQuery( '#ms_word_filtered_html' ).val( e.target.result );
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsText(f);
  }

  document.getElementById('upload').addEventListener('change', handleFileSelect, false);
</script>

change array size

Yes, it is possible to resize an array. For example:

int[] arr = new int[5];
// increase size to 10
Array.Resize(ref arr, 10);
// decrease size to 3
Array.Resize(ref arr, 3);

If you create an array with CreateInstance() method, the Resize() method is not working. For example:

// create an integer array with size of 5
var arr = Array.CreateInstance(typeof(int), 5);
// this not work
Array.Resize(ref arr, 10);

The array size is not dynamic, even we can resize it. If you want a dynamic array, I think we can use generic List instead.

var list = new List<int>();
// add any item to the list
list.Add(5);
list.Add(8);
list.Add(12);
// we can remove it easily as well
list.Remove(5);
foreach(var item in list)
{
  Console.WriteLine(item);
}

Mysql: Select all data between two dates

you must add 1 day to the end date, using: DATE_ADD('$end_date', INTERVAL 1 DAY)

What's the difference between JPA and Hibernate?

JPA is the dance, Hibernate is the dancer.

"for loop" with two variables?

"Python 3."

Add 2 vars with for loop using zip and range; Returning a list.

Note: Will only run till smallest range ends.

>>>a=[g+h for g,h in zip(range(10), range(10))]
>>>a
>>>[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

How to change the integrated terminal in visual studio code or VSCode

If you want to change the external terminal to the new windows terminal, here's how.

Remove folder and its contents from git/GitHub's history

I find that the --tree-filter option used in other answers can be very slow, especially on larger repositories with lots of commits.

Here is the method I use to completely remove a directory from the git history using the --index-filter option, which runs much quicker:

# Make a fresh clone of YOUR_REPO
git clone YOUR_REPO
cd YOUR_REPO

# Create tracking branches of all branches
for remote in `git branch -r | grep -v /HEAD`; do git checkout --track $remote ; done

# Remove DIRECTORY_NAME from all commits, then remove the refs to the old commits
# (repeat these two commands for as many directories that you want to remove)
git filter-branch --index-filter 'git rm -rf --cached --ignore-unmatch DIRECTORY_NAME/' --prune-empty --tag-name-filter cat -- --all
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d

# Ensure all old refs are fully removed
rm -Rf .git/logs .git/refs/original

# Perform a garbage collection to remove commits with no refs
git gc --prune=all --aggressive

# Force push all branches to overwrite their history
# (use with caution!)
git push origin --all --force
git push origin --tags --force

You can check the size of the repository before and after the gc with:

git count-objects -vH

When do we need curly braces around shell variables?

Variables are declared and assigned without $ and without {}. You have to use

var=10

to assign. In order to read from the variable (in other words, 'expand' the variable), you must use $.

$var      # use the variable
${var}    # same as above
${var}bar # expand var, and append "bar" too
$varbar   # same as ${varbar}, i.e expand a variable called varbar, if it exists.

This has confused me sometimes - in other languages we refer to the variable in the same way, regardless of whether it's on the left or right of an assignment. But shell-scripting is different, $var=10 doesn't do what you might think it does!

Difference between e.target and e.currentTarget

Ben is completely correct in his answer - so keep what he says in mind. What I'm about to tell you isn't a full explanation, but it's a very easy way to remember how e.target, e.currentTarget work in relation to mouse events and the display list:

e.target = The thing under the mouse (as ben says... the thing that triggers the event). e.currentTarget = The thing before the dot... (see below)

So if you have 10 buttons inside a clip with an instance name of "btns" and you do:

btns.addEventListener(MouseEvent.MOUSE_OVER, onOver);
// btns = the thing before the dot of an addEventListener call
function onOver(e:MouseEvent):void{
  trace(e.target.name, e.currentTarget.name);
}

e.target will be one of the 10 buttons and e.currentTarget will always be the "btns" clip.

It's worth noting that if you changed the MouseEvent to a ROLL_OVER or set the property btns.mouseChildren to false, e.target and e.currentTarget will both always be "btns".

jQuery: value.attr is not a function

Contents of that jQuery object are plain DOM elements, which doesn't respond to jQuery methods (e.g. .attr). You need to wrap the value by $() to turn it into a jQuery object to use it.

    console.info("cat_id: ", $(value).attr('cat_id'));

or just use the DOM method directly

    console.info("cat_id: ", value.getAttribute('cat_id'));

Remove the last three characters from a string

items.Remove(items.Length - 3)

string.Remove() removes all items from that index to the end. items.length - 3 gets the index 3 chars from the end

How do I make Visual Studio pause after executing a console application in debug mode?

You could also setup your executable as an external tool, and mark the tool for Use output window. That way the output of the tool will be visible within Visual Studio itself, not a separate window.

LDAP root query syntax to search more than one specific OU

I don't think this is possible with AD. The distinguishedName attribute is the only thing I know of that contains the OU piece on which you're trying to search, so you'd need a wildcard to get results for objects under those OUs. Unfortunately, the wildcard character isn't supported on DNs.

If at all possible, I'd really look at doing this in 2 queries using OU=Staff... and OU=Vendors... as the base DNs.

Case insensitive string as HashMap key

I like using ICU4J’s CaseInsensitiveString wrap of the Map key because it takes care of the hash\equals and issue and it works for unicode\i18n.

HashMap<CaseInsensitiveString, String> caseInsensitiveMap = new HashMap<>();
caseInsensitiveMap.put("tschüß", "bye");
caseInsensitiveMap.containsKey("TSCHÜSS"); # true

Git asks for username every time I push

Quick method

get url of your git when inside working dir :

git config remote.origin.url

then :

git config credential.helper store

git push "url of your git"

will ask username and password last one time

done.

Correlation heatmap

Another alternative is to use the heatmap function in seaborn to plot the covariance. This example uses the Auto data set from the ISLR package in R (the same as in the example you showed).

import pandas.rpy.common as com
import seaborn as sns
%matplotlib inline

# load the R package ISLR
infert = com.importr("ISLR")

# load the Auto dataset
auto_df = com.load_data('Auto')

# calculate the correlation matrix
corr = auto_df.corr()

# plot the heatmap
sns.heatmap(corr, 
        xticklabels=corr.columns,
        yticklabels=corr.columns)

enter image description here

If you wanted to be even more fancy, you can use Pandas Style, for example:

cmap = cmap=sns.diverging_palette(5, 250, as_cmap=True)

def magnify():
    return [dict(selector="th",
                 props=[("font-size", "7pt")]),
            dict(selector="td",
                 props=[('padding', "0em 0em")]),
            dict(selector="th:hover",
                 props=[("font-size", "12pt")]),
            dict(selector="tr:hover td:hover",
                 props=[('max-width', '200px'),
                        ('font-size', '12pt')])
]

corr.style.background_gradient(cmap, axis=1)\
    .set_properties(**{'max-width': '80px', 'font-size': '10pt'})\
    .set_caption("Hover to magify")\
    .set_precision(2)\
    .set_table_styles(magnify())

enter image description here

Facebook database design?

Have a look at the following database schema, reverse engineered by Anatoly Lubarsky:

Facebook Schema

How do I get the SharedPreferences from a PreferenceActivity in Android?

having to pass context around everywhere is really annoying me. the code becomes too verbose and unmanageable. I do this in every project instead...

public class global {
    public static Activity globalContext = null;

and set it in the main activity create

@Override
public void onCreate(Bundle savedInstanceState) {
    Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
            global.sdcardPath,
            ""));
    super.onCreate(savedInstanceState);

    //Start 
    //Debug.startMethodTracing("appname.Trace1");

    global.globalContext = this;

also all preference keys should be language independent, I'm shocked nobody has mentioned that.

getText(R.string.yourPrefKeyName).toString()

now call it very simply like this in one line of code

global.globalContext.getSharedPreferences(global.APPNAME_PREF, global.MODE_PRIVATE).getBoolean("isMetric", true);

How to reset or change the passphrase for a GitHub SSH key?

You can change the passphrase for your private key by doing:

ssh-keygen -f ~/.ssh/id_rsa -p

How to create a backup of a single table in a postgres database?

If you are on Ubuntu,

  1. Login to your postgres user sudo su postgres
  2. pg_dump -d <database_name> -t <table_name> > file.sql

Make sure that you are executing the command where the postgres user have write permissions (Example: /tmp)

Edit

If you want to dump the .sql in another computer, you may need to consider skipping the owner information getting saved into the .sql file.

You can use pg_dump --no-owner -d <database_name> -t <table_name> > file.sql

MySQL selecting yesterday's date

The simplest and best way to get yesterday's date is:

subdate(current_date, 1)

Your query would be:

SELECT 
    url as LINK,
    count(*) as timesExisted,
    sum(DateVisited between UNIX_TIMESTAMP(subdate(current_date, 1)) and
        UNIX_TIMESTAMP(current_date)) as timesVisitedYesterday
FROM mytable
GROUP BY 1

For the curious, the reason that sum(condition) gives you the count of rows that satisfy the condition, which would otherwise require a cumbersome and wordy case statement, is that in mysql boolean values are 1 for true and 0 for false, so summing a condition effectively counts how many times it's true. Using this pattern can neaten up your SQL code.

Windows command prompt log to a file

First method

For Windows 7 and above users, Windows PowerShell give you this option. Users with windows version less than 7 can download PowerShell online and install it.

Steps:

  1. type PowerShell in search area and click on "Windows PowerShell"

  2. If you have a .bat (batch) file go to step 3 OR copy your commands to a file and save it with .bat extension (e.g. file.bat)

  3. run the .bat file with following command

    PS (location)> <path to bat file>/file.bat | Tee-Object -file log.txt

This will generate a log.txt file with all command prompt output in it. Advantage is that you can also the output on command prompt.

Second method

You can use file redirection (>, >>) as suggest by Bali C above.

I will recommend first method if you have lots of commands to run or a script to run. I will recommend last method if there is only few commands to run.

Convert A String (like testing123) To Binary In Java

import java.lang.*;
import java.io.*;
class d2b
{
  public static void main(String args[]) throws IOException{
  BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter the decimal value:");
  String h = b.readLine();
  int k = Integer.parseInt(h);  
  String out = Integer.toBinaryString(k);
  System.out.println("Binary: " + out);
  }
}   

How do you redirect to a page using the POST verb?

I would like to expand the answer of Jason Bunting

like this

ActionResult action = new SampelController().Index(2, "text");
return action;

And Eli will be here for something idea on how to make it generic variable

Can get all types of controller

Is there a query language for JSON?

Check out https://github.com/niclasko/Cypher.js (note: I'm the author)

It's a zero-dependency Javascript implementation of the Cypher graph database query language along with a graph database. It runs in the browser (tested with Firefox, Chrome, IE).

With relevance to the question. It can be used to query JSON endpoints:

load json from "http://url/endpoint" as l return l limit 10

Here's an example of querying a complex JSON document and performing analysis on it:

Cypher.js JSON query example

Rendering HTML in a WebView with custom CSS

You can Use Online Css link To set Style over existing content.

For That you have to load data in webview and enable JavaScript Support.

See Below Code:

   WebSettings webSettings=web_desc.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDefaultTextEncodingName("utf-8");
    webSettings.setTextZoom(55);
    StringBuilder sb = new StringBuilder();
    sb.append("<HTML><HEAD><LINK href=\" http://yourStyleshitDomain.com/css/mbl-view-content.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>");
    sb.append(currentHomeContent.getDescription());
    sb.append("</body></HTML>");
    currentWebView.loadDataWithBaseURL("file:///android_asset/", sb.toString(), "text/html", "utf-8", null);

Here Use StringBuilder to append String for Style.

sb.append("<HTML><HEAD><LINK href=\" http://yourStyleshitDomain.com/css/mbl-view-content.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>");
sb.append(currentHomeContent.getDescription());

How to export and import environment variables in windows?

Combine @vincsilver and @jdigital's answers with some modifications,

  1. export .reg to current directory
  2. add date mark

code:

set TODAY=%DATE:~0,4%-%DATE:~5,2%-%DATE:~8,2%

regedit /e "%CD%\user_env_variables[%TODAY%].reg" "HKEY_CURRENT_USER\Environment"
regedit /e "%CD%\global_env_variables[%TODAY%].reg" "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

Output would like:

global_env_variables[2017-02-14].reg
user_env_variables[2017-02-14].reg

Using DataContractSerializer to serialize, but can't deserialize back

Other solution is:

public static T Deserialize<T>(string rawXml)
{
    using (XmlReader reader = XmlReader.Create(new StringReader(rawXml)))
    {
        DataContractSerializer formatter0 = 
            new DataContractSerializer(typeof(T));
        return (T)formatter0.ReadObject(reader);
    }
}

One remark: sometimes it happens that raw xml contains e.g.:

<?xml version="1.0" encoding="utf-16"?>

then of course you can't use UTF8 encoding used in other examples..

How to get longitude and latitude of any address?

There is no forumula, as street names and cities are essentially handed out randomly. The address needs to be looked up in a database. Alternatively, you can look up a zip code in a database for the region that the zip code is for.

You didn't mention a country, so I'm going to assume you just want addresses in the USA. There are numerous databases you can use, some free, some not.

You can also use the Google Maps API to have them look up an address in their database for you. That is probably the easiest solution, but requires your application to have a working internet connection at all times.

Changing specific text's color using NSMutableAttributedString in Swift

Answer is already given in previous posts but i have a different way of doing this

Swift 3x :

var myMutableString = NSMutableAttributedString()

myMutableString = NSMutableAttributedString(string: "Your full label textString")

myMutableString.setAttributes([NSFontAttributeName : UIFont(name: "HelveticaNeue-Light", size: CGFloat(17.0))!
        , NSForegroundColorAttributeName : UIColor(red: 232 / 255.0, green: 117 / 255.0, blue: 40 / 255.0, alpha: 1.0)], range: NSRange(location:12,length:8)) // What ever range you want to give

yourLabel.attributedText = myMutableString

Hope this helps anybody!

Error message "unreported exception java.io.IOException; must be caught or declared to be thrown"

Exceptions bubble up the stack. If a caller calls a method that throws a checked exception, like IOException, it must also either catch the exception, or itself throw it.

In the case of the first block:

filecontent()
{
    setGUI();
    setRegister();
    showfile();
    setTitle("FileData");
    setVisible(true);
    setSize(300, 300);

    /*
        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent we)
            {
                System.exit(0);
            }
        });
    */
}

You would have to include a try catch block:

filecontent()
{
    setGUI();
    setRegister();
    try {
        showfile();
    }
    catch (IOException e) {
        // Do something here
    }
    setTitle("FileData");
    setVisible(true);
    setSize(300, 300);

    /*
        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent we)
            {
                System.exit(0);
            }
        });
    */
}

In the case of the second:

public void actionPerformed(ActionEvent ae)
{
    if (ae.getSource() == submit)
    {
        showfile();
    }
}

You cannot throw IOException from this method as its signature is determined by the interface, so you must catch the exception within:

public void actionPerformed(ActionEvent ae)
{
    if(ae.getSource()==submit)
    {
        try {
            showfile();
        }
        catch (IOException e) {
            // Do something here
        }
    }
}

Remember, the showFile() method is throwing the exception; that's what the "throws" keyword indicates that the method may throw that exception. If the showFile() method is throwing, then whatever code calls that method must catch, or themselves throw the exception explicitly by including the same throws IOException addition to the method signature, if it's permitted.

If the method is overriding a method signature defined in an interface or superclass that does not also declare that the method may throw that exception, you cannot declare it to throw an exception.

Is there a way to iterate over a dictionary?

The block approach avoids running the lookup algorithm for every key:

[dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL* stop) {
  NSLog(@"%@ => %@", key, value);
}];

Even though NSDictionary is implemented as a hashtable (which means that the cost of looking up an element is O(1)), lookups still slow down your iteration by a constant factor.

My measurements show that for a dictionary d of numbers ...

NSMutableDictionary* dict = [NSMutableDictionary dictionary];
for (int i = 0; i < 5000000; ++i) {
  NSNumber* value = @(i);
  dict[value.stringValue] = value;
}

... summing up the numbers with the block approach ...

__block int sum = 0;
[dict enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSNumber* value, BOOL* stop) {
  sum += value.intValue;
}];

... rather than the loop approach ...

int sum = 0;
for (NSString* key in dict)
  sum += [dict[key] intValue];

... is about 40% faster.

EDIT: The new SDK (6.1+) appears to optimise loop iteration, so the loop approach is now about 20% faster than the block approach, at least for the simple case above.

error: Libtool library used but 'LIBTOOL' is undefined

For folks who ended up here and are using CYGWIN, install following packages in cygwin and re-run:

  • cygwin32-libtool
  • libtool
  • libtool-debuginfo

How is OAuth 2 different from OAuth 1?

The previous explanations are all overly detailed and complicated IMO. Put simply, OAuth 2 delegates security to the HTTPS protocol. OAuth 1 did not require this and consequentially had alternative methods to deal with various attacks. These methods required the application to engage in certain security protocols which are complicated and can be difficult to implement. Therefore, it is simpler to just rely on the HTTPS for security so that application developers dont need to worry about it.

As to your other questions, the answer depends. Some services dont want to require the use of HTTPS, were developed before OAuth 2, or have some other requirement which may prevent them from using OAuth 2. Furthermore, there has been a lot of debate about the OAuth 2 protocol itself. As you can see, Facebook, Google, and a few others each have slightly varying versions of the protocols implemented. So some people stick with OAuth 1 because it is more uniform across the different platforms. Recently, the OAuth 2 protocol has been finalized but we have yet to see how its adoption will take.

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I had the same problem of "gpg: keyserver timed out" with a couple of different servers. Finally, it turned out that I didn't need to do that manually at all. On a Debian system, the simple solution which fixed it was just (as root or precede with sudo):

aptitude install debian-archive-keyring

In case it is some other keyring you need, check out

apt-cache search keyring | grep debian

My squeeze system shows all these:

debian-archive-keyring       - GnuPG archive keys of the Debian archive
debian-edu-archive-keyring   - GnuPG archive keys of the Debian Edu archive
debian-keyring               - GnuPG keys of Debian Developers
debian-ports-archive-keyring - GnuPG archive keys of the debian-ports archive
emdebian-archive-keyring     - GnuPG archive keys for the emdebian repository

Send PHP variable to javascript function

You can pass PHP values to JavaScript. The PHP will execute server side so the value will be calculated and then you can echo it to the HTML containing the javascript. The javascript will then execute in the clients browser with the value PHP calculated server-side.

<script type="text/javascript">
    // Do something in JavaScript
    var x = <?php echo $calculatedValue; ?>;
    // etc..
</script>

How to give a delay in loop execution using Qt

C++11 has some portable timer stuff. Check out sleep_for.

MySQL vs MongoDB 1000 reads

man,,, the answer is that you're basically testing PHP and not a database.

don't bother iterating the results, whether commenting out the print or not. there's a chunk of time.

   foreach ($cursor as $obj)
    {
        //echo $obj["thread_title"] . "<br><Br>";
    }

while the other chunk is spend yacking up a bunch of rand numbers.

function get_15_random_numbers()
{
    $numbers = array();
    for($i=1;$i<=15;$i++)
    {
        $numbers[] = mt_rand(1, 20000000) ;

    }
    return $numbers;
}

then theres a major difference b/w implode and in.

and finally what is going on here. looks like creating a connection each time, thus its testing the connection time plus the query time.

$m = new Mongo();

vs

$db = new AQLDatabase();

so your 101% faster might turn out to be 1000% faster for the underlying query stripped of jazz.

urghhh.

Make DateTimePicker work as TimePicker only in WinForms

...or alternatively if you only want to show a portion of the time value use "Custom":

timePicker = new DateTimePicker();
timePicker.Format = DateTimePickerFormat.Custom;
timePicker.CustomFormat = "HH:mm"; // Only use hours and minutes
timePicker.ShowUpDown = true;

Scroll to a specific Element Using html

_x000D_
_x000D_
 <nav>
      <a href="#section1">1</a> 
      <a href="#section2">2</a> 
      <a href="#section3">3</a>
    </nav>
    <section id="section1">1</section>
    <section id="section2" class="fifty">2</section>
    <section id="section3">3</section>
    
    <style>
      * {padding: 0; margin: 0;}
      nav {
        background: black;
        position: fixed;
      }
      a {
        color: #fff;
        display: inline-block;
        padding: 0 1em;
        height: 50px;
      }
      section {
        background: red;
        height: 100vh;
        text-align: center;
        font-size: 5em;
      }
      html {
        scroll-behavior: smooth;
      }
      #section1{
        background-color:green;
      }
      #section3{
        background-color:yellow;
      }
      
    </style>
    
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" >
      $(document).on('click', 'a[href^="#"]', function (event) {
        event.preventDefault();
    
        $('html, body').animate({
            scrollTop: $($.attr(this, 'href')).offset().top
        }, 500);
      });
    </script>
      
_x000D_
_x000D_
_x000D_

Java 8 Iterable.forEach() vs foreach loop

The advantage comes into account when the operations can be executed in parallel. (See http://java.dzone.com/articles/devoxx-2012-java-8-lambda-and - the section about internal and external iteration)

  • The main advantage from my point of view is that the implementation of what is to be done within the loop can be defined without having to decide if it will be executed in parallel or sequential

  • If you want your loop to be executed in parallel you could simply write

     joins.parallelStream().forEach(join -> mIrc.join(mSession, join));
    

    You will have to write some extra code for thread handling etc.

Note: For my answer I assumed joins implementing the java.util.Stream interface. If joins implements only the java.util.Iterable interface this is no longer true.

How to make an ImageView with rounded corners?

Romain Guy is where it's at.

Minified version as follows.

Bitmap bitmap = ((BitmapDrawable) getResources().getDrawable(R.drawable.image)).getBitmap();

Bitmap bitmapRounded = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
Canvas canvas = new Canvas(bitmapRounded);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
canvas.drawRoundRect((new RectF(0.0f, 0.0f, bitmap.getWidth(), bitmap.getHeight())), 10, 10, paint);

imageView.setImageBitmap(bitmapRounded);

Default username password for Tomcat Application Manager

The admin and manager apps are two separate things. Here's a snapshot of a tomcat-users.xml file that works, try this:

<?xml version='1.0' encoding='utf-8'?>  
<tomcat-users>  
    <role rolename="tomcat"/>  
    <role rolename="role1"/>  
    <role rolename="manager"/>  
    <user username="tomcat" password="tomcat" roles="tomcat"/>  
    <user username="both" password="tomcat" roles="tomcat,role1"/>  
    <user username="role1" password="tomcat" roles="role1"/>  
    <user username="USERNAME" password="PASSWORD" roles="manager,tomcat,role1"/>  
</tomcat-users>  

It works for me very well

Online PHP syntax checker / validator

Here is a similar question to yours. (Practically the same.)

What ways are there to validate PHP code?

Edit

The top answer there suggest this resource:

http://www.meandeviation.com/tutorials/learnphp/php-syntax-check/v4/syntax-check.php

Vertical Align text in a Label

Use css on your label.

For example:

label {line-height:1em; margin:2px 5px 3px 5px; padding:2px 5px 3px 5px;}

Notice that the line-height will adjust the height of the line itself, whereas margin will dictate how far out other elements will be outside the lable and padding will dictate any inner space from the outside edge of the label. The margin and padding work like this (clockwise: Top Right Bottom Left), so 2px 5px 3px 5px is:

2px Top 5px Right 3px Bottom 5px Left

How can I clear the terminal in Visual Studio Code?

workbench.action.terminal.clear no longer works (at least for VS Code Insiders 1.54 on Mac)

The following is the way to now map CTRL+L yo the default console functionality.

{
    "key": "ctrl+l",
    "command": "workbench.action.terminal.sendSequence",
    "args": {"text": "\u000c"},
    "when": "terminalFocus"
}

angular ng-repeat in reverse

I had gotten frustrated with this problem myself and so I modified the filter that was created by @Trevor Senior as I was running into an issue with my console saying that it could not use the reverse method. I also, wanted to keep the integrity of the object because this is what Angular is originally using in a ng-repeat directive. In this case I used the input of stupid (key) because the console will get upset saying there are duplicates and in my case I needed to track by $index.

Filter:

angular.module('main').filter('reverse', function() {
    return function(stupid, items) {
    var itemss = items.files;
    itemss = itemss.reverse();  
    return items.files = itemss; 
  };
});

HTML: <div ng-repeat="items in items track by $index | reverse: items">

How to change link color (Bootstrap)

I'm fully aware that the code in the original quesiton displays a situation of being navbar related. But as you also dive into other compontents, it maybe helpful to know that the class options for text styling may not work.

But you can still create your own helper classes to keep the "Bootstrap flow" going in your HTML. Here is one idea to help style links that are in panel-title regions.

The following code by itself will not style a warning color on your anchor link...

<div class="panel panel-default my-panel-styles"> 
...    
  <h4 class="panel-title">
    <a class="accordion-toggle btn-block text-warning" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
      My Panel title that is also a link
    </a>
  </h4>
 ...
 </div>

But you could extend the Bootstrap styling package by adding your own class with appropriate colors like this...

.my-panel-styles .text-muted {color:#777;}
.my-panel-styles .text-primary {color:#337ab7;}
.my-panel-styles .text-success {color:#d44950;}
.my-panel-styles .text-info {color:#31708f;}
.my-panel-styles .text-warning {color:#8a6d3b;}
.my-panel-styles .text-danger {color:#a94442;}

...Now you can continue building out your panel anchor links with the Bootstrap colors you want.

is it possible to evenly distribute buttons across the width of an android linearlayout

You can do this by giving both Views a layout_width of 0dp and a layout_weight of 1:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>

    <TextView
        android:layout_width="0dp"
        android:text="example text"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>

</LinearLayout>

The way android layout_weight works is that:

  • first, it looks to the size that a View would normally take and reserves this space.
  • second, if the layout is match_parent then it will divide the space that is left in the ratio of the layout_weights. Thus if you gave the Views layout_weight="2" and layout_weight="1",the resultant ratio will be 2 to 1,that is : the first View will get 2/3 of the space that is left and the other view 1/3.

So that's why if you give layout_width a size of 0dp the first step has no added meaning since both Views are not assigned any space. Then only the second point decides the space each View gets, thus giving the Views the space you specified according to the ratio!

To explain why 0dp causes the space to devide equally by providing an example that shows the opposite: The code below would result in something different since example text now has a width that is greater than 0dp because it has wrap_content instead making the free space left to divide less than 100% because the text takes space. The result will be that they do get 50% of the free space left but the text already took some space so the TextView will have well over 50% of the total space.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>

    <TextView
        android:layout_width="wrap_content"
        android:text="example text"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>

</LinearLayout>

upstream sent too big header while reading response header from upstream

Add the following to your conf file

fastcgi_buffers 16 16k; 
fastcgi_buffer_size 32k;

How to scroll to the bottom of a UITableView on the iPhone before the view appears

Is of course a Bug. Probably somewhere in your code you use table.estimatedRowHeight = value (for example 100). Replace this value by the highest value you think a row height could get, for example 500.. This should solve the problem in combination with following code:

//auto scroll down example
let delay = 0.1 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))

dispatch_after(time, dispatch_get_main_queue(), {
    self.table.scrollToRowAtIndexPath(NSIndexPath(forRow: self.Messages.count - 1, inSection: 0), atScrollPosition: UITableViewScrollPosition.Bottom, animated: false)
})

Delete many rows from a table using id in Mysql

The best way is to use IN statement :

DELETE from tablename WHERE id IN (1,2,3,...,254);

You can also use BETWEEN if you have consecutive IDs :

DELETE from tablename WHERE id BETWEEN 1 AND 254;

You can of course limit for some IDs using other WHERE clause :

DELETE from tablename WHERE id BETWEEN 1 AND 254 AND id<>10;

How to escape special characters of a string with single backslashes

Simply using re.sub might also work instead of str.maketrans. And this would also work in python 2.x

>>> print(re.sub(r'(\-|\]|\^|\$|\*|\.|\\)',lambda m:{'-':'\-',']':'\]','\\':'\\\\','^':'\^','$':'\$','*':'\*','.':'\.'}[m.group()],"^stack.*/overflo\w$arr=1"))
\^stack\.\*/overflo\\w\$arr=1

How can I shrink the drawable on a button?

Here the function which I created for scaling vector drawables. I used it for setting TextView compound drawable.

/**
 * Used to load vector drawable and set it's size to intrinsic values
 *
 * @param context Reference to {@link Context}
 * @param resId   Vector image resource id
 * @param tint    If not 0 - colour resource to tint the drawable with.
 * @param newWidth If not 0 then set the drawable's width to this value and scale 
 *                 height accordingly.
 * @return On success a reference to a vector drawable
 */
@Nullable
public static Drawable getVectorDrawable(@NonNull Context context,
                                         @DrawableRes int resId,
                                         @ColorRes int tint,
                                         float newWidth)
{
    VectorDrawableCompat drawableCompat =
            VectorDrawableCompat.create(context.getResources(), resId, context.getTheme());
    if (drawableCompat != null)
    {
        if (tint != 0)
        {
            drawableCompat.setTint(ResourcesCompat.getColor(context.getResources(), tint, context.getTheme()));
        }

        drawableCompat.setBounds(0, 0, drawableCompat.getIntrinsicWidth(), drawableCompat.getIntrinsicHeight());

        if (newWidth != 0.0)
        {
            float scale = newWidth / drawableCompat.getIntrinsicWidth();
            float height = scale * drawableCompat.getIntrinsicHeight();
            ScaleDrawable scaledDrawable = new ScaleDrawable(drawableCompat, Gravity.CENTER, 1.0f, 1.0f);
            scaledDrawable.setBounds(0,0, (int) newWidth, (int) height);
            scaledDrawable.setLevel(10000);
            return scaledDrawable;
        }
    }
    return drawableCompat;
}

Webpack.config how to just copy the index.html to the dist folder

To copy an already existing index.html file into the dist directory you can simply use the HtmlWebpackPlugin by specifying the source index.html as a template.

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  // ...
  plugins: [    
    new HtmlWebpackPlugin({
      template: './path/to/index.html',
    })
  ],
  // ...
};

The created dist/index.html file will be basically the same as your source file with the difference that bundled resources like .js files are injected with <script> tags by webpack. Minification and further options can be configured and are documented on github.

LPCSTR, LPCTSTR and LPTSTR

To answer the first part of your question:

LPCSTR is a pointer to a const string (LP means Long Pointer)

LPCTSTR is a pointer to a const TCHAR string, (TCHAR being either a wide char or char depending on whether UNICODE is defined in your project)

LPTSTR is a pointer to a (non-const) TCHAR string

In practice when talking about these in the past, we've left out the "pointer to a" phrase for simplicity, but as mentioned by lightness-races-in-orbit they are all pointers.

This is a great codeproject article describing C++ strings (see 2/3 the way down for a chart comparing the different types)

Accessing Imap in C#

MailSystem.NET contains all your need for IMAP4. It's free & open source.

(I'm involved in the project)

Class JavaLaunchHelper is implemented in both ... libinstrument.dylib. One of the two will be used. Which one is undefined

If you're using IntelliJ & Mac just go to Project structure -> SDK and make sure that there is Java listed but it points to sth like

/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home

Rather than user home...

How to specify Memory & CPU limit in docker compose version 3

Docker Compose does not support the deploy key. It's only respected when you use your version 3 YAML file in a Docker Stack.

This message is printed when you add the deploy key to you docker-compose.yml file and then run docker-compose up -d

WARNING: Some services (database) use the 'deploy' key, which will be ignored. Compose does not support 'deploy' configuration - use docker stack deploy to deploy to a swarm.

The documentation (https://docs.docker.com/compose/compose-file/#deploy) says:

Specify configuration related to the deployment and running of services. This only takes effect when deploying to a swarm with docker stack deploy, and is ignored by docker-compose up and docker-compose run.

What does the construct x = x || y mean?

Quote: "What does the construct x = x || y mean?"

Assigning a default value.

This means providing a default value of y to x, in case x is still waiting for its value but hasn't received it yet or was deliberately omitted in order to fall back to a default.

Python 101: Can't open file: No such file or directory

Try uninstalling Python and then install it again, but this time make sure that the option Add Python to Path is marked as checked during the installation process.

Why does cURL return error "(23) Failed writing body"?

If you are trying something similar like source <( curl -sS $url ) and getting the (23) Failed writing body error, it is because sourcing a process substitution doesn't work in bash 3.2 (the default for macOS).

Instead, you can use this workaround.

source /dev/stdin <<<"$( curl -sS $url )"

Which font is used in Visual Studio Code Editor and how to change fonts?

Another way to determine the default font is to start typing "editor.fontFamily" in settings and see what auto-fill suggests. On a Mac, it shows by default:

"editor.fontFamily": "Menlo, Monaco, 'Courier New', monospace",

which confirms what Andy Li says above.

set div height using jquery (stretch div height)

The correct way to do this is with good-old CSS:

#content{
    width:100%;
    position:absolute;
    top:35px;
    bottom:35px;
}

And the bonus is that you don't need to attach to the window.onresize event! Everything will adjust as the document reflows. All for the low-low price of four lines of CSS!

Android draw a Horizontal line between views

A View whose background color you can specify would do (height=a few dpi). Looked in real code and here it is:

        <LinearLayout
            android:id="@+id/lineA"
            android:layout_width="fill_parent"
            android:layout_height="2dp"
            android:background="#000000" />

Note that it may be any kind of View.

Is there an auto increment in sqlite?

What you do is correct, but the correct syntax for 'auto increment' should be without space:

CREATE TABLE people (id integer primary key autoincrement, first_name string, last_name string);

(Please also note that I changed your varchars to strings. That's because SQLite internally transforms a varchar into a string, so why bother?)

then your insert should be, in SQL language as standard as possible:

INSERT INTO people(id, first_name, last_name) VALUES (null, 'john', 'doe');

while it is true that if you omit id it will automatically incremented and assigned, I personally prefer not to rely on automatic mechanisms which could change in the future.

A note on autoincrement: although, as many pointed out, it is not recommended by SQLite people, I do not like the automatic reuse of ids of deleted records if autoincrement is not used. In other words, I like that the id of a deleted record will never, ever appear again.

HTH

Get content of a DIV using JavaScript

(1) Your <script> tag should be placed before the closing </body> tag. Your JavaScript is trying to manipulate HTML elements that haven't been loaded into the DOM yet.
(2) Your assignment of HTML content looks jumbled.
(3) Be consistent with the case in your element ID, i.e. 'DIV2' vs 'Div2'
(4) User lower case for 'document' object (credit: ThatOtherPerson)

<body>
<div id="DIV1">
 // Some content goes here.
</div>

<div id="DIV2">
</div>
<script type="text/javascript">

   var MyDiv1 = document.getElementById('DIV1');
   var MyDiv2 = document.getElementById('DIV2');
   MyDiv2.innerHTML = MyDiv1.innerHTML;

</script>
</body>

Is there a way to style a TextView to uppercase all of its letters?

It is really very disappointing that you can't do it with styles (<item name="android:textAllCaps">true</item>) or on each XML layout file with the textAllCaps attribute, and the only way to do it is actually using theString.toUpperCase() on each of the strings when you do a textViewXXX.setText(theString).

In my case, I did not wanted to have theString.toUpperCase() everywhere in my code but to have a centralized place to do it because I had some Activities and lists items layouts with TextViews that where supposed to be capitalized all the time (a title) and other who did not... so... some people may think is an overkill, but I created my own CapitalizedTextView class extending android.widget.TextView and overrode the setText method capitalizing the text on the fly.

At least, if the design changes or I need to remove the capitalized text in future versions, I just need to change to normal TextView in the layout files.

Now, take in consideration that I did this because the App's Designer actually wanted this text (the titles) in CAPS all over the App no matter the original content capitalization, and also I had other normal TextViews where the capitalization came with the the actual content.

This is the class:

package com.realactionsoft.android.widget;

import android.content.Context; 
import android.util.AttributeSet; 
import android.view.ViewTreeObserver; 
import android.widget.TextView;


public class CapitalizedTextView extends TextView implements ViewTreeObserver.OnPreDrawListener {

    public CapitalizedTextView(Context context) {
        super(context);
    }

    public CapitalizedTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CapitalizedTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        super.setText(text.toString().toUpperCase(), type);
    }

}

And whenever you need to use it, just declare it with all the package in the XML layout:

<com.realactionsoft.android.widget.CapitalizedTextView 
        android:id="@+id/text_view_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

Some will argue that the correct way to style text on a TextView is to use a SpannableString, but I think that would be even a greater overkill, not to mention more resource-consuming because you'll be instantiating another class than TextView.

Programmatically Hide/Show Android Soft Keyboard

UPDATE 2

@Override
    protected void onResume() {
        super.onResume();
        mUserNameEdit.requestFocus();

        mUserNameEdit.postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                InputMethodManager keyboard = (InputMethodManager)
                getSystemService(Context.INPUT_METHOD_SERVICE);
                keyboard.showSoftInput(mUserNameEdit, 0);
            }
        },200); //use 300 to make it run when coming back from lock screen
    }

I tried very hard and found out a solution ... whenever a new activity starts then keyboard cant open but we can use Runnable in onResume and it is working fine so please try this code and check...

UPDATE 1

add this line in your AppLogin.java

mUserNameEdit.requestFocus();

and this line in your AppList.java

listview.requestFocus()'

after this check your application if it is not working then add this line in your AndroidManifest.xml file

<activity android:name=".AppLogin" android:configChanges="keyboardHidden|orientation"></activity>
<activity android:name=".AppList" android:configChanges="keyboard|orientation"></activity>

ORIGINAL ANSWER

 InputMethodManager imm = (InputMethodManager)this.getSystemService(Service.INPUT_METHOD_SERVICE);

for hide keyboard

 imm.hideSoftInputFromWindow(ed.getWindowToken(), 0); 

for show keyboard

 imm.showSoftInput(ed, 0);

for focus on EditText

 ed.requestFocus();

where ed is EditText

Angular JS POST request not sending JSON data

If you are serializing your data object, it will not be a proper json object. Take what you have, and just wrap the data object in a JSON.stringify().

$http({
    url: '/user_to_itsr',
    method: "POST",
    data: JSON.stringify({application:app, from:d1, to:d2}),
    headers: {'Content-Type': 'application/json'}
}).success(function (data, status, headers, config) {
    $scope.users = data.users; // assign  $scope.persons here as promise is resolved here 
}).error(function (data, status, headers, config) {
    $scope.status = status + ' ' + headers;
});

Retrieving Android API version programmatically

Like this:

String versionRelease = BuildConfig.VERSION_NAME;

versionRelease :- 2.1.17

Please make sure your import package is correct ( import package your_application_package_name, otherwise it will not work properly).

Image re-size to 50% of original size in HTML

You can use the x descriptor of the srcset attribute as such:

_x000D_
_x000D_
<!-- Original image -->
<img src="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png" />

<!-- With a 80% size reduction (1/0.8=1.25) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 1.25x" />

<!-- With a 50% size reduction (1/0.5=2) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 2x" />
_x000D_
_x000D_
_x000D_

Currently supported by all browsers except IE. (caniuse)

MDN documentation

Java creating .jar file

way 1 :

Let we have java file test.java which contains main class testa now first we compile our java file simply as javac test.java we create file manifest.txt in same directory and we write Main-Class: mainclassname . e.g :

  Main-Class: testa

then we create jar file by this command :

  jar cvfm anyname.jar manifest.txt testa.class

then we run jar file by this command : java -jar anyname.jar

way 2 :

Let we have one package named one and every class are inside it. then we create jar file by this command :

  jar cf anyname.jar one

then we open manifest.txt inside directory META-INF in anyname.jar file and write

  Main-Class: one.mainclassname 

in third line., then we run jar file by this command :

  java -jar anyname.jar

to make jar file having more than one class file : jar cf anyname.jar one.class two.class three.class......

jQuery count number of divs with a certain class?

I just created this js function using the jQuery size function http://api.jquery.com/size/

function classCount(name){
  alert($('.'+name).size())
}

It alerts out the number of times the class name occurs in the document.

Pip - Fatal error in launcher: Unable to create process using '"'

D:\Python36\Scripts>pip3 -V
Fatal error in launcher: Unable to create process using '"'

D:\Python36\Scripts>python3 -m pip freeze
beautifulsoup4==4.5.1
bs4==0.0.1
Naked==0.1.31
pycrypto==2.6.1
PyYAML==3.12
requests==2.11.1
shellescape==3.4.1
You are using pip version 8.1.2, however version 9.0.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' comm
and.

D:\Python36\Scripts>python3 -m pip install --upgrade pip

D:\Python36\Scripts>pip3 -V
pip 9.0.1 from d:\python36\lib\site-packages (python 3.6)

How to add many functions in ONE ng-click?

You have 2 options :

  1. Create a third method that wrap both methods. Advantage here is that you put less logic in your template.

  2. Otherwise if you want to add 2 calls in ng-click you can add ';' after edit($index) like this

    ng-click="edit($index); open()"

See here : http://jsfiddle.net/laguiz/ehTy6/

Javascript - remove an array item by value

function removeValue(arr, value) {
    for(var i = 0; i < arr.length; i++) {
        if(arr[i] === value) {
            arr.splice(i, 1);
            break;
        }
    }
    return arr;
}

This can be called like so:

removeValue(tag_story, 90);

Batch file include external file for variables

So you just have to do this right?:

@echo off
echo text shizzle
echo.
echo pause^>nul (press enter)
pause>nul

REM writing to file
(
echo XD
echo LOL
)>settings.cdb
cls

REM setting the variables out of the file
(
set /p input=
set /p input2=
)<settings.cdb
cls

REM echo'ing the variables
echo variables:
echo %input%
echo %input2%
pause>nul

if %input%==XD goto newecho
DEL settings.cdb
exit

:newecho
cls
echo If you can see this, good job!
DEL settings.cdb
pause>nul
exit

grep from tar.gz without extracting [faster one]

For starters, you could start more than one process:

tar -ztf file.tar.gz | while read FILENAME
do
        (if tar -zxf file.tar.gz "$FILENAME" -O | grep -l "string"
        then
                echo "$FILENAME contains string"
        fi) &
done

The ( ... ) & creates a new detached (read: the parent shell does not wait for the child) process.

After that, you should optimize the extracting of your archive. The read is no problem, as the OS should have cached the file access already. However, tar needs to unpack the archive every time the loop runs, which can be slow. Unpacking the archive once and iterating over the result may help here:

local tempPath=`tempfile`
mkdir $tempPath && tar -zxf file.tar.gz -C $tempPath &&
find $tempPath -type f | while read FILENAME
do
        (if grep -l "string" "$FILENAME"
        then
                echo "$FILENAME contains string"
        fi) &
done && rm -r $tempPath

find is used here, to get a list of files in the target directory of tar, which we're iterating over, for each file searching for a string.

Edit: Use grep -l to speed up things, as Jim pointed out. From man grep:

   -l, --files-with-matches
          Suppress normal output; instead print the name of each input file from which output would
          normally have been printed.  The scanning will stop on the first match.  (-l is specified
          by POSIX.)

Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

I had tried almost all the above methods.

Finally fixed it by including the

script src="{%static 'App/js/jquery.js' %}"

just after loading the staticfiles i.e {% load staticfiles %} in base.html

jquery append div inside div with id and manipulate

You're overcomplicating things:

var e = $('<div style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
e.attr('id', 'myid');
$('#box').append(e);

For example: http://jsfiddle.net/ambiguous/Dm5J2/

Python: How do I make a subclass from a superclass?

Subclassing in Python is done as follows:

class WindowElement:
    def print(self):
        pass

class Button(WindowElement):
    def print(self):
        pass

Here is a tutorial about Python that also contains classes and subclasses.

Reading a cell value in Excel vba and write in another Cell

I have this function for this case ..

Function GetValue(r As Range, Tag As String) As Integer
Dim c, nRet As String
Dim n, x As Integer
Dim bNum As Boolean

c = r.Value
n = InStr(c, Tag)
For x = n + 1 To Len(c)
  Select Case Mid(c, x, 1)
    Case ":":    bNum = True
    Case " ": Exit For
    Case Else: If bNum Then nRet = nRet & Mid(c, x, 1)
  End Select
Next
GetValue = val(nRet)
End Function

To fill cell BC .. (assumed that you check cell A1)

Worksheets("Übersicht_2013").Cells(i, "BC") = GetValue(range("A1"),"S")

Javascript/jQuery detect if input is focused

Did you try:

$(this).is(':focus');

Take a look at Using jQuery to test if an input has focus it features some more examples

How can I get the console logs from the iOS Simulator?

iOS Simulator > Menu Bar > Debug > Open System Log


Old ways:

iOS Simulator prints its logs directly to stdout, so you can see the logs mixed up with system logs.

Open the Terminal and type: tail -f /var/log/system.log

Then run the simulator.

EDIT:

This stopped working on Mavericks/Xcode 5. Now you can access the simulator logs in its own folder: ~/Library/Logs/iOS Simulator/<sim-version>/system.log

You can either use the Console.app to see this, or just do a tail (iOS 7.0.3 64 bits for example):

tail -f ~/Library/Logs/iOS\ Simulator/7.0.3-64/system.log

EDIT 2:

They are now located in ~/Library/Logs/CoreSimulator/<simulator-hash>/system.log

tail -f ~/Library/Logs/CoreSimulator/<simulator-hash>/system.log

java.io.FileNotFoundException: (Access is denied)

You cannot open and read a directory, use the isFile() and isDirectory() methods to distinguish between files and folders. You can get the contents of folders using the list() and listFiles() methods (for filenames and Files respectively) you can also specify a filter that selects a subset of files listed.

Set Google Chrome as the debugging browser in Visual Studio

For MVC developers,

  • click on a folder in Solution Explorer (say, Controllers)
  • Select Browse With...
  • Select desired browser
  • (Optionally click ) set as Default

Getting URL hash location, and using it in jQuery

I'm using this to address the security implications noted in @CMS's answer.

// example 1: www.example.com/index.html#foo

// load correct subpage from URL hash if it exists
$(window).on('load', function () {
    var hash = window.location.hash;
    if (hash) {
        hash = hash.replace('#',''); // strip the # at the beginning of the string
        hash = hash.replace(/([^a-z0-9]+)/gi, '-'); // strip all non-alphanumeric characters
        hash = '#' + hash; // hash now equals #foo with example 1

        // do stuff with hash
        $( 'ul' + hash + ':first' ).show();
        // etc...
    }
});

How to I say Is Not Null in VBA

Use Not IsNull(Fields!W_O_Count.Value)

Wait for page load in Selenium

I'm surprised that predicates weren't the first choice as you typically know what element(s) you will next interact with on the page you're waiting to load. My approach has always been to build out predicates/functions like waitForElementByID(String id) and waitForElemetVisibleByClass(String className), etc. and then use and reuse these wherever I need them, be it for a page load or page content change I'm waiting on.

For example,

In my test class:

driverWait.until(textIsPresent("expectedText");

In my test class parent:

protected Predicate<WebDriver> textIsPresent(String text){
    final String t = text;
    return new Predicate<WebDriver>(){
        public boolean apply(WebDriver driver){
            return isTextPresent(t);
        }
    };
}

protected boolean isTextPresent(String text){
    return driver.getPageSource().contains(text);
}

Though this seems like a lot, it takes care of checking repeatedly for you and the interval for how often to check can be set along with the ultimate wait time before timing out. Also, you will reuse such methods.

In this example, the parent class defined and initiated the WebDriver driver and the WebDriverWait driverWait.

I hope this helps.

How can I pop-up a print dialog box using Javascript?

window.print();  

unless you mean a custom looking popup.

Weird PHP error: 'Can't use function return value in write context'

for WORDPRESS:

instead of:

if (empty(get_option('smth')))

should be:

if (!get_option('smth'))

Convert a String to int?

You can use the FromStr trait's from_str method, which is implemented for i32:

let my_num = i32::from_str("9").unwrap_or(0);

Using Git with Visual Studio

TortoiseGit has matured and I recommend it especially if you have used TortoiseSVN.

How to add external fonts to android application

Create a folder named fonts in the assets folder and add the snippet from the below link.

Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/fontname.ttf");
textview.setTypeface(tf);

How can I get a list of all classes within current module in Python?

What about

g = globals().copy()
for name, obj in g.iteritems():

?

npm install doesn't create node_modules directory

If you have a package-lock.json file, you may have to delete that file then run npm i. That worked for me

Get user info via Google API

scope - https://www.googleapis.com/auth/userinfo.profile

return youraccess_token = access_token

get https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=youraccess_token

you will get json:

{
 "id": "xx",
 "name": "xx",
 "given_name": "xx",
 "family_name": "xx",
 "link": "xx",
 "picture": "xx",
 "gender": "xx",
 "locale": "xx"
}

To Tahir Yasin:

This is a php example.
You can use json_decode function to get userInfo array.

$q = 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=xxx';
$json = file_get_contents($q);
$userInfoArray = json_decode($json,true);
$googleEmail = $userInfoArray['email'];
$googleFirstName = $userInfoArray['given_name'];
$googleLastName = $userInfoArray['family_name'];

multiple packages in context:component-scan, spring config

The following approach is correct:

<context:component-scan base-package="x.y.z.service, x.y.z.controller" /> 

Note that the error complains about x.y.z.dao.daoservice.LoginDAO, which is not in the packages mentioned above, perhaps you forgot to add it:

<context:component-scan base-package="x.y.z.service, x.y.z.controller, x.y.z.dao" /> 

Virtual network interface in Mac OS X

i have resorted to running PFSense, a BSD based router/firewall to achieve this goal….

why? because OS X Server gets so FREAKY without a Static IP…

so after wrestling with it for DAYS to make NAT and DHCP and firewall and …

I'm trying this is parallels…

will let ya know how it goes...

Difference between View and ViewGroup in Android

A View object is a component of the user interface (UI) like a button or a text box, and it's also called widget.

A ViewGroup object is a layout, that is, a container of other ViewGroup objects (layouts) and View objects (widgets). It's possible to have a layout inside another layout. It's called nested layout but it can increase the time needed to draw the user interface.

The user interface for an app is built using a hierarchy of ViewGroup and View objects. In Android Studio it is possible to use the Component Tree window to visualise this hierarchy.

The Layout Editor in Android Studio can be used to drag and drop View objects (widgets) in the layout. It simplifies the creation of a layout.

Difference between git pull and git pull --rebase

Suppose you have two commits in local branch:

      D---E master
     /
A---B---C---F origin/master

After "git pull", will be:

      D--------E  
     /          \
A---B---C---F----G   master, origin/master

After "git pull --rebase", there will be no merge point G. Note that D and E become different commits:

A---B---C---F---D'---E'   master, origin/master

How to save an image to localStorage and display it on the next page?

I have come up with the same issue, instead of storing images, that eventually overflow the local storage, you can just store the path to the image. something like:

let imagen = ev.target.getAttribute('src');
arrayImagenes.push(imagen);

How to launch Safari and open URL from iOS app

Try this:

NSString *URL = @"xyz.com";
if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:URL]])
{
     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:URL]];
}

Click a button programmatically - JS

The other answers here rely on the user making an initial click (on the image). This is fine for the specifics of the OP detail but not necessarily the question title.

There is an answer here explaining how to do it by firing a click event on the button ( or any element ).

How to print instances of a class using print()?

>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
... 
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test

The __str__ method is what happens when you print it, and the __repr__ method is what happens when you use the repr() function (or when you look at it with the interactive prompt). If this isn't the most Pythonic method, I apologize, because I'm still learning too - but it works.

If no __str__ method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__, Python will use what you see above as the __repr__, but still use __str__ for printing.

SQL permissions for roles

SQL-Server follows the principle of "Least Privilege" -- you must (explicitly) grant permissions.

'does it mean that they wont be able to update 4 and 5 ?'

If your users in the doctor role are only in the doctor role, then yes.

However, if those users are also in other roles (namely, other roles that do have access to 4 & 5), then no.

More Information: http://msdn.microsoft.com/en-us/library/bb669084%28v=vs.110%29.aspx

Angular IE Caching issue for $http

The guaranteed one that I had working was something along these lines:

myModule.config(['$httpProvider', function($httpProvider) {
    if (!$httpProvider.defaults.headers.common) {
        $httpProvider.defaults.headers.common = {};
    }
    $httpProvider.defaults.headers.common["Cache-Control"] = "no-cache";
    $httpProvider.defaults.headers.common.Pragma = "no-cache";
    $httpProvider.defaults.headers.common["If-Modified-Since"] = "Mon, 26 Jul 1997 05:00:00 GMT";
}]);

I had to merge 2 of the above solutions in order to guarantee the correct usage for all methods, but you can replace common with get or other method i.e. put, post, delete to make this work for different cases.

Easiest way to ignore blank lines when reading a file in Python

You could use list comprehension:

with open("names", "r") as f:
    names_list = [line.strip() for line in f if line.strip()]

Updated: Removed unnecessary readlines().

To avoid calling line.strip() twice, you can use a generator:

names_list = [l for l in (line.strip() for line in f) if l]

You have to be inside an angular-cli project in order to use the build command after reinstall of angular-cli

Same as John Pankowicz answer, but in my case I had to run

npm install -g @angular/cli@latest

for the versions to match.

How do I install TensorFlow's tensorboard?

It may be helpful to make an alias for it.

Install and find your tensorboard location:

pip install tensorboard
pip show tensorboard

Add the following alias in .bashrc:

alias tensorboard='python pathShownByPip/tensorboard/main.py'

Open another terminal or run exec bash.

For Windows users, cd into pathShownByPip\tensorboard and run python main.py from there.

For Python 3.x, use pip3 instead of pip, and don't forget to use python3 in the alias.

Run php function on button click

<a href="home.php?click=1" class="btn">Click me</a>
<?php 
  if($_GET['click']){
    doSomething();
  }
?>

But is better to use JS and with ajax to call function!

how can select from drop down menu and call javascript function

Greetings if i get you right you need a JavaScript function that doing it

function report(v) {
//To Do
  switch(v) {
    case "daily":
      //Do something
      break;
    case "monthly":
      //Do somthing
      break;
    }
  }

Regards

What is special about /dev/tty?

/dev/tty is a synonym for the controlling terminal (if any) of the current process. As jtl999 says, it's a character special file; that's what the c in the ls -l output means.

man 4 tty or man -s 4 tty should give you more information, or you can read the man page online here.

Incidentally, pwd > /dev/tty doesn't necessarily print to the shell's stdout (though it is the pwd command's standard output). If the shell's standard output has been redirected to something other than the terminal, /dev/tty still refers to the terminal.

You can also read from /dev/tty, which will normally read from the keyboard.

What does the "no version information available" error from linux dynamic linker mean?

What this message from the glibc dynamic linker actually means is that the library mentioned (/lib/libpam.so.0 in your case) doesn't have the VERDEF ELF section while the binary (authpam in your case) has some version definitions in VERNEED section for this library (presumably, libpam.so.0). You can easily see it with readelf, just look at .gnu.version_d and .gnu.version_r sections (or lack thereof).

So it's not a symbol version mismatch, because if the binary wanted to get some specific version via VERNEED and the library didn't provide it in its actual VERDEF, that would be a hard linker error and the binary wouldn't run at all (like this compared to this or that). It's that the binary wants some versions, but the library doesn't provide any information about its versions.

What does it mean in practice? Usually, exactly what is seen in this example — nothing, things just work ignoring versioning. Could things break? Of course, yes, so the other answers are correct in the fact that one should use the same libraries at runtime as the ones the binary was linked to at build time.

More information could be found in Ulrich Dreppers "ELF Symbol Versioning".

Pretty-Print JSON in Java

Pretty printing with GSON in one line:

System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(new JsonParser().parse(jsonString)));

Besides inlining, this is equivalent to the accepted answer.

How to get File Created Date and Modified Date

You can use this code to see the last modified date of a file.

DateTime dt = File.GetLastWriteTime(path);

And this code to see the creation time.

DateTime fileCreatedDate = File.GetCreationTime(@"C:\Example\MyTest.txt");

An item with the same key has already been added

Another way to encounter this error is from a dataset with unnamed columns. The error is thrown when the dataset is serialized into JSON.

This statement will result in error:

select @column1, @column2

Adding column names will prevent the error:

select @column1 as col1, @column2 as col2

How to create a temporary directory and get the path / file name in Python

Use the mkdtemp() function from the tempfile module:

import tempfile
import shutil

dirpath = tempfile.mkdtemp()
# ... do stuff with dirpath
shutil.rmtree(dirpath)

How to get Java Decompiler / JD / JD-Eclipse running in Eclipse Helios

I am using Eclipse 3.7 Indigo and Windows 7 64-bit:

What I did was to install the Microsoft Visual C++ 2008 SP1 Redistributable Package as suggested by the site and reminded by @Universalspezialist.

Then install the plugin as stated in the site: http://java.decompiler.free.fr/?q=jdeclipse

Go to preference, then find "File Associations" Click on the *.class, then set the "class File Editor" as default.

Restart Eclipse perhaps? (I did this, but I'm not sure if it's necessary or not)

Setting onClickListener for the Drawable right of an EditText

You don't have access to the right image as far my knowledge, unless you override the onTouch event. I suggest to use a RelativeLayout, with one editText and one imageView, and set OnClickListener over the image view as below:

<RelativeLayout
        android:id="@+id/rlSearch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:drawable/edit_text"
        android:padding="5dip" >

        <EditText
            android:id="@+id/txtSearch"
            android:layout_width="match_parent"

            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@+id/imgSearch"
            android:background="#00000000"
            android:ems="10"/>

        <ImageView
            android:id="@+id/imgSearch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:src="@drawable/btnsearch" />
    </RelativeLayout>

Defining static const integer members in class definition

My understanding is that C++ allows static const members to be defined inside a class so long as it's an integer type.

You are sort of correct. You are allowed to initialize static const integrals in the class declaration but that is not a definition.

http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/cplr038.htm

Interestingly, if I comment out the call to std::min, the code compiles and links just fine (even though test::N is also referenced on the previous line).

Any idea as to what's going on?

std::min takes its parameters by const reference. If it took them by value you'd not have this problem but since you need a reference you also need a definition.

Here's chapter/verse:

9.4.2/4 - If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

See Chu's answer for a possible workaround.

Simulate string split function in Excel formula

A formula to return either the first word or all the other words.

=IF(ISERROR(FIND(" ",TRIM(A2),1)),TRIM(A2),MID(TRIM(A2),FIND(" ",TRIM(A2),1),LEN(A2)))

Examples and results

Text                  Description                      Results

                      Blank 
                      Space 
some                  Text no space                some
some text             Text with space                  text
 some                 Text with leading space          some
some                  Text with trailing space         some
some text some text   Text with multiple spaces        text some text

Comments on Formula:

  • The TRIM function is used to remove all leading and trailing spaces. Duplicate spacing within the text is also removed.
  • The FIND function then finds the first space
  • If there is no space then the trimmed text is returned
  • Otherwise the MID function is used to return any text after the first space

PHP Fatal error: Cannot access empty property

To access a variable in a class, you must use $this->myVar instead of $this->$myvar.

And, you should use access identifier to declare a variable instead of var.

Please read the doc here.

How to scroll up or down the page to an anchor using jQuery?

following solution worked for me:

$("a[href^=#]").click(function(e)
        {
            e.preventDefault();
            var aid = $(this).attr('href');
            console.log(aid);
            aid = aid.replace("#", "");
            var aTag = $("a[name='"+ aid +"']");
            if(aTag == null || aTag.offset() == null)
                aTag = $("a[id='"+ aid +"']");

            $('html,body').animate({scrollTop: aTag.offset().top}, 1000);
        }
    );

How to say no to all "do you want to overwrite" prompts in a batch file copy?

Depending on the size and number of files being copied, you could copy the destination directory over the source first with "yes to all", then do the original copy you were doing, also with "yes to all" set. That should give you the same results.

How do I interpret precision and scale of a number in a database?

Precision, Scale, and Length in the SQL Server 2000 documentation reads:

Precision is the number of digits in a number. Scale is the number of digits to the right of the decimal point in a number. For example, the number 123.45 has a precision of 5 and a scale of 2.

How does origin/HEAD get set?

Remember there are two independent git repos we are talking about. Your local repo with your code and the remote running somewhere else.

Your are right, when you change a branch, HEAD points to your current branch. All of this is happening on your local git repo. Not the remote repo, which could be owned by another developer, or siting on a sever in your office, or github, or another directory on the filesystem, or etc...

Your computer (local repo) has no business changing the HEAD pointer on the remote git repo. It could be owned by a different developer for example.

One more thing, what your computer calls origin/XXX is your computer's understanding of the state of the remote at the time of the last fetch.

So what would "organically" update origin/HEAD? It would be activity on the remote git repo. Not your local repo.

People have mentioned

git symbolic-ref HEAD refs/head/my_other_branch

Normally, that is used when there is a shared central git repo on a server for use by the development team. It would be a command executed on the remote computer. You would see this as activity on the remote git repo.

How to add headers to a multicolumn listbox in an Excel userform using VBA

You can give this a try. I am quite new to the forum but wanted to offer something that worked for me since I've gotten so much help from this site in the past. This is essentially a variation of the above, but I found it simpler.

Just paste this into the Userform_Initialize section of your userform code. Note you must already have a listbox on the userform or have it created dynamically above this code. Also please note the Array is a list of headings (below as "Header1", "Header2" etc. Replace these with your own headings. This code will then set up a heading bar at the top based on the column widths of the list box. Sorry it doesn't scroll - it's fixed labels.

More senior coders - please feel free to comment or improve this.

    Dim Mywidths As String
    Dim Arrwidths, Arrheaders As Variant
    Dim ColCounter, Labelleft As Long
    Dim theLabel As Object                

    [Other code here that you would already have in the Userform_Initialize section]

    Set theLabel = Me.Controls.Add("Forms.Label.1", "Test" & ColCounter, True)
            With theLabel
                    .Left = ListBox1.Left
                    .Top = ListBox1.Top - 10
                    .Width = ListBox1.Width - 1
                    .Height = 10
                    .BackColor = RGB(200, 200, 200)
            End With
            Arrheaders = Array("Header1", "Header2", "Header3", "Header4")

            Mywidths = Me.ListBox1.ColumnWidths
            Mywidths = Replace(Mywidths, " pt", "")
            Arrwidths = Split(Mywidths, ";")
            Labelleft = ListBox1.Left + 18
            For ColCounter = LBound(Arrwidths) To UBound(Arrwidths)
                        If Arrwidths(ColCounter) > 0 Then
                                Header = Header + 1
                                Set theLabel = Me.Controls.Add("Forms.Label.1", "Test" & ColCounter, True)

                                With theLabel
                                    .Caption = Arrheaders(Header - 1)
                                    .Left = Labelleft
                                    .Width = Arrwidths(ColCounter)
                                    .Height = 10
                                    .Top = ListBox1.Top - 10
                                    .BackColor = RGB(200, 200, 200)
                                    .Font.Bold = True
                                End With
                                 Labelleft = Labelleft + Arrwidths(ColCounter)

                        End If
             Next

Multiple arguments to function called by pthread_create()?

Since asking the same question but for C++ is considered a duplicate I might as well supply C++ code as an answer.

//  hello-2args.cpp
// https://stackoverflow.com/questions/1352749
#include <iostream>
#include <omp.h>
#include <pthread.h>
using namespace std;

typedef struct thread_arguments {
  int thrnr;
  char *msg;
} thargs_t;

void *print_hello(void *thrgs) {
  cout << ((thargs_t*)thrgs)->msg << ((thargs_t*)thrgs)->thrnr << "\n";
  pthread_exit(NULL);
}

int main(int argc, char *argv[]) {
  cout << " Hello C++!\n";
  const int NR_THRDS = omp_get_max_threads();
  pthread_t threads[NR_THRDS];
  thargs_t thrgs[NR_THRDS];
  for(int t=0;t<NR_THRDS;t++) {
    thrgs[t].thrnr = t;
    thrgs[t].msg = (char*)"Hello World. - It's me! ... thread #";
    cout << "In main: creating thread " << t << "\n";
    pthread_create(&threads[t], NULL, print_hello, &thrgs[t]);
  }
  for(int t=0;t<NR_THRDS;t++) {
    pthread_join(threads[t], NULL);
  }
  cout << "After join: I am always last. Byebye!\n";
  return EXIT_SUCCESS;
}

Compile and run by using one of the following:

g++ -fopenmp -pthread hello-2args.cpp && ./a.out # Linux
g++ -fopenmp -pthread hello-2args.cpp && ./a.exe # MSYS2, Windows

Meaning of 'const' last in a function declaration of a class?

When you add the const keyword to a method the this pointer will essentially become a pointer to const object, and you cannot therefore change any member data. (Unless you use mutable, more on that later).

The const keyword is part of the functions signature which means that you can implement two similar methods, one which is called when the object is const, and one that isn't.

#include <iostream>

class MyClass
{
private:
    int counter;
public:
    void Foo()
    { 
        std::cout << "Foo" << std::endl;    
    }

    void Foo() const
    {
        std::cout << "Foo const" << std::endl;
    }

};

int main()
{
    MyClass cc;
    const MyClass& ccc = cc;
    cc.Foo();
    ccc.Foo();
}

This will output

Foo
Foo const

In the non-const method you can change the instance members, which you cannot do in the const version. If you change the method declaration in the above example to the code below you will get some errors.

    void Foo()
    {
        counter++; //this works
        std::cout << "Foo" << std::endl;    
    }

    void Foo() const
    {
        counter++; //this will not compile
        std::cout << "Foo const" << std::endl;
    }

This is not completely true, because you can mark a member as mutable and a const method can then change it. It's mostly used for internal counters and stuff. The solution for that would be the below code.

#include <iostream>

class MyClass
{
private:
    mutable int counter;
public:

    MyClass() : counter(0) {}

    void Foo()
    {
        counter++;
        std::cout << "Foo" << std::endl;    
    }

    void Foo() const
    {
        counter++;    // This works because counter is `mutable`
        std::cout << "Foo const" << std::endl;
    }

    int GetInvocations() const
    {
        return counter;
    }
};

int main(void)
{
    MyClass cc;
    const MyClass& ccc = cc;
    cc.Foo();
    ccc.Foo();
    std::cout << "Foo has been invoked " << ccc.GetInvocations() << " times" << std::endl;
}

which would output

Foo
Foo const
Foo has been invoked 2 times