Programs & Examples On #Grid layout

Grid layout is used to align content into columns and fields. Unlike table layouts, grids are composed of guide lines so that elements positioned relative to the grid can have drag and drop behavior.

Grid of responsive squares

You can make responsive grid of squares with verticaly and horizontaly centered content only with CSS. I will explain how in a step by step process but first here are 2 demos of what you can achieve :

Responsive 3x3 square grid Responsive square images in a 3x3 grid

Now let's see how to make these fancy responsive squares!



1. Making the responsive squares :

The trick for keeping elements square (or whatever other aspect ratio) is to use percent padding-bottom.
Side note: you can use top padding too or top/bottom margin but the background of the element won't display.

As top padding is calculated according to the width of the parent element (See MDN for reference), the height of the element will change according to its width. You can now Keep its aspect ratio according to its width.
At this point you can code :

HTML :

 <div></div>

CSS

div {
    width: 30%;
    padding-bottom: 30%; /* = width for a square aspect ratio */
}

Here is a simple layout example of 3*3 squares grid using the code above.

With this technique, you can make any other aspect ratio, here is a table giving the values of bottom padding according to the aspect ratio and a 30% width.

 Aspect ratio  |  padding-bottom  |  for 30% width
------------------------------------------------
    1:1        |  = width         |    30%
    1:2        |  width x 2       |    60%
    2:1        |  width x 0.5     |    15%
    4:3        |  width x 0.75    |    22.5%
    16:9       |  width x 0.5625  |    16.875%




2. Adding content inside the squares

As you can't add content directly inside the squares (it would expand their height and squares wouldn't be squares anymore) you need to create child elements (for this example I am using divs) inside them with position: absolute; and put the content inside them. This will take the content out of the flow and keep the size of the square.

Don't forget to add position:relative; on the parent divs so the absolute children are positioned/sized relatively to their parent.

Let's add some content to our 3x3 grid of squares :

HTML :

<div class="square">
    <div class="content">
        .. CONTENT HERE ..
    </div>
</div>
... and so on 9 times for 9 squares ...

CSS :

.square {
    float:left;
    position: relative;
    width: 30%;
    padding-bottom: 30%; /* = width for a 1:1 aspect ratio */
    margin:1.66%;
    overflow:hidden;
}

.content {
    position:absolute;
    height:80%; /* = 100% - 2*10% padding */
    width:90%; /* = 100% - 2*5% padding */
    padding: 10% 5%;
}

RESULT <-- with some formatting to make it pretty!



3.Centering the content

Horizontally :

This is pretty easy, you just need to add text-align:center to .content.
RESULT

Vertical alignment

This becomes serious! The trick is to use

display:table;
/* and */
display:table-cell;
vertical-align:middle;

but we can't use display:table; on .square or .content divs because it conflicts with position:absolute; so we need to create two children inside .content divs. Our code will be updated as follow :

HTML :

<div class="square">
    <div class="content">
        <div class="table">
            <div class="table-cell">
                ... CONTENT HERE ...
            </div>
        </div>
    </div>
</div>
... and so on 9 times for 9 squares ...

CSS :

.square {
    float:left;
    position: relative;
    width: 30%;
    padding-bottom : 30%; /* = width for a 1:1 aspect ratio */
    margin:1.66%;
    overflow:hidden;
}

.content {
    position:absolute;
    height:80%; /* = 100% - 2*10% padding */
    width:90%; /* = 100% - 2*5% padding */
    padding: 10% 5%;
}
.table{
    display:table;
    height:100%;
    width:100%;
}
.table-cell{
    display:table-cell;
    vertical-align:middle;
    height:100%;
    width:100%;
}




We have now finished and we can take a look at the result here :

LIVE FULLSCREEN RESULT

editable fiddle here


Load arrayList data into JTable

You can do something like what i did with my List< Future< String > > or any other Arraylist, Type returned from other class called PingScan that returns List> because it implements service executor. Anyway the code down note that you can use foreach and retrieve data from the List.

 PingScan p = new PingScan();
 List<Future<String>> scanResult = p.checkThisIP(jFormattedTextField1.getText(), jFormattedTextField2.getText());
                for (final Future<String> f : scanResult) {
                    try {
                        if (f.get() instanceof String) {
                            String ip = f.get();
                            Object[] data = {ip};
                            tableModel.addRow(data);
                        }
                    } catch (InterruptedException | ExecutionException ex) {
                        Logger.getLogger(gui.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

Bootstrap 4, how to make a col have a height of 100%?

I came across this problem because my cols exceeded the row grid length (> 12)

A solution using 100% Bootstrap 4:

Since the rows in Bootstrap are already display: flex

You just need to add flex-fill to the Col, and h-100 to the container and any children.

Pen here: https://codepen.io/joshkopecek/pen/Exjdgjo

<div class="container-fluid h-100">
  <div class="row justify-content-center h-100">

    <div class="col-4 hidden-md-down flex-fill" id="yellow">
      XXXX
    </div>

    <div id="blue" class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8 h-100">
      Form Goes Here
    </div>

    <div id="green" class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8 h-100">
      Another form
    </div>
  </div>
</div>

Prevent content from expanding grid items

The previous answer is pretty good, but I also wanted to mention that there is a fixed layout equivalent for grids, you just need to write minmax(0, 1fr) instead of 1fr as your track size.

Flex-box: Align last row to grid

Assuming:

  • You want 4 column grid layout with wrapping
  • The number of items is not necessarily a multiple of 4

Set a left margin on every item except 1st, 5th and 9th item and so on. If the left margin is 10px then each row will have 30px margin distributed among 4 items. The percentage width for item is calculated as follows:

100% / 4 - horizontal-border - horizontal-padding - left-margin * (4 - 1) / 4

This is a decent workaround for issues involving last row of flexbox.

_x000D_
_x000D_
.flex {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  flex-wrap: wrap;_x000D_
  margin: 1em 0 3em;_x000D_
  background-color: peachpuff;_x000D_
}_x000D_
_x000D_
.item {_x000D_
  margin-left: 10px;_x000D_
  border: 1px solid;_x000D_
  padding: 10px;_x000D_
  width: calc(100% / 4 - 2px - 20px - 10px * (4 - 1) / 4);_x000D_
  background-color: papayawhip;_x000D_
}_x000D_
_x000D_
.item:nth-child(4n + 1) {_x000D_
  margin-left: 0;_x000D_
}_x000D_
_x000D_
.item:nth-child(n + 5) {_x000D_
  margin-top: 10px;_x000D_
}
_x000D_
<div class="flex">_x000D_
  <div class="item">1</div>_x000D_
  <div class="item">2</div>_x000D_
  <div class="item">3</div>_x000D_
  <div class="item">4</div>_x000D_
</div>_x000D_
<div class="flex">_x000D_
  <div class="item">1</div>_x000D_
  <div class="item">2</div>_x000D_
  <div class="item">3</div>_x000D_
  <div class="item">4</div>_x000D_
  <div class="item">5</div>_x000D_
  <div class="item">6</div>_x000D_
</div>_x000D_
<div class="flex">_x000D_
  <div class="item">1</div>_x000D_
  <div class="item">2</div>_x000D_
  <div class="item">3</div>_x000D_
  <div class="item">4</div>_x000D_
  <div class="item">5</div>_x000D_
  <div class="item">6</div>_x000D_
  <div class="item">7</div>_x000D_
  <div class="item">8</div>_x000D_
  <div class="item">9</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

GridView VS GridLayout in Android Apps

A GridView is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.

This is what you'd want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen. GridViews, much like ListViews reuse and recycle their views for better performance.

Whereas a GridLayout is a layout that places its children in a rectangular grid.

It was introduced in API level 14, and was recently backported in the Support Library. Its main purpose is to solve alignment and performance problems in other layouts. Check out this tutorial if you want to learn more about GridLayout.

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

Equal height rows in CSS Grid Layout

The short answer is that setting grid-auto-rows: 1fr; on the grid container solves what was asked.

https://codepen.io/Hlsg/pen/EXKJba

How can I copy a file on Unix using C?

There is no baked-in equivalent CopyFile function in the APIs. But sendfile can be used to copy a file in kernel mode which is a faster and better solution (for numerous reasons) than opening a file, looping over it to read into a buffer, and writing the output to another file.

Update:

As of Linux kernel version 2.6.33, the limitation requiring the output of sendfile to be a socket was lifted and the original code would work on both Linux and — however, as of OS X 10.9 Mavericks, sendfile on OS X now requires the output to be a socket and the code won't work!

The following code snippet should work on the most OS X (as of 10.5), (Free)BSD, and Linux (as of 2.6.33). The implementation is "zero-copy" for all platforms, meaning all of it is done in kernelspace and there is no copying of buffers or data in and out of userspace. Pretty much the best performance you can get.

#include <fcntl.h>
#include <unistd.h>
#if defined(__APPLE__) || defined(__FreeBSD__)
#include <copyfile.h>
#else
#include <sys/sendfile.h>
#endif

int OSCopyFile(const char* source, const char* destination)
{    
    int input, output;    
    if ((input = open(source, O_RDONLY)) == -1)
    {
        return -1;
    }    
    if ((output = creat(destination, 0660)) == -1)
    {
        close(input);
        return -1;
    }

    //Here we use kernel-space copying for performance reasons
#if defined(__APPLE__) || defined(__FreeBSD__)
    //fcopyfile works on FreeBSD and OS X 10.5+ 
    int result = fcopyfile(input, output, 0, COPYFILE_ALL);
#else
    //sendfile will work with non-socket output (i.e. regular file) on Linux 2.6.33+
    off_t bytesCopied = 0;
    struct stat fileinfo = {0};
    fstat(input, &fileinfo);
    int result = sendfile(output, input, &bytesCopied, fileinfo.st_size);
#endif

    close(input);
    close(output);

    return result;
}

EDIT: Replaced the opening of the destination with the call to creat() as we want the flag O_TRUNC to be specified. See comment below.

Insert value into a string at a certain position?

If you just want to insert a value at a certain position in a string, you can use the String.Insert method:

public string Insert(int startIndex, string value)

Example:

"abc".Insert(2, "XYZ") == "abXYZc"

Refreshing all the pivot tables in my excel workbook with a macro

The code

Private Sub Worksheet_Activate()
    Dim PvtTbl As PivotTable
        Cells.EntireColumn.AutoFit
        For Each PvtTbl In Worksheets("Sales Details").PivotTables
        PvtTbl.RefreshTable
        Next
End Sub 

works fine.

The code is used in the activate sheet module, thus it displays a flicker/glitch when the sheet is activated.

Simple (I think) Horizontal Line in WPF?

For anyone else struggling with this: Qwertie's comment worked well for me.

<Border Width="1" Margin="2" Background="#8888"/>

This creates a vertical seperator which you can talior to suit your needs.

I can’t find the Android keytool

No need to use the command line.

If you FILE-> "Export Android Application" in the ADK then it will allow you to create a key and then produce your .apk file.

Writing a VLOOKUP function in vba

        Public Function VLOOKUP1(ByVal lookup_value As String, ByVal table_array As Range, ByVal col_index_num As Integer) As String
        Dim i As Long

        For i = 1 To table_array.Rows.Count
            If lookup_value = table_array.Cells(table_array.Row + i - 1, 1) Then
                VLOOKUP1 = table_array.Cells(table_array.Row + i - 1, col_index_num)
                Exit For
            End If
        Next i

        End Function

How to tell CRAN to install package dependencies automatically?

On your own system, try

install.packages("foo", dependencies=...)

with the dependencies= argument is documented as

dependencies: logical indicating to also install uninstalled packages
      which these packages depend on/link to/import/suggest (and so
      on recursively).  Not used if ‘repos = NULL’.  Can also be a
      character vector, a subset of ‘c("Depends", "Imports",
      "LinkingTo", "Suggests", "Enhances")’.

      Only supported if ‘lib’ is of length one (or missing), so it
      is unambiguous where to install the dependent packages.  If
      this is not the case it is ignored, with a warning.

      The default, ‘NA’, means ‘c("Depends", "Imports",
      "LinkingTo")’.

      ‘TRUE’ means (as from R 2.15.0) to use ‘c("Depends",
      "Imports", "LinkingTo", "Suggests")’ for ‘pkgs’ and
      ‘c("Depends", "Imports", "LinkingTo")’ for added
      dependencies: this installs all the packages needed to run
      ‘pkgs’, their examples, tests and vignettes (if the package
      author specified them correctly).

so you probably want a value TRUE.

In your package, list what is needed in Depends:, see the Writing R Extensions manual which is pretty clear on this.

How to install SQL Server Management Studio 2012 (SSMS) Express?

You need to install ENU\x64\SQLEXPRWT_x64_ENU.exe which is Express with Tools (RTM release. SP1 release can be found here).

As the page states

Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express) This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.

So install this and use the management studio included with it.

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

I inspired myself from @maxisam's answer and created my own sort function and I'd though I'd share it (cuz I'm bored).

Situation I want to filter through an array of cars. The selected properties to filter are name, year, price and km. The property price and km are numbers (hence the use of .toString). I also want to control for uppercase letters (hence .toLowerCase). Also I want to be able to split up my filter query into different words (e.g. given the filter 2006 Acura, it finds matches 2006 with the year and Acura with the name).

Function I pass to filter

        var attrs = [car.name.toLowerCase(), car.year, car.price.toString(), car.km.toString()],
            filters = $scope.tableOpts.filter.toLowerCase().split(' '),
            isStringInArray = function (string, array){
                for (var j=0;j<array.length;j++){
                    if (array[j].indexOf(string)!==-1){return true;}
                }
                return false;
            };

        for (var i=0;i<filters.length;i++){
            if (!isStringInArray(filters[i], attrs)){return false;}
        }
        return true;
    };

Cannot find vcvarsall.bat when running a Python script

Note that there is a very simple solution.

  1. Download the software from http://www.microsoft.com/en-us/download/details.aspx?id=44266 and install it.

  2. Find the installing directory, it is something like "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python"

  3. Change the directory name "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0" to "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\VC"

  4. Add a new environment variable "VS90COMNTOOLS" and its value is "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\VC\VC"

Now everything is OK.

When to use in vs ref vs out

Still feel the need for a good summary, this is what I came up with.

Summary,

When we are inside the function, this is how we specify the variable data access control,

in = R

out = must W before R

ref = R+W


Explanation,

in

Function may only READ that variable.

out

Variable must not be initialised first because,
function MUST WRITE to it before READ.

ref

Function may READ/WRITE to that variable.


Why is it named as such?

Focusing on where data gets modified,

in

Data must only be set before entering (in) function.

out

Data must only be set before leaving (out) function.

ref

Data must be set before entering (in) function.
Data may be set before leaving (out) function.

SSIS Excel Connection Manager failed to Connect to the Source

It seems like the 32-bit version of Excel was not installed. Remember that SSDT is a 32-bit IDE. Therefore, when data is access from SSDT the 32-bit data providers are used. When running the package outside of SSDT it runs in 64-bit mode (not always, but mostly) and uses the 64-bit data providers.

Always keep in mind that if you want to run your package in 64-bit (which you should aim for) you will need both the 32-bit data providers (for development in SSDT) as well as the 64-bit data providers (for executing the package in production).

I downloaded the 32-bit access drivers from:

After installation, I could see the worksheets


Source:

Compare integer in bash, unary operator expected

I need to add my 5 cents. I see everybody use [ or [[, but it worth to mention that they are not part of if syntax.

For arithmetic comparisons, use ((...)) instead.

((...)) is an arithmetic command, which returns an exit status of 0 if the expression is nonzero, or 1 if the expression is zero. Also used as a synonym for "let", if side effects (assignments) are needed.

See: ArithmeticExpression

How to deal with the URISyntaxException

I had this exception in the case of a test for checking some actual accessed URLs by users.

And the URLs are sometime contains an illegal-character and hang by this error.

So I make a function to encode only the characters in the URL string like this.

String encodeIllegalChar(String uriStr,String enc)
  throws URISyntaxException,UnsupportedEncodingException {
  String _uriStr = uriStr;
  int retryCount = 17;
  while(true){
     try{
       new URI(_uriStr);
       break;
     }catch(URISyntaxException e){
       String reason = e.getReason();
       if(reason == null ||
         !(
          reason.contains("in path") ||
          reason.contains("in query") ||
          reason.contains("in fragment")
         )
       ){
         throw e;
       }
       if(0 > retryCount--){
         throw e;
       }
       String input = e.getInput();
       int idx = e.getIndex();
       String illChar = String.valueOf(input.charAt(idx));
       _uriStr = input.replace(illChar,URLEncoder.encode(illChar,enc));
     }
  }
  return _uriStr;
}

test:

String q =  "\\'|&`^\"<>)(}{][";
String url = "http://test.com/?q=" + q + "#" + q;
String eic = encodeIllegalChar(url,'UTF-8');
System.out.println(String.format("  original:%s",url));
System.out.println(String.format("   encoded:%s",eic));
System.out.println(String.format("   uri-obj:%s",new URI(eic)));
System.out.println(String.format("re-decoded:%s",URLDecoder.decode(eic)));

How do I remove version tracking from a project cloned from git?

You can also remove all the git related stuff using one command. The .gitignore file will also be deleted with this one.

rm -rf .git*

Facebook page automatic "like" URL (for QR Code)

In my opinion, it is not possible for the like button (and I hope it is not possible).

But, you can trigger a custom OpenGraph v2 action, or display a like button linked to your facebook page.

Setting href attribute at runtime

In jQuery 1.6+ it's better to use:

$(selector).prop('href',"http://www...") to set the value, and

$(selector).prop('href') to get the value

In short, .prop gets and sets values on the DOM object, and .attr gets and sets values in the HTML. This makes .prop a little faster and possibly more reliable in some contexts.

How to store images in mysql database using php

I found the answer, For those who are looking for the same thing here is how I did it. You should not consider uploading images to the database instead you can store the name of the uploaded file in your database and then retrieve the file name and use it where ever you want to display the image.

HTML CODE

<input type="file" name="imageUpload" id="imageUpload">

PHP CODE

if(isset($_POST['submit'])) {

    //Process the image that is uploaded by the user

    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

    if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }

    $image=basename( $_FILES["imageUpload"]["name"],".jpg"); // used to store the filename in a variable

    //storind the data in your database
    $query= "INSERT INTO items VALUES ('$id','$title','$description','$price','$value','$contact','$image')";
    mysql_query($query);

    require('heading.php');
    echo "Your add has been submited, you will be redirected to your account page in 3 seconds....";
    header( "Refresh:3; url=account.php", true, 303);
}

CODE TO DISPLAY THE IMAGE

while($row = mysql_fetch_row($result)) {
    echo "<tr>";
    echo "<td><img src='uploads/$row[6].jpg' height='150px' width='300px'></td>";
    echo "</tr>\n";
}

Go to beginning of line without opening new line in VI

I just found 0(zero) and shift+0 works on vim.

Convert JSON string to dict using Python

If you trust the data source, you can use eval to convert your string into a dictionary:

eval(your_json_format_string)

Example:

>>> x = "{'a' : 1, 'b' : True, 'c' : 'C'}"
>>> y = eval(x)

>>> print x
{'a' : 1, 'b' : True, 'c' : 'C'}
>>> print y
{'a': 1, 'c': 'C', 'b': True}

>>> print type(x), type(y)
<type 'str'> <type 'dict'>

>>> print y['a'], type(y['a'])
1 <type 'int'>

>>> print y['a'], type(y['b'])
1 <type 'bool'>

>>> print y['a'], type(y['c'])
1 <type 'str'>

set default schema for a sql query

For Oracle, please use this simple command:

ALTER SESSION SET current_schema = your-schema-without-quotes;

How to change the type of a field?

What really helped me to change the type of the object in MondoDB was just this simple line, perhaps mentioned before here...:

db.Users.find({age: {$exists: true}}).forEach(function(obj) {
    obj.age = new NumberInt(obj.age);
    db.Users.save(obj);
});

Users are my collection and age is the object which had a string instead of an integer (int32).

Using OR & AND in COUNTIFS

You could just add a few COUNTIF statements together:

=COUNTIF(A1:A196,"yes")+COUNTIF(A1:A196,"no")+COUNTIF(J1:J196,"agree")

This will give you the result you need.

EDIT

Sorry, misread the question. Nicholas is right that the above will double count. I wasn't thinking of the AND condition the right way. Here's an alternative that should give you the correct results, which you were pretty close to in the first place:

=SUM(COUNTIFS(A1:A196,{"yes","no"},J1:J196,"agree"))

Get the filename of a fileupload in a document through JavaScript

Try the value property, like this:

var fu1 = document.getElementById("FileUpload1");
alert("You selected " + fu1.value);

NOTE: It looks like FileUpload1 is an ASP.Net server-side FileUpload control.
If so, you should get its ID using the ClientID property, like this:

var fu1 = document.getElementById("<%= FileUpload1.ClientID %>");

Difficulty with ng-model, ng-repeat, and inputs

You get into a difficult situation when it is necessary to understand how scopes, ngRepeat and ngModel with NgModelController work. Also try to use 1.0.3 version. Your example will work a little differently.

You can simply use solution provided by jm-

But if you want to deal with the situation more deeply, you have to understand:

  • how AngularJS works;
  • scopes have a hierarchical structure;
  • ngRepeat creates new scope for every element;
  • ngRepeat build cache of items with additional information (hashKey); on each watch call for every new item (that is not in the cache) ngRepeat constructs new scope, DOM element, etc. More detailed description.
  • from 1.0.3 ngModelController rerenders inputs with actual model values.

How your example "Binding to each element directly" works for AngularJS 1.0.3:

  • you enter letter 'f' into input;
  • ngModelController changes model for item scope (names array is not changed) => name == 'Samf', names == ['Sam', 'Harry', 'Sally'];
  • $digest loop is started;
  • ngRepeat replaces model value from item scope ('Samf') by value from unchanged names array ('Sam');
  • ngModelController rerenders input with actual model value ('Sam').

How your example "Indexing into the array" works:

  • you enter letter 'f' into input;
  • ngModelController changes item in names array => `names == ['Samf', 'Harry', 'Sally'];
  • $digest loop is started;
  • ngRepeat can't find 'Samf' in cache;
  • ngRepeat creates new scope, adds new div element with new input (that is why the input field loses focus - old div with old input is replaced by new div with new input);
  • new values for new DOM elements are rendered.

Also, you can try to use AngularJS Batarang and see how changes $id of the scope of div with input in which you enter.

What is the most efficient way to create HTML elements using jQuery?

I think you're using the best method, though you could optimize it to:

 $("<div/>");

Google Map API v3 — set bounds and center

The setCenter() method is still applicable for latest version of Maps API for Flash where fitBounds() does not exist.

In Chart.js set chart title, name of x axis and y axis?

In Chart.js version 2.0, it is possible to set labels for axes:

options = {
  scales: {
    yAxes: [{
      scaleLabel: {
        display: true,
        labelString: 'probability'
      }
    }]
  }     
}

See Labelling documentation for more details.

MySQL Error: : 'Access denied for user 'root'@'localhost'

I tried many steps to get this issue corrected. There are so many sources for possible solutions to this issue that is is hard to filter out the sense from the nonsense. I finally found a good solution here:

Step 1: Identify the Database Version

$ mysql --version

You'll see some output like this with MySQL:

$ mysql  Ver 14.14 Distrib 5.7.16, for Linux (x86_64) using  EditLine wrapper

Or output like this for MariaDB:

mysql  Ver 15.1 Distrib 5.5.52-MariaDB, for Linux (x86_64) using readline 5.1

Make note of which database and which version you're running, as you'll use them later. Next, you need to stop the database so you can access it manually.

Step 2: Stopping the Database Server

To change the root password, you have to shut down the database server beforehand.

You can do that for MySQL with:

$ sudo systemctl stop mysql

And for MariaDB with:

$ sudo systemctl stop mariadb

Step 3: Restarting the Database Server Without Permission Checking

If you run MySQL and MariaDB without loading information about user privileges, it will allow you to access the database command line with root privileges without providing a password. This will allow you to gain access to the database without knowing it.

To do this, you need to stop the database from loading the grant tables, which store user privilege information. Because this is a bit of a security risk, you should also skip networking as well to prevent other clients from connecting.

Start the database without loading the grant tables or enabling networking:

$ sudo mysqld_safe --skip-grant-tables --skip-networking &

The ampersand at the end of this command will make this process run in the background so you can continue to use your terminal.

Now you can connect to the database as the root user, which should not ask for a password.

$ mysql -u root

You'll immediately see a database shell prompt instead.

MySQL Prompt

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

MariaDB Prompt

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>

Now that you have root access, you can change the root password.

Step 4: Changing the Root Password

mysql> FLUSH PRIVILEGES;

Now we can actually change the root password.

For MySQL 5.7.6 and newer as well as MariaDB 10.1.20 and newer, use the following command:

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

For MySQL 5.7.5 and older as well as MariaDB 10.1.20 and older, use:

mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_password');

Make sure to replace new_password with your new password of choice.

Note: If the ALTER USER command doesn't work, it's usually indicative of a bigger problem. However, you can try UPDATE ... SET to reset the root password instead.

[IMPORTANT] This is the specific line that fixed my particular issue:

mysql> UPDATE mysql.user SET authentication_string = PASSWORD('new_password') WHERE User = 'root' AND Host = 'localhost';

Remember to reload the grant tables after this.

In either case, you should see confirmation that the command has been successfully executed.

Query OK, 0 rows affected (0.00 sec)

The password has been changed, so you can now stop the manual instance of the database server and restart it as it was before.

Step 5: Restart the Database Server Normally

The tutorial goes into some further steps to restart the database, but the only piece I used was this:

For MySQL, use: $ sudo systemctl start mysql

For MariaDB, use:

$ sudo systemctl start mariadb

Now you can confirm that the new password has been applied correctly by running:

$ mysql -u root -p

The command should now prompt for the newly assigned password. Enter it, and you should gain access to the database prompt as expected.

Conclusion

You now have administrative access to the MySQL or MariaDB server restored. Make sure the new root password you choose is strong and secure and keep it in safe place.

OS X Bash, 'watch' command

I am going with the answer from here:

bash -c 'while [ 0 ]; do <your command>; sleep 5; done'

But you're really better off installing watch as this isn't very clean...

How to find the path of Flutter SDK

Visit https://flutter.dev/docs/get-started/install/windows#update-your-path official page of Flutter

for windows you can look an Evroitmen variabel with value name Path

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

Solved the problem by re-installing CUDA:

wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/cuda-ubuntu1804.pin
mv cuda-ubuntu1804.pin /etc/apt/preferences.d/cuda-repository-pin-600
wget https://developer.download.nvidia.com/compute/cuda/11.1.0/local_installers/cuda-repo-ubuntu1804-11-1-local_11.1.0-455.23.05-1_amd64.deb
echo "md5sum: $(md5sum cuda-repo-ubuntu1804-11-1-local_11.1.0-455.23.05-1_amd64.deb)"
echo "correct: 056de5e03444cce506202f50967b0016"
dpkg -i cuda-repo-ubuntu1804-11-1-local_11.1.0-455.23.05-1_amd64.deb
apt-key add /var/cuda-repo-ubuntu1804-11-1-local/7fa2af80.pub
apt-get -qq update
apt-get -qq -y install cuda
rm cuda-repo-ubuntu1804-11-1-local_11.1.0-455.23.05-1_amd64.deb

How to use hex color values

Swift 2.0

The code below is tested on xcode 7.2

import UIKit
extension UIColor{

    public convenience init?(colorCodeInHex: String, alpha: Float = 1.0){

        var filterColorCode:String =  colorCodeInHex.stringByReplacingOccurrencesOfString("#", withString: "")

        if  filterColorCode.characters.count != 6 {
            self.init(red: 0.0, green: 0.0, blue: 0.0, alpha: CGFloat(alpha))
            return
        }

        filterColorCode = filterColorCode.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString

        var range = Range(start: filterColorCode.startIndex.advancedBy(0), end: filterColorCode.startIndex.advancedBy(2))
        let rString = filterColorCode.substringWithRange(range)

        range = Range(start: filterColorCode.startIndex.advancedBy(2), end: filterColorCode.startIndex.advancedBy(4))
        let gString = filterColorCode.substringWithRange(range)


        range = Range(start: filterColorCode.startIndex.advancedBy(4), end: filterColorCode.startIndex.advancedBy(6))
        let bString = filterColorCode.substringWithRange(range)

        var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
        NSScanner(string: rString).scanHexInt(&r)
        NSScanner(string: gString).scanHexInt(&g)
        NSScanner(string: bString).scanHexInt(&b)


        self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(alpha))
        return
    }
}

PuTTY scripting to log onto host

mputty can do that but it does not seem to work always. (if that wait period is too slow)

mputty uses putty and it extends putty. There is an option to run a script. If it does not work, make sure that wait period before typing is a high value or increase that value. See putty sessions , then name of session, right mouse button,properties/script page.

(Mac) -bash: __git_ps1: command not found

Please not that, if you haven't installed git through Xcode or home-brew, you'll likely find the bash scripts haysclarks refers to in /Library/Developer/CommandLineTools/, and not in /Applications/Xcode.app/Contents/Developer/, thus making the lines to include within .bashrc the following:

if [ -f /Library/Developer/CommandLineTools/usr/share/git-core/git-completion.bash ]; then
    . /Library/Developer/CommandLineTools/usr/share/git-core/git-completion.bash
fi

source /Library/Developer/CommandLineTools/usr/share/git-core/git-prompt.sh

You'll need those lines if you wish to use git-prompt as well. [1]: https://stackoverflow.com/a/20211241/4795986

PowerShell script to return versions of .NET Framework on a machine?

gci 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' |
sort pschildname -des                                  |
select -fi 1 -exp pschildname

This answer doesn't return 4.5 if that is installed. The answer below from @Jaykul and using recurse does.

How to append contents of multiple files into one file

if you have a certain output type then do something like this

cat /path/to/files/*.txt >> finalout.txt

exception in thread 'main' java.lang.NoClassDefFoundError:

Run it like this:

java -jar HelloWorld.jar

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

Add this line under the dependencies in your gradle file

compile 'com.android.support:support-annotations:27.1.1'

Call An Asynchronous Javascript Function Synchronously

You can also convert it into callbacks.

function thirdPartyFoo(callback) {    
  callback("Hello World");    
}

function foo() {    
  var fooVariable;

  thirdPartyFoo(function(data) {
    fooVariable = data;
  });

  return fooVariable;
}

var temp = foo();  
console.log(temp);

Change SVN repository URL

Given that the Apache Subversion server will be moved to this new DNS alias: sub.someaddress.com.tr:

  • With Subversion 1.7 or higher, use svn relocate. Relocate is used when the SVN server's location changes. switch is only used if you want to change your local working copy to another branch or another path. If using TortoiseSVN, you may follow instructions from the TortoiseSVN Manual. If using the SVN command line interface, refer to this section of SVN's documentation. The command should look like this:

    svn relocate svn://sub.someaddress.com.tr/project

  • Keep using /project given that the actual contents of your repository probably won't change.

Note: svn relocate is not available before version 1.7 (thanks to ColinM for the info). In older versions you would use:

    svn switch --relocate OLD NEW

How to check if that data already exist in the database during update (Mongoose And Express)

Here is another way to accomplish this in less code.

UPDATE 3: Asynchronous model class statics

Similar to option 2, this allows you to create a function directly linked to the schema, but called from the same file using the model.

model.js

 userSchema.statics.updateUser = function(user, cb) {
  UserModel.find({name : user.name}).exec(function(err, docs) {
    if (docs.length){
      cb('Name exists already', null);
    } else {
      user.save(function(err) {
        cb(err,user);
      }
    }
  });
}

Call from file

var User = require('./path/to/model');

User.updateUser(user.name, function(err, user) {
  if(err) {
    var error = new Error('Already exists!');
    error.status = 401;
    return next(error);
  }
});

Reading file line by line (with space) in Unix Shell scripting - Issue

Try this,

IFS=''
while read line
do
    echo $line
done < file.txt

EDIT:

From man bash

IFS - The Internal Field Separator that is used for word
splitting after expansion and to split lines into words
with  the  read  builtin  command. The default value is
``<space><tab><newline>''

Storage permission error in Marshmallow

Unless there is a definite requirement of writing on external storage, you can always choose to save files in app directory. In my case I had to save files and after wasting 2 to 3 days I found out if I change the storage path from

Environment.getExternalStorageDirectory()

to

getApplicationContext().getFilesDir().getPath() //which returns the internal app files directory path

it works like charm on all the devices. This is because for writing on External storage you need extra permissions but writing in internal app directory is simple.

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

It's worth noting some other things:

  1. As shown in Windows Explorer Properties dialog for the generated assembly file, there are two places called "File version". The one seen in the header of the dialog shows the AssemblyVersion, not the AssemblyFileVersion.

    In the Other version information section, there is another element called "File Version". This is where you can see what was entered as the AssemblyFileVersion.

  2. AssemblyFileVersion is just plain text. It doesn't have to conform to the numbering scheme restrictions that AssemblyVersion does (<build> < 65K, e.g.). It can be 3.2.<release tag text>.<datetime>, if you like. Your build system will have to fill in the tokens.

    Moreover, it is not subject to the wildcard replacement that AssemblyVersion is. If you just have a value of "3.0.1.*" in the AssemblyInfo.cs, that is exactly what will show in the Other version information->File Version element.

  3. I don't know the impact upon an installer of using something other than numeric file version numbers, though.

Getting output of system() calls in Ruby

puts `date`
puts $?


Mon Mar  7 19:01:15 PST 2016
pid 13093 exit 0

How to wrap text of HTML button with fixed width?

   white-space: normal;
   word-wrap: break-word;

"Both" worked for me.

Grouped bar plot in ggplot

First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

Then you need to create a data frame out of it, melt it and plot it:

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns

# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')

# plot everything
ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

Is this what you're after?

enter image description here

To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:

> head(df)
  ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1  1    A  1980   450   338   154    36    13     9
2  2    A  2000   288   407   212    54    16    23
3  3    A  2020   196   434   246    68    19    36
4  4    B  1980   111   326   441    90    21    11
5  5    B  2000    63   298   443   133    42    21
6  6    B  2020    36   257   462   162    55    30

Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape and plotted.

For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw)) to get this:

> data
   Names Very.Bad Bad Good Very.Good
1   Food        7   6    5         2
2  Music        5   5    7         3
3 People        6   3    7         4

Just imagine you have Very.Bad, Bad, Good and so on instead of X1PCE, X2PCE, X3PCE. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw)).

C# Change A Button's Background Color

I doubt if any of those should work. Try: First import the namespace in the beginning of the code page as below.

using System.Drawing;

then in the code.

Button4.BackColor = Color.LawnGreen;

Hope it helps.

Stop node.js program from command line

you can type .exit to quit node js REPL

how to deal with google map inside of a hidden div (Updated picture)

I didn't like that the map would load only after the hidden div had become visible. In a carousel, for example, that doesn't really work.

This my solution is to add class to the hidden element to unhide it and hide it with position absolute instead, then render the map, and remove the class after map load.

Tested in Bootstrap Carousel.

HTML

<div class="item loading"><div id="map-canvas"></div></div>

CSS

.loading { display: block; position: absolute; }

JS

$(document).ready(function(){
    // render map //
    google.maps.event.addListenerOnce(map, 'idle', function(){
        $('.loading').removeClass('loading');
    });
}

read subprocess stdout line by line

Bit late to the party, but was surprised not to see what I think is the simplest solution here:

import io
import subprocess

proc = subprocess.Popen(["prog", "arg"], stdout=subprocess.PIPE)
for line in io.TextIOWrapper(proc.stdout, encoding="utf-8"):  # or another encoding
    # do something with line

(This requires Python 3.)

Java: How to get input from System.console()

Scanner in = new Scanner(System.in);

int i = in.nextInt();
String s = in.next();

'Property does not exist on type 'never'

In my case (I'm using typescript) I was trying to simulate response with fake data where the data is assigned later on. My first attempt was with:

let response = {status: 200, data: []};

and later, on the assignment of the fake data it starts complaining that it is not assignable to type 'never[]'. Then I defined the response like follows and it accepted it..

let dataArr: MyClass[] = [];
let response = {status: 200, data: dataArr};

and assigning of the fake data:

response.data = fakeData;

How to view AndroidManifest.xml from APK file?

Android Studio can now show this. Go to Build > Analyze APK... and select your apk. Then you can see the content of the AndroidManifset file.

How to define several include path in Makefile

Make's substitutions feature is nice and helped me to write

%.i: src/%.c $(INCLUDE)
        gcc -E $(CPPFLAGS) $(INCLUDE:%=-I %) $< > $@

You might find this useful, because it asks make to check for changes in include folders too

DECODE( ) function in SQL Server

In my Case I used it in a lot of places first example if you have 2 values for select statement like gender (Male or Female) then use the following statement:

SELECT CASE Gender WHEN 'Male' THEN 1 ELSE 2 END AS Gender

If there is more than one condition like nationalities you can use it as the following statement:

SELECT CASE Nationality 
WHEN 'AMERICAN'   THEN 1 
WHEN 'BRITISH'   THEN 2
WHEN 'GERMAN'    THEN 3 
WHEN 'EGYPT'     THEN 4 
WHEN 'PALESTINE' THEN 5 
ELSE 6 END AS Nationality 

multiple packages in context:component-scan, spring config

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

will work since the rest of the packages are sub packages of "x.y.z". Thus, you dont need to mention each package individually.

How can I make window.showmodaldialog work in chrome 37?

Yes, It's deprecated. Spent yesterday rewriting code to use Window.open and PostMessage instead.

How to square or raise to a power (elementwise) a 2D numpy array?

The fastest way is to do a*a or a**2 or np.square(a) whereas np.power(a, 2) showed to be considerably slower.

np.power() allows you to use different exponents for each element if instead of 2 you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2 or a*a, which become important in cases where you have small tolerances.

I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:

In [29]: a = np.random.random((1000, 1000))

In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop

In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop

In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop

Check if a string is a valid Windows directory (folder) path

    private bool IsValidPath(string path)
    {
        Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
        if (!driveCheck.IsMatch(path.Substring(0, 3))) return false;
        string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());
        strTheseAreInvalidFileNameChars += @":/?*" + "\"";
        Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]");
        if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
            return false;

        DirectoryInfo dir = new DirectoryInfo(Path.GetFullPath(path));
        if (!dir.Exists)
            dir.Create();
        return true;
    }

How to install pip3 on Windows?

For python3.5.3, pip3 is also installed when you install python. When you install it you may not select the add to path. Then you can find where the pip3 located and add it to path manually.

How to get .pem file from .key and .crt files?

Your keys may already be in PEM format, but just named with .crt or .key.

If the file's content begins with -----BEGIN and you can read it in a text editor:

The file uses base64, which is readable in ASCII, not binary format. The certificate is already in PEM format. Just change the extension to .pem.

If the file is in binary:

For the server.crt, you would use

openssl x509 -inform DER -outform PEM -in server.crt -out server.crt.pem

For server.key, use openssl rsa in place of openssl x509.

The server.key is likely your private key, and the .crt file is the returned, signed, x509 certificate.

If this is for a Web server and you cannot specify loading a separate private and public key:

You may need to concatenate the two files. For this use:

cat server.crt server.key > server.includesprivatekey.pem

I would recommend naming files with "includesprivatekey" to help you manage the permissions you keep with this file.

Cannot load properties file from resources directory

Right click the Resources folder and select Build Path > Add to Build Path

Disable-web-security in Chrome 48+

In a terminal put these:

cd C:\Program Files (x86)\Google\Chrome\Application

chrome.exe --disable-web-security --user-data-dir="c:/chromedev"

How can I read input from the console using the Scanner class in Java?

A simple example:

import java.util.Scanner;

public class Example
{
    public static void main(String[] args)
    {
        int number1, number2, sum;

        Scanner input = new Scanner(System.in);

        System.out.println("Enter First multiple");
        number1 = input.nextInt();

        System.out.println("Enter second multiple");
        number2 = input.nextInt();

        sum = number1 * number2;

        System.out.printf("The product of both number is %d", sum);
    }
}

How to print the values of slices

If you just want to see the values of an array without brackets, you can use a combination of fmt.Sprint() and strings.Trim()

a := []string{"a", "b"}
fmt.Print(strings.Trim(fmt.Sprint(a), "[]"))
fmt.Print(a)

Returns:

a b
[a b]

Be aware though that with this solution any leading brackets will be lost from the first value and any trailing brackets will be lost from the last value

a := []string{"[a]", "[b]"}
fmt.Print(strings.Trim(fmt.Sprint(a), "[]")
fmt.Print(a)

Returns:

a] [b
[[a] [b]]

For more info see the documentation for strings.Trim()

Auto refresh code in HTML using meta tags

Try this tag. This will refresh the index.html page every 30 seconds.

<meta http-equiv="refresh" content="30;url=index.html">

Can you use Microsoft Entity Framework with Oracle?

DevArt's OraDirect provider now supports entity framework. See http://devart.com/news/2008/directs475.html

Python error when trying to access list by index - "List indices must be integers, not str"

players is a list which needs to be indexed by integers. You seem to be using it like a dictionary. Maybe you could use unpacking -- Something like:

name, score = player

(if the player list is always a constant length).

There's not much more advice we can give you without knowing what query is and how it works.

It's worth pointing out that the entire code you posted doesn't make a whole lot of sense. There's an IndentationError on the second line. Also, your function is looping over some iterable, but unconditionally returning during the first iteration which isn't usually what you actually want to do.

Distinct in Linq based on only one field of the table

You can try this:table1.GroupBy(t => t.Text).Select(shape => shape.r)).Distinct();

Disable back button in android

Apart form these two methods from answer above.

onBackPressed() (API Level 5, Android 2.0)

onKeyDown() (API Level 1, Android 1.0)

You can also override the dispatchKeyEvent()(API Level 1, Android 1.0) like this,

dispatchKeyEvent() (API Level 1, Android 1.0)

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    // TODO Auto-generated method stub
    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
        return true;
    }
    return super.dispatchKeyEvent(event);
}

Bootstrap dropdown sub menu missing

Updated 2018

The dropdown-submenu has been removed in Bootstrap 3 RC. In the words of Bootstrap author Mark Otto..

"Submenus just don't have much of a place on the web right now, especially the mobile web. They will be removed with 3.0" - https://github.com/twbs/bootstrap/pull/6342

But, with a little extra CSS you can get the same functionality.

Bootstrap 4 (navbar submenu on hover)

.navbar-nav li:hover > ul.dropdown-menu {
    display: block;
}
.dropdown-submenu {
    position:relative;
}
.dropdown-submenu>.dropdown-menu {
    top:0;
    left:100%;
    margin-top:-6px;
}

Navbar submenu dropdown hover
Navbar submenu dropdown hover (right aligned)
Navbar submenu dropdown click (right aligned)
Navbar dropdown hover (no submenu)


Bootstrap 3

Here is an example that uses 3.0 RC 1: http://bootply.com/71520

Here is an example that uses Bootstrap 3.0.0 (final): http://bootply.com/86684

CSS

.dropdown-submenu {
    position:relative;
}
.dropdown-submenu>.dropdown-menu {
    top:0;
    left:100%;
    margin-top:-6px;
    margin-left:-1px;
    -webkit-border-radius:0 6px 6px 6px;
    -moz-border-radius:0 6px 6px 6px;
    border-radius:0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
    display:block;
}
.dropdown-submenu>a:after {
    display:block;
    content:" ";
    float:right;
    width:0;
    height:0;
    border-color:transparent;
    border-style:solid;
    border-width:5px 0 5px 5px;
    border-left-color:#cccccc;
    margin-top:5px;
    margin-right:-10px;
}
.dropdown-submenu:hover>a:after {
    border-left-color:#ffffff;
}
.dropdown-submenu.pull-left {
    float:none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
    left:-100%;
    margin-left:10px;
    -webkit-border-radius:6px 0 6px 6px;
    -moz-border-radius:6px 0 6px 6px;
    border-radius:6px 0 6px 6px;
}

Sample Markup

<div class="navbar navbar-default navbar-fixed-top" role="navigation">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">  
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
        </div>
        <div class="collapse navbar-collapse navbar-ex1-collapse">
            <ul class="nav navbar-nav">
                <li class="menu-item dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Drop Down<b class="caret"></b></a>
                    <ul class="dropdown-menu">
                        <li class="menu-item dropdown dropdown-submenu">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Level 1</a>
                            <ul class="dropdown-menu">
                                <li class="menu-item ">
                                    <a href="#">Link 1</a>
                                </li>
                                <li class="menu-item dropdown dropdown-submenu">
                                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Level 2</a>
                                    <ul class="dropdown-menu">
                                        <li>
                                            <a href="#">Link 3</a>
                                        </li>
                                    </ul>
                                </li>
                            </ul>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</div>

P.S. - Example in navbar that adjusts left position: http://bootply.com/92442

How to rename uploaded file before saving it into a directory?

You can Try this,

$newfilename= date('dmYHis').str_replace(" ", "", basename($_FILES["file"]["name"]));

move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);

javascript create empty array of a given size

As of ES5 (when this answer was given):

If you want an empty array of undefined elements, you could simply do

var whatever = new Array(5);

this would give you

[undefined, undefined, undefined, undefined, undefined]

and then if you wanted it to be filled with empty strings, you could do

whatever.fill('');

which would give you

["", "", "", "", ""]

And if you want to do it in one line:

var whatever = Array(5).fill('');

What Regex would capture everything from ' mark to the end of a line?

This will capture everything up to the ' in backreference 1 - and everything after the ' in backreference 2. You may need to escape the apostrophes though depending on language (\')

/^([^']*)'?(.*)$/

Quick modification: if the line doesn't have an ' - backreference 1 should still catch the whole line.

^ - start of string
([^']*) - capture any number of not ' characters
'? - match the ' 0 or 1 time
(.*) - capture any number of characters
$ - end of string

Android Webview gives net::ERR_CACHE_MISS message

Answers assembled! I wanted to just combine all the answers into one comprehensive one.

1. Check if <uses-permission android:name="android.permission.INTERNET" /> is present in manifest.xml. Make sure that it is nested under <manifest> and not <application>. Thanks to sajid45 and Liyanis Velazquez

2. Ensure that you are using <uses-permission android:name="android.permission.INTERNET"/> instead of the deprecated <uses-permission android:name="android.permission.internet"/>. Much thanks to alan_shi and creos.

3. If minimum version is below KK, check that you have

if (18 < Build.VERSION.SDK_INT ){
    //18 = JellyBean MR2, KITKAT=19
    mWeb.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
}

or

if (Build.VERSION.SDK_INT >= 19) {
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}

because proper webview is only added in KK (SDK 19). Thanks to Devavrata, Mike ChanSeong Kim and Liyanis Velazquez

4. Ensure that you don't have webView.getSettings().setBlockNetworkLoads (false);. Thanks to TechNikh for pointing this out.

5. If all else fails, make sure that your Android Studio, Android SDK and the emulator image (if you are using one) is updated. And if you are still meeting the problem, just open a new question and make a comment below to your URL.

Class is inaccessible due to its protection level

There was a project that used linked files. I needed to add the method.cs file to that project as a linked file as well, since the FBlock.cs file was there. I've never heard of linked files before, I didn't even know that was possible.

.NET End vs Form.Close() vs Application.Exit Cleaner way to close one's app

In .Net 1.1 and earlier, Application.Exit was not a wise choice and the MSDN docs specifically recommended against it because all message processing stopped immediately.

In later versions however, calling Application.Exit will result in Form.Close being called on all open forms in the application, thus giving you a chance to clean up after yourself, or even cancel the operation all together.

Transpose a matrix in Python

If we wanted to return the same matrix we would write:

return [[ m[row][col] for col in range(0,width) ] for row in range(0,height) ]

What this does is it iterates over a matrix m by going through each row and returning each element in each column. So the order would be like:

[[1,2,3],
[4,5,6],
[7,8,9]]

Now for question 3, we instead want to go column by column, returning each element in each row. So the order would be like:

[[1,4,7],
[2,5,8],
[3,6,9]]

Therefore just switch the order in which we iterate:

return [[ m[row][col] for row in range(0,height) ] for col in range(0,width) ]

How can I generate a tsconfig.json file?

You need to have typescript library installed and then you can use

npx tsc --init 

If the response is error TS5023: Unknown compiler option 'init'. that means the library is not installed

yarn add --dev typescript

and run npx command again

Best way to encode Degree Celsius symbol into web page?

If using Java-JSP, What worked for me is to paste below in JSP page

<%@ page contentType="text/html; charset=UTF-8" %>

MySQL convert date string to Unix timestamp

From http://www.epochconverter.com/

SELECT DATEDIFF(s, '1970-01-01 00:00:00', GETUTCDATE())

My bad, SELECT unix_timestamp(time) Time format: YYYY-MM-DD HH:MM:SS or YYMMDD or YYYYMMDD. More on using timestamps with MySQL:

http://www.epochconverter.com/programming/mysql-from-unixtime.php

How to add text to a WPF Label in code?

you can use TextBlock control and assign the text property.

Fastest way to get the first n elements of a List into an Array

Option 3

Iterators are faster than using the get operation, since the get operation has to start from the beginning if it has to do some traversal. It probably wouldn't make a difference in an ArrayList, but other data structures could see a noticeable speed difference. This is also compatible with things that aren't lists, like sets.

String[] out = new String[n];
Iterator<String> iterator = in.iterator();
for (int i = 0; i < n && iterator.hasNext(); i++)
    out[i] = iterator.next();

How to execute a shell script from C in Linux?

If you're ok with POSIX, you can also use popen()/pclose()

#include <stdio.h>
#include <stdlib.h>

int main(void) {
/* ls -al | grep '^d' */
  FILE *pp;
  pp = popen("ls -al", "r");
  if (pp != NULL) {
    while (1) {
      char *line;
      char buf[1000];
      line = fgets(buf, sizeof buf, pp);
      if (line == NULL) break;
      if (line[0] == 'd') printf("%s", line); /* line includes '\n' */
    }
    pclose(pp);
  }
  return 0;
}

Undefined index error PHP

Hey this is happening because u r trying to display value before assignnig it U just fill in the values and submit form it will display correct output Or u can write ur php code below form tags It ll run without any errors

Can I make a <button> not submit a form?

Just use good old HTML:

<input type="button" value="Submit" />

Wrap it as the subject of a link, if you so desire:

<a href="http://somewhere.com"><input type="button" value="Submit" /></a>

Or if you decide you want javascript to provide some other functionality:

<input type="button" value="Cancel" onclick="javascript: someFunctionThatCouldIncludeRedirect();"/>

How can I add a box-shadow on one side of an element?

Here is my example:

_x000D_
_x000D_
.box{_x000D_
        _x000D_
        width: 400px; _x000D_
        height: 80px; _x000D_
        background-color: #C9C; _x000D_
        text-align: center; _x000D_
        font: 20px normal Arial, Helvetica, sans-serif; _x000D_
        color: #fff; _x000D_
        padding: 100px 0 0 0;_x000D_
        -webkit-box-shadow: 0 8px 6px -6px black;_x000D_
           -moz-box-shadow: 0 8px 6px -6px black;_x000D_
                box-shadow: 0 8px 6px -6px black;_x000D_
    }
_x000D_
<div class="box">_x000D_
</div>
_x000D_
_x000D_
_x000D_

CSS3 background image transition

Considering background-images can't be animated, I created a little SCSS mixin allowing to transition between 2 different background-images using pseudo selectors before and after. They are at different z-index layers. The one that is ahead starts with opacity 0 and becomes visible with hover.

You can use it the same approach for creating animations with linear-gradients too.

scss

@mixin bkg-img-transition( $bkg1, $bkg2, $transTime:0.5s ){  
  position: relative;  
  z-index: 100; 
  &:before, &:after {
    background-size: cover;  
    content: '';    
    display: block;
    height: 100%;
    position: absolute;
    top: 0; left: 0;    
    width: 100%;    
    transition: opacity $transTime;
  }
  &:before {    
    z-index: -101;
    background-image: url("#{$bkg1}");    
  }
  &:after {    
    z-index: -100;
    opacity: 0;
    background-image: url("#{$bkg2}");    
  }
  &:hover {
     &:after{
       opacity: 1; 
     }
  }  
}

Now you can simply use it with

@include bkg-img-transition("https://picsum.photos/300/300/?random","https://picsum.photos/g/300/300");

You can check it out here: https://jsfiddle.net/pablosgpacheco/01rmg0qL/

Format Float to n decimal places

I was looking for an answer to this question and later I developed a method! :) A fair warning, it's rounding up the value.

private float limitDigits(float number) {
    return Float.valueOf(String.format(Locale.getDefault(), "%.2f", number));
}

incompatible character encodings: ASCII-8BIT and UTF-8

Just for the record: for me it turned out that it was the gem called 'mysql' ... obviously this is working with US-ASCII 8 bit by default. So changing it to the gem called mysql2 (the 2 is the important point here) solved all of my issues.

I looked @ the gem list posted above - Michael Koper has obviously mysql2 installed but I posted this in case someone has this issue as well .. (took me some time to figure out).

If you dislike this answer please comment and I will delete it.

P.S: German umlauts (ä,ö and ü) screwed it out with mysql

How to read html from a url in python 3

Note that Python3 does not read the html code as a string but as a bytearray, so you need to convert it to one with decode.

import urllib.request

fp = urllib.request.urlopen("http://www.python.org")
mybytes = fp.read()

mystr = mybytes.decode("utf8")
fp.close()

print(mystr)

How do I convert datetime.timedelta to minutes, hours in Python?

Another alternative for this (older) question:

import datetime
import pytz
import time

pacific=pytz.timezone('US/Pacific')
now=datetime.datetime.now()
# pacific.dst(now).total_seconds() yields 3600 secs. [aka 1 hour]
time.strftime("%-H", time.gmtime(pacific.dst(now).total_seconds()))
'1'

The above is a good way to tell if your current time zone is actually in daylight savings time or not. (It provides an offset of 0 or 1.) Anyway, the real work is being done by time.strftime("%H:%M:%S", time.gmtime(36901)) which does work on the output of gmtime().

>>> time.strftime("%H:%M:%S",time.gmtime(36901))  # secs = 36901
'10:15:01'

And, that's it! (NOTE: Here's a link to format specifiers for time.strftime(). ...)

Reading From A Text File - Batch

Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.

So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.

cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit

But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.

@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit

Or if you'd like them to select the file from which to write in the batch you could do the following.

@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit

What exactly does Double mean in java?

A double is an IEEE754 double-precision floating point number, similar to a float but with a larger range and precision.

IEEE754 single precision numbers have 32 bits (1 sign, 8 exponent and 23 mantissa bits) while double precision numbers have 64 bits (1 sign, 11 exponent and 52 mantissa bits).

A Double in Java is the class version of the double basic type - you can use doubles but, if you want to do something with them that requires them to be an object (such as put them in a collection), you'll need to box them up in a Double object.

Process all arguments except the first one (in a bash script)

Use this:

echo "${@:2}"

The following syntax:

echo "${*:2}"

would work as well, but is not recommended, because as @Gordon already explained, that using *, it runs all of the arguments together as a single argument with spaces, while @ preserves the breaks between them (even if some of the arguments themselves contain spaces). It doesn't make the difference with echo, but it matters for many other commands.

How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

I know that you can modify a javascript file when using Google Chrome.

  1. Open up Chrome Inspector, go to the "Scripts" tab.
  2. Press the drop-down menu and select the javascript file that you want to edit.
  3. Double click in the text field, type in what ever you want and delete whatever you want.
  4. Then all you have to do is press Ctrl + S to save the file.

Warning: If you refresh the page, all changes will go back to original file. I recommend to copy/paste the code somewhere else if you want to use it again.

Hope this helps!

Programmatically get height of navigation bar

Swift version:

let navigationBarHeight: CGFloat = self.navigationController!.navigationBar.frame.height

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

To me it happened in DogController that autowired DogService that autowired DogRepository. Dog class used to have field name but I changed it to coolName, but didn't change methods in DogRepository: Dog findDogByName(String name). I change that method to Dog findDogByCoolName(String name) and now it works.

How to change FontSize By JavaScript?

JavaScript is case sensitive.

So, if you want to change the font size, you have to go:

span.style.fontSize = "25px";

How to do a https request with bad certificate?

If you want to use the default settings from http package, so you don't need to create a new Transport and Client object, you can change to ignore the certificate verification like this:

tr := http.DefaultTransport.(*http.Transport)
tr.TLSClientConfig.InsecureSkipVerify = true

How can I kill all sessions connecting to my oracle database?

As SYS:

startup force;

Brutal, yet elegant.

Set element width or height in Standards Mode

The style property lets you specify values for CSS properties.

The CSS width property takes a length as its value.

Lengths require units. In quirks mode, browsers tend to assume pixels if provided with an integer instead of a length. Specify units.

e1.style.width = "400px";

Android Device Chooser -- device not showing up

I had the same issue with Sony Experia Z, that is because I'm running on windows 8 and apparently I need to download a driver for it.

As mentioned by stkhou, I check my Device manager and saw the eclamation mark. Which it was the model of my phone, to double check so I remove the usb and it dissapeard. So I plug it in again and the icon appears again.

So it's pretty sure the driver issue, so I have download it and install. After installation, run the android device chooser on eclipse again and it works for me.

I hope same for you.

Here below I saved the links that might intrests someone who has sony issue. ;)

Here are the list of available driver for sony devices:

http://developer.sonymobile.com/downloads/drivers/

Sony SDK

http://developer.sonymobile.com/knowledge-base/sony-add-on-sdk/install-the-sony-add-on-sdk/

Get query from java.sql.PreparedStatement

This is nowhere definied in the JDBC API contract, but if you're lucky, the JDBC driver in question may return the complete SQL by just calling PreparedStatement#toString(). I.e.

System.out.println(preparedStatement);

To my experience, the ones which do so are at least the PostgreSQL 8.x and MySQL 5.x JDBC drivers. For the case your JDBC driver doesn't support it, your best bet is using a statement wrapper which logs all setXxx() methods and finally populates a SQL string on toString() based on the logged information. For example Log4jdbc or P6Spy.

Run local python script on remote server

You can do it via ssh.

ssh [email protected] "python ./hello.py"

You can also edit the script in ssh using a textual editor or X11 forwarding.

Avoid dropdown menu close on click inside

$('body').on("click", ".dropdown-menu", function (e) {
    $(this).parent().is(".show") && e.stopPropagation();
});

Android dependency has different version for the compile and runtime

After a lot of time and getting help from a friend who knows a lot more than me about android: app/build.gradle

android {
    compileSdkVersion 27

    // org.gradle.caching = true

    defaultConfig {
        applicationId "com.cryptoviewer"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 196
        versionName "16.83"
        // ndk {
        //     abiFilters "armeabi-v7a", "x86"
        // }
    }

and dependencies

dependencies {
    implementation project(':react-native-camera')
   //...
    implementation "com.android.support:appcompat-v7:26.1.0" // <= YOU CARE ABOUT THIS
    implementation "com.facebook.react:react-native:+"  // From node_modules
}

in build.gradle

allprojects {
   //...
    configurations.all {
        resolutionStrategy.force "com.android.support:support-v4:26.1.0"
    }

in gradle.properties

android.useDeprecatedNdk=true
android.enableAapt2=false
org.gradle.jvmargs=-Xmx4608M

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

if you tried running java with -version argument, and even though the problem could not be solved by any means, then you might have installed many java versions, like JDK 1.8 and JDK 1.7 at the same time.

So try uninstalling all other versions other than the one you need, then set the JAVA_HOMEpath variable for that JDK remaining, and you're done.

Generating PDF files with JavaScript

Another interesting project is texlive.js.

It allows you to compile (La)TeX to PDF in the browser.

Oracle SQL - REGEXP_LIKE contains characters other than a-z or A-Z

Something like

select *
  from foo
 where regexp_like( col1, '[^[:alpha:]]' ) ;

should work

SQL> create table foo( col1 varchar2(100) );

Table created.

SQL> insert into foo values( 'abc' );

1 row created.

SQL> insert into foo values( 'abc123' );

1 row created.

SQL> insert into foo values( 'def' );

1 row created.

SQL> select *
  2    from foo
  3   where regexp_like( col1, '[^[:alpha:]]' ) ;

COL1
--------------------------------------------------------------------------------
abc123

How do I negate a condition in PowerShell?

You almost had it with Not. It should be:

if (-Not (Test-Path C:\Code)) {
    write "it doesn't exist!"
} 

You can also use !: if (!(Test-Path C:\Code)){}

Just for fun, you could also use bitwise exclusive or, though it's not the most readable/understandable method.

if ((test-path C:\code) -bxor 1) {write "it doesn't exist!"}

Installed Java 7 on Mac OS X but Terminal is still using version 6

You can execute following command in your terminal :

export PATH="/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin:$PATH"

And this replaces the java old with new one.

ERROR 1067 (42000): Invalid default value for 'created_at'

The problem is because of sql_modes. Please check your current sql_modes by command:

show variables like 'sql_mode' ; 

And remove the sql_mode "NO_ZERO_IN_DATE,NO_ZERO_DATE" to make it work. This is the default sql_mode in mysql new versions.

You can set sql_mode globally as root by command:

set global sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';

Read input stream twice

For splitting an InputStream in two, while avoiding to load all data in memory, and then process them independently:

  1. Create a couple of OutputStream, precisely: PipedOutputStream
  2. Connect each PipedOutputStream with a PipedInputStream, these PipedInputStream are the returned InputStream.
  3. Connect the sourcing InputStream with just created OutputStream. So, everything read it from the sourcing InputStream, would be written in both OutputStream. There is not need to implement that, because it is done already in TeeInputStream (commons.io).
  4. Within a separated thread read the whole sourcing inputStream, and implicitly the input data is transferred to the target inputStreams.

    public static final List<InputStream> splitInputStream(InputStream input) 
        throws IOException 
    { 
        Objects.requireNonNull(input);      
    
        PipedOutputStream pipedOut01 = new PipedOutputStream();
        PipedOutputStream pipedOut02 = new PipedOutputStream();
    
        List<InputStream> inputStreamList = new ArrayList<>();
        inputStreamList.add(new PipedInputStream(pipedOut01));
        inputStreamList.add(new PipedInputStream(pipedOut02));
    
        TeeOutputStream tout = new TeeOutputStream(pipedOut01, pipedOut02);
    
        TeeInputStream tin = new TeeInputStream(input, tout, true);
    
        Executors.newSingleThreadExecutor().submit(tin::readAllBytes);  
    
        return Collections.unmodifiableList(inputStreamList);
    }
    

Be aware to close the inputStreams after being consumed, and close the thread that runs: TeeInputStream.readAllBytes()

In case, you need to split it into multiple InputStream, instead of just two. Replace in the previous fragment of code the class TeeOutputStream for your own implementation, which would encapsulate a List<OutputStream> and override the OutputStream interface:

public final class TeeListOutputStream extends OutputStream {
    private final List<? extends OutputStream> branchList;

    public TeeListOutputStream(final List<? extends OutputStream> branchList) {
        Objects.requireNonNull(branchList);
        this.branchList = branchList;
    }

    @Override
    public synchronized void write(final int b) throws IOException {
        for (OutputStream branch : branchList) {
            branch.write(b);
        }
    }

    @Override
    public void flush() throws IOException {
        for (OutputStream branch : branchList) {
            branch.flush();
        }
    }

    @Override
    public void close() throws IOException {
        for (OutputStream branch : branchList) {
            branch.close();
        }
    }
}

Using multiple case statements in select query

There are two ways to write case statements, you seem to be using a combination of the two

case a.updatedDate
    when 1760 then 'Entered on' + a.updatedDate
    when 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

or

case 
    when a.updatedDate = 1760 then 'Entered on' + a.updatedDate
    when a.updatedDate = 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

are equivalent. They may not work because you may need to convert date types to varchars to append them to other varchars.

Is there a concurrent List in Java's JDK?

Because the act of acquiring the position and getting the element from the given position naturally requires some locking (you can't have the list have structural changes between those two operations).

The very idea of a concurrent collection is that each operation on its own is atomic and can be done without explicit locking/synchronization.

Therefore getting the element at position n from a given List as an atomic operation doesn't make too much sense in a situation where concurrent access is anticipated.

Using ng-click vs bind within link function of Angular Directive

You may use a controller in directive:

angular.module('app', [])
  .directive('appClick', function(){
     return {
       restrict: 'A',
       scope: true,
       template: '<button ng-click="click()">Click me</button> Clicked {{clicked}} times',
       controller: function($scope, $element){
         $scope.clicked = 0;
         $scope.click = function(){
           $scope.clicked++
         }
       }
     }
   });

Demo on plunkr

More about directives in Angular guide. And very helpfull for me was videos from official Angular blog post About those directives.

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

What is difference between sleep() method and yield() method of multi threading?

Yield : will make thread to wait for the currently executing thread and the thread which has called yield() will attaches itself at the end of the thread execution. The thread which call yield() will be in Blocked state till its turn.

Sleep : will cause the thread to sleep in sleep mode for span of time mentioned in arguments.

Join : t1 and t2 are two threads , t2.join() is called then t1 enters into wait state until t2 completes execution. Then t1 will into runnable state then our specialist JVM thread scheduler will pick t1 based on criteria's.

how to add a jpg image in Latex

if you add a jpg,png,pdf picture, you should use pdflatex to compile it.

segmentation fault : 11

Run your program with valgrind of linked to efence. That will tell you where the pointer is being dereferenced and most likely fix your problem if you fix all the errors they tell you about.

How to connect SQLite with Java?

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;   


public class Connectdatabase {

        Connection con = null;

        public static Connection ConnecrDb(){

            try{
                //String dir = System.getProperty("user.dir");
                Class.forName("org.sqlite.JDBC");
                Connection con = DriverManager.getConnection("jdbc:sqlite:D:\\testdb.db");
                return con;
            }
            catch(ClassNotFoundException | SQLException e){
                JOptionPane.showMessageDialog(null,"Problem with connection of database");
                return null;
            }
        }

    }

Sort array of objects by string property value

Way 1 :

You can use Underscore.js. Import underscore first.

 import * as _ from 'underscore';
 let SortedObjs = _.sortBy(objs, 'last_nom');

Way 2 : Use compare function.

function compare(first, second) {
     if (first.last_nom < second.last_nom)
         return -1;
     if (first.last_nom > second.last_nom)
       return 1;
    return 0;
 }

objs.sort(compare);

How can I enable or disable the GPS programmatically on Android?

This code works on ROOTED phones if the app is moved to /system/aps, and they have the following permissions in the manifest:

<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>

Code

private void turnGpsOn (Context context) {
    beforeEnable = Settings.Secure.getString (context.getContentResolver(),
                                              Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    String newSet = String.format ("%s,%s",
                                   beforeEnable,
                                   LocationManager.GPS_PROVIDER);
    try {
        Settings.Secure.putString (context.getContentResolver(),
                                   Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
                                   newSet); 
    } catch(Exception e) {}
}


private void turnGpsOff (Context context) {
    if (null == beforeEnable) {
        String str = Settings.Secure.getString (context.getContentResolver(),
                                                Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if (null == str) {
            str = "";
        } else {                
            String[] list = str.split (",");
            str = "";
            int j = 0;
            for (int i = 0; i < list.length; i++) {
                if (!list[i].equals (LocationManager.GPS_PROVIDER)) {
                    if (j > 0) {
                        str += ",";
                    }
                    str += list[i];
                    j++;
                }
            }
            beforeEnable = str;
        }
    }
    try {
        Settings.Secure.putString (context.getContentResolver(),
                                   Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
                                   beforeEnable);
    } catch(Exception e) {}
}

Create two-dimensional arrays and access sub-arrays in Ruby

I'm quite sure this can be very simple

2.0.0p247 :032 > list = Array.new(5)

 => [nil, nil, nil, nil, nil] 

2.0.0p247 :033 > list.map!{ |x| x = [0] }

 => [[0], [0], [0], [0], [0]] 

2.0.0p247 :034 > list[0][0]

  => 0

merge one local branch into another local branch

First, checkout to your Branch3:

git checkout Branch3

Then merge the Branch1:

git merge Branch1

And if you want the updated commits of Branch1 on Branch2, you are probaly looking for git rebase

git checkout Branch2
git rebase Branch1

This will update your Branch2 with the latest updates of Branch1.

How to handle a single quote in Oracle SQL

I found the above answer giving an error with Oracle SQL, you also must use square brackets, below;

SQL> SELECT Q'[Paddy O'Reilly]' FROM DUAL;


Result: Paddy O'Reilly

Swift Bridging Header import issue

Had similar issue that could not be solved by any solution above. My project uses CocoaPods. I noticed that along with errors I got a warning with the following message:

Uncategorized: Target 'Pods' of project 'Pods' was rejected as an implicit dependency for 'Pods.framework' because its architectures 'arm64' didn't contain all required architectures 'armv7 arm64'

enter image description here

So solution was quite simple. For Pods project, change Build Active Architecture Only flag to No and original error went away.

How to get text and a variable in a messagebox

I kind of run into the same issue. I wanted my message box to display the message and the vendorcontractexpiration. This is what I did:

Dim ab As String
Dim cd As String

ab = "THE CONTRACT FOR THIS VENDOR WILL EXPIRE ON "
cd = VendorContractExpiration


If InvoiceDate >= VendorContractExpiration - 120 And InvoiceDate < VendorContractExpiration Then

MsgBox [ab] & [cd], vbCritical, "WARNING"

End If

How do you get the list of targets in a makefile?

This is far from clean, but did the job, for me.

make -p 2&>/dev/null | grep -A 100000 "# Files" | grep -v "^$" | grep -v "^\(\s\|#\|\.\)" | grep -v "Makefile:" | cut -d ":" -f 1

I use make -p that dumps the internal database, ditch stderr, use a quick and dirty grep -A 100000 to keep the bottom of the output. Then I clean the output with a couple of grep -v, and finally use cut to get what's before the colon, namely, the targets.

This is enough for my helper scripts on most of my Makefiles.

EDIT: added grep -v Makefile that is an internal rule

How to get value from form field in django framework?

To retrieve data from form which send post request you can do it like this

def login_view(request):
    if(request.POST):
        login_data = request.POST.dict()
        username = login_data.get("username")
        password = login_data.get("password")
        user_type = login_data.get("user_type")
        print(user_type, username, password)
        return HttpResponse("This is a post request")
    else:
        return render(request, "base.html")

Array of structs example

Given an instance of the struct, you set the values.

    student thisStudent;
    Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
    thisStudent.s_id = int.Parse(Console.ReadLine());
    thisStudent.s_name = Console.ReadLine();
    thisStudent.c_name = Console.ReadLine();
    thisStudent.s_dob = Console.ReadLine();

Note this code is incredibly fragile, since we aren't checking the input from the user at all. And you aren't clear to the user that you expect each data point to be entered on a separate line.

How to compile a static library in Linux?

See Creating a shared and static library with the gnu compiler [gcc]

gcc -c -o out.o out.c

-c means to create an intermediary object file, rather than an executable.

ar rcs libout.a out.o

This creates the static library. r means to insert with replacement, c means to create a new archive, and s means to write an index. As always, see the man page for more info.

How to compute precision, recall, accuracy and f1-score for the multiclass case with scikit learn?

Lot of very detailed answers here but I don't think you are answering the right questions. As I understand the question, there are two concerns:

  1. How to I score a multiclass problem?
  2. How do I deal with unbalanced data?

1.

You can use most of the scoring functions in scikit-learn with both multiclass problem as with single class problems. Ex.:

from sklearn.metrics import precision_recall_fscore_support as score

predicted = [1,2,3,4,5,1,2,1,1,4,5] 
y_test = [1,2,3,4,5,1,2,1,1,4,1]

precision, recall, fscore, support = score(y_test, predicted)

print('precision: {}'.format(precision))
print('recall: {}'.format(recall))
print('fscore: {}'.format(fscore))
print('support: {}'.format(support))

This way you end up with tangible and interpretable numbers for each of the classes.

| Label | Precision | Recall | FScore | Support |
|-------|-----------|--------|--------|---------|
| 1     | 94%       | 83%    | 0.88   | 204     |
| 2     | 71%       | 50%    | 0.54   | 127     |
| ...   | ...       | ...    | ...    | ...     |
| 4     | 80%       | 98%    | 0.89   | 838     |
| 5     | 93%       | 81%    | 0.91   | 1190    |

Then...

2.

... you can tell if the unbalanced data is even a problem. If the scoring for the less represented classes (class 1 and 2) are lower than for the classes with more training samples (class 4 and 5) then you know that the unbalanced data is in fact a problem, and you can act accordingly, as described in some of the other answers in this thread. However, if the same class distribution is present in the data you want to predict on, your unbalanced training data is a good representative of the data, and hence, the unbalance is a good thing.

fail to change placeholder color with Bootstrap 3

Assign the placeholder to a class selector like this:

.form-control::-webkit-input-placeholder { color: white; }  /* WebKit, Blink, Edge */
.form-control:-moz-placeholder { color: white; }  /* Mozilla Firefox 4 to 18 */
.form-control::-moz-placeholder { color: white; }  /* Mozilla Firefox 19+ */
.form-control:-ms-input-placeholder { color: white; }  /* Internet Explorer 10-11 */
.form-control::-ms-input-placeholder { color: white; }  /* Microsoft Edge */

It will work then since a stronger selector was probably overriding your global. I'm on a tablet so i cant inspect and confirm which stronger selector it was :) But it does work I tried it in your fiddle.

This also answers your second question. By assigning it to a class or id and giving an input only that class you can control what inputs to style.

How to migrate GIT repository from one server to a new one

Copy it over. It's really that simple. :)

On the client side, just edit .git/config in the client's local repo to point your remotes to the new URL as necessary.

Javascript Drag and drop for touch devices

For anyone looking to use this and keep the 'click' functionality (as John Landheer mentions in his comment), you can do it with just a couple of modifications:

Add a couple of globals:

var clickms = 100;
var lastTouchDown = -1;

Then modify the switch statement from the original to this:

var d = new Date();
switch(event.type)
{
    case "touchstart": type = "mousedown"; lastTouchDown = d.getTime(); break;
    case "touchmove": type="mousemove"; lastTouchDown = -1; break;        
    case "touchend": if(lastTouchDown > -1 && (d.getTime() - lastTouchDown) < clickms){lastTouchDown = -1; type="click"; break;} type="mouseup"; break;
    default: return;
}

You may want to adjust 'clickms' to your tastes. Basically it's just watching for a 'touchstart' followed quickly by a 'touchend' to simulate a click.

UTF-8: General? Bin? Unicode?

Really, I tested saving values like 'é' and 'e' in column with unique index and they cause duplicate error on both 'utf8_unicode_ci' and 'utf8_general_ci'. You can save them only in 'utf8_bin' collated column.

And mysql docs (in http://dev.mysql.com/doc/refman/5.7/en/charset-applications.html) suggest into its examples set 'utf8_general_ci' collation.

[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci

jQuery - Illegal invocation

My problem was unrelated to processData. It was because I sent a function that cannot be called later with apply because it did not have enough arguments. Specifically I shouldn't have used alert as the error callback.

$.ajax({
    url: csvApi,
    success: parseCsvs,
    dataType: "json",
    timeout: 5000,
    processData: false,
    error: alert
});

See this answer for more information on why that can be a problem: Why are certain function calls termed "illegal invocations" in JavaScript?

The way I was able to discover this was by adding a console.log(list[ firingIndex ]) to jQuery so I could track what it was firing.

This was the fix:

function myError(jqx, textStatus, errStr) {
    alert(errStr);
}

$.ajax({
    url: csvApi,
    success: parseCsvs,
    dataType: "json",
    timeout: 5000,
    error: myError // Note that passing `alert` instead can cause a "jquery.js:3189 Uncaught TypeError: Illegal invocation" sometimes
});

How to install Hibernate Tools in Eclipse?

uncompress the zip HibernateTools-3.2.4.Beta1-R20081031133 later in eclipse --> menu Help -> Update Sofwate -> add site -> local add, and select de folder uncompress an install automatic

Python: json.loads returns items prefixing with 'u'

Everything is cool, man. The 'u' is a good thing, it indicates that the string is of type Unicode in python 2.x.

http://docs.python.org/2/howto/unicode.html#the-unicode-type

jQuery using append with effects

Something like:

$('#test').append('<div id="newdiv">Hello</div>').hide().show('slow');

should do it?

Edit: sorry, mistake in code and took Matt's suggestion on board too.

Setting default permissions for newly created files and sub-directories under a directory in Linux?

It's ugly, but you can use the setfacl command to achieve exactly what you want.

On a Solaris machine, I have a file that contains the acls for users and groups. Unfortunately, you have to list all of the users (at least I couldn't find a way to make this work otherwise):

user::rwx
user:user_a:rwx
user:user_b:rwx
...
group::rwx
mask:rwx
other:r-x
default:user:user_a:rwx
default:user:user_b:rwx
....
default:group::rwx
default:user::rwx
default:mask:rwx
default:other:r-x

Name the file acl.lst and fill in your real user names instead of user_X.

You can now set those acls on your directory by issuing the following command:

setfacl -f acl.lst /your/dir/here

SQL query to select distinct row with minimum value

Use:

SELECT tbl.*
FROM TableName tbl
  INNER JOIN
  (
    SELECT Id, MIN(Point) MinPoint
    FROM TableName
    GROUP BY Id
  ) tbl1
  ON tbl1.id = tbl.id
WHERE tbl1.MinPoint = tbl.Point

How do I call an Angular 2 pipe with multiple arguments?

I use Pipes in Angular 2+ to filter arrays of objects. The following takes multiple filter arguments but you can send just one if that suits your needs. Here is a StackBlitz Example. It will find the keys you want to filter by and then filters by the value you supply. It's actually quite simple, if it sounds complicated it's not, check out the StackBlitz Example.

Here is the Pipe being called in an *ngFor directive,

<div *ngFor='let item of items | filtermulti: [{title:"mr"},{last:"jacobs"}]' >
  Hello {{item.first}} !
</div>

Here is the Pipe,

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filtermulti'
})
export class FiltermultiPipe implements PipeTransform {
  transform(myobjects: Array<object>, args?: Array<object>): any {
    if (args && Array.isArray(myobjects)) {
      // copy all objects of original array into new array of objects
      var returnobjects = myobjects;
      // args are the compare oprators provided in the *ngFor directive
      args.forEach(function (filterobj) {
        let filterkey = Object.keys(filterobj)[0];
        let filtervalue = filterobj[filterkey];
        myobjects.forEach(function (objectToFilter) {
          if (objectToFilter[filterkey] != filtervalue && filtervalue != "") {
            // object didn't match a filter value so remove it from array via filter
            returnobjects = returnobjects.filter(obj => obj !== objectToFilter);
          }
        })
      });
      // return new array of objects to *ngFor directive
      return returnobjects;
    }
  }
}

And here is the Component containing the object to filter,

import { Component } from '@angular/core';
import { FiltermultiPipe } from './pipes/filtermulti.pipe';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  items = [{ title: "mr", first: "john", last: "jones" }
   ,{ title: "mr", first: "adrian", last: "jacobs" }
   ,{ title: "mr", first: "lou", last: "jones" }
   ,{ title: "ms", first: "linda", last: "hamilton" }
  ];
}

StackBlitz Example

GitHub Example: Fork a working copy of this example here

*Please note that in an answer provided by Gunter, Gunter states that arrays are no longer used as filter interfaces but I searched the link he provides and found nothing speaking to that claim. Also, the StackBlitz example provided shows this code working as intended in Angular 6.1.9. It will work in Angular 2+.

Happy Coding :-)

How can I set focus on an element in an HTML form using JavaScript?

Do this.

If your element is something like this..

<input type="text" id="mytext"/>

Your script would be

<script>
function setFocusToTextBox(){
    document.getElementById("mytext").focus();
}
</script>

How to resolve "must be an instance of string, string given" prior to PHP 7?

I got this error when invoking a function from a Laravel Controller to a PHP file.

After a couple of hours, I found the problem: I was using $this from within a static function.

What is the most effective way to get the index of an iterator of an std::vector?

I'd use the - variant for std::vector only - it's pretty clear what is meant, and the simplicity of the operation (which isn't more than a pointer subtraction) is expressed by the syntax (distance, on the other side, sounds like pythagoras on the first reading, doesn't it?). As UncleBen points out, - also acts as a static assertion in case vector is accidentially changed to list.

Also I think it is much more common - have no numbers to prove it, though. Master argument: it - vec.begin() is shorter in source code - less typing work, less space consumed. As it's clear that the right answer to your question boils down to be a matter of taste, this can also be a valid argument.

PDO with INSERT INTO through prepared statements

I have just rewritten the code to the following:

    $dbhost = "localhost";
    $dbname = "pdo";
    $dbusername = "root";
    $dbpassword = "845625";

    $link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
    $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $statement = $link->prepare("INSERT INTO testtable(name, lastname, age)
        VALUES(?,?,?)");

    $statement->execute(array("Bob","Desaunois",18));

And it seems to work now. BUT. if I on purpose cause an error to occur, it does not say there is any. The code works, but still; should I encounter more errors, I will not know why.

Java 8 stream's .min() and .max(): why does this compile?

Let me explain what is happening here, because it isn't obvious!

First, Stream.max() accepts an instance of Comparator so that items in the stream can be compared against each other to find the minimum or maximum, in some optimal order that you don't need to worry too much about.

So the question is, of course, why is Integer::max accepted? After all it's not a comparator!

The answer is in the way that the new lambda functionality works in Java 8. It relies on a concept which is informally known as "single abstract method" interfaces, or "SAM" interfaces. The idea is that any interface with one abstract method can be automatically implemented by any lambda - or method reference - whose method signature is a match for the one method on the interface. So examining the Comparator interface (simple version):

public Comparator<T> {
    T compare(T o1, T o2);
}

If a method is looking for a Comparator<Integer>, then it's essentially looking for this signature:

int xxx(Integer o1, Integer o2);

I use "xxx" because the method name is not used for matching purposes.

Therefore, both Integer.min(int a, int b) and Integer.max(int a, int b) are close enough that autoboxing will allow this to appear as a Comparator<Integer> in a method context.

Stopping a CSS3 Animation on last frame

I learned today that there is a limit you want to use for the fill-mode. This is from an Apple dev. Rumor is * around * six, but not certain. Alternatively, you can set the initial state of your class to how you want the animation to end, then * initialize * it at from / 0% .

Wireshark vs Firebug vs Fiddler - pros and cons?

Wireshark, Firebug, Fiddler all do similar things - capture network traffic.

  • Wireshark captures any kind of network packet. It can capture packet details below TCP/IP (HTTP is at the top). It does have filters to reduce the noise it captures.

  • Firebug tracks each request the browser page makes and captures the associated headers and the time taken for each stage of the request (DNS, receiving, sending, ...).

  • Fiddler works as an HTTP/HTTPS proxy. It captures every HTTP request the computer makes and records everything associated with it. It does allow things like converting post variables to a table form and editing/replaying requests. It doesn't, by default, capture localhost traffic in IE, see the FAQ for the workaround.

Combine a list of data frames into one data frame by row

The only thing that the solutions with data.table are missing is the identifier column to know from which dataframe in the list the data is coming from.

Something like this:

df_id <- data.table::rbindlist(listOfDataFrames, idcol = TRUE)

The idcol parameter adds a column (.id) identifying the origin of the dataframe contained in the list. The result would look to something like this:

.id a         b           c
1   u   -0.05315128 -1.31975849 
1   b   -1.00404849 1.15257952  
1   y   1.17478229  -0.91043925 
1   q   -1.65488899 0.05846295  
1   c   -1.43730524 0.95245909  
1   b   0.56434313  0.93813197  

Format number to always show 2 decimal places

var quantity = 12;

var import1 = 12.55;

var total = quantity * import1;

var answer = parseFloat(total).toFixed(2);

document.write(answer);

HTML button onclick event

on first button add the following.

onclick="window.location.href='Students.html';"

similarly do the rest 2 buttons.

<input type="button" value="Add Students" onclick="window.location.href='Students.html';"> 
<input type="button" value="Add Courses" onclick="window.location.href='Courses.html';"> 
<input type="button" value="Student Payments" onclick="window.location.href='Payments.html';">

Rails DB Migration - How To Drop a Table?

First generate an empty migration with any name you'd like. It's important to do it this way since it creates the appropriate date.

rails generate migration DropProductsTable

This will generate a .rb file in /db/migrate/ like 20111015185025_drop_products_table.rb

Now edit that file to look like this:

class DropProductsTable < ActiveRecord::Migration
  def up
    drop_table :products
  end

  def down
    raise ActiveRecord::IrreversibleMigration
  end
end

The only thing I added was drop_table :products and raise ActiveRecord::IrreversibleMigration.

Then run rake db:migrate and it'll drop the table for you.

How to stop C# console applications from closing automatically?

You can just compile (start debugging) your work with Ctrl+F5.

Try it. I always do it and the console shows me my results open on it. No additional code is needed.

Declare and Initialize String Array in VBA

Dim myStringArray() As String
*code*
redim myStringArray(size_of_your_array)

Then you can do something static like this:

myStringArray = { item_1, item_2, ... }

Or something iterative like this:

Dim x
For x = 0 To size_of_your_array
    myStringArray(x) = data_source(x).Name
Next x

How do I fix 'ImportError: cannot import name IncompleteRead'?

Simply running easy_install -U pip resolved my problem.

EnterKey to press button in VBA Userform

Further to @Penn's comment, and in case the link breaks, you can also achieve this by setting the Default property of the button to True (you can set this in the properties window, open by hitting F4)

That way whenever Return is hit, VBA knows to activate the button's click event. Similarly setting the Cancel property of a button to True would cause that button's click event to run whenever ESC key is hit (useful for gracefully exiting the Userform)


Source: Olivier Jacot-Descombes's answer accessible here https://stackoverflow.com/a/22793040/6609896

Fine control over the font size in Seaborn plots for academic papers

You are right. This is a badly documented issue. But you can change the font size parameter (by opposition to font scale) directly after building the plot. Check the following example:

import seaborn as sns
tips = sns.load_dataset("tips")

b = sns.boxplot(x=tips["total_bill"])
b.axes.set_title("Title",fontsize=50)
b.set_xlabel("X Label",fontsize=30)
b.set_ylabel("Y Label",fontsize=20)
b.tick_params(labelsize=5)
sns.plt.show()

, which results in this:

Different font sizes for different labels

To make it consistent in between plots I think you just need to make sure the DPI is the same. By the way it' also a possibility to customize a bit the rc dictionaries since "font.size" parameter exists but I'm not too sure how to do that.

NOTE: And also I don't really understand why they changed the name of the font size variables for axis labels and ticks. Seems a bit un-intuitive.

GitHub README.md center image

For left alignment

 <img align="left" width="600" height="200" src="https://www.python.org/python-.png">

For right alignment

<img align="right" width="600" height="200" src="https://www.python.org/python-.png">

And for center alignment

<p align="center">
  <img width="600" height="200" src="https://www.python.org/python-.png">
</p>

Fork it here for future references, if you find this useful.

How to list all the available keyspaces in Cassandra?

DESC KEYSPACES will do the job.

Also, If you want to describe schema of a particular keyspace you can use

DESC

JavaScript: clone a function

Short and simple:

Function.prototype.clone = function() {
  return new Function('return ' + this.toString())();
};

How do I interpret precision and scale of a number in a database?

Numeric precision refers to the maximum number of digits that are present in the number.

ie 1234567.89 has a precision of 9

Numeric scale refers to the maximum number of decimal places

ie 123456.789 has a scale of 3

Thus the maximum allowed value for decimal(5,2) is 999.99

cv2.imshow command doesn't work properly in opencv-python

Method 1:

The following code worked for me. Just adding the destroyAllWindows() didn't close the window. Adding another cv2.waitKey(1) at the end did the job.

im = cv2.imread("./input.jpg")
cv2.imshow("image", im)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)

credit : https://stackoverflow.com/a/50091712/8109630

Note for beginners:

  • This will open the image in a separate window, instead of displaying inline on the notebook. That is why we have to use the destroyAllWindows() to close it later.
  • So if you don't see a separate window pop up, check if it is behind your current window.
  • After you view the image press a key to close the popped up window.

Method 2:

If you want to display on the Jupyter notebook.

from matplotlib import pyplot as plt
import cv2

im = cv2.imread("./input.jpg")
color = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
plt.imshow(color)
plt.title('Image')
plt.show()

Parser Error when deploy ASP.NET application

This happens when the files inside the Debug and Release folder are not created properly(Either they are having wrong reference or having overwritten many times). I have faced the same problem in which, i everything works fine when we build the solution, but when i publish the website it gives me same error. I have solved this in following manner:

  1. Go to your Solution Explorer in Visual Studio and click on show hidden files (if they are not showing ! )
  2. you will find a folder named obj, open it .
  3. Here there are again 2 folder named respectively as Debug and Release. Now, delete the content from these two folder, Make sure that you do not delete the folders Debug and Release. Only delete the files and folders inside Debug and Release folder.
  4. Now build and publish your solution and everything will work like charm.

What would be the best method to code heading/title for <ul> or <ol>, Like we have <caption> in <table>?

how about making the heading a list-element with different styles like so

<ul>
 <li class="heading">heading</li>
 <li>list item</li>
 <li>list item</li>
 <li>list item</li>
 <li>list item</li>
</ul>

and the CSS

ul .heading {font-weight: normal; list-style: none;}

additionally, use a reset CSS to set margins and paddings right on the ul and li. here's a good reset CSS. once you've reset the margins and paddings, you can apply some margin on the list-elements other than the one's with the heading class, to indent them.

Java Class that implements Map and keeps insertion order?

I don't know if it is opensource, but after a little googling, I found this implementation of Map using ArrayList. It seems to be pre-1.5 Java, so you might want to genericize it, which should be easy. Note that this implementation has O(N) access, but this shouldn't be a problem if you don't add hundreds of widgets to your JPanel, which you shouldn't anyway.

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

Java ResultSet how to check if there are any results

if (!resultSet.isAfterLast() ) {    
System.out.println("No data"); 
} 

isAfterLast() also returns false for empty result set but since cursor is before first row anyways, this method seems more clear.

Android: How to set password property in an edit text?

See this link text view android:password

This applies for EditText as well, as it is a known direct subclass of TextView.

macro - open all files in a folder

Try the below code:

Sub opendfiles()

Dim myfile As Variant
Dim counter As Integer
Dim path As String

myfolder = "D:\temp\"
ChDir myfolder
myfile = Application.GetOpenFilename(, , , , True)
counter = 1
If IsNumeric(myfile) = True Then
    MsgBox "No files selected"
End If
While counter <= UBound(myfile)
    path = myfile(counter)
    Workbooks.Open path
    counter = counter + 1
Wend

End Sub

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>

you can use indexing if your enumerable type is string like below

((string[])MyEnumerableStringList)[0]

Unique Key constraints for multiple columns in Entity Framework

I found three ways to solve the problem.

Unique indexes in EntityFramework Core:

First approach:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<Entity>()
   .HasIndex(p => new {p.FirstColumn , p.SecondColumn}).IsUnique();
}

The second approach to create Unique Constraints with EF Core by using Alternate Keys.

Examples

One column:

modelBuilder.Entity<Blog>().HasAlternateKey(c => c.SecondColumn).HasName("IX_SingeColumn");

Multiple columns:

modelBuilder.Entity<Entity>().HasAlternateKey(c => new [] {c.FirstColumn, c.SecondColumn}).HasName("IX_MultipleColumns");

EF 6 and below:


First approach:

dbContext.Database.ExecuteSqlCommand(string.Format(
                        @"CREATE UNIQUE INDEX LX_{0} ON {0} ({1})", 
                                 "Entitys", "FirstColumn, SecondColumn"));

This approach is very fast and useful but the main problem is that Entity Framework doesn't know anything about those changes!


Second approach:
I found it in this post but I did not tried by myself.

CreateIndex("Entitys", new string[2] { "FirstColumn", "SecondColumn" },
              true, "IX_Entitys");

The problem of this approach is the following: It needs DbMigration so what do you do if you don't have it?


Third approach:
I think this is the best one but it requires some time to do it. I will just show you the idea behind it: In this link http://code.msdn.microsoft.com/CSASPNETUniqueConstraintInE-d357224a you can find the code for unique key data annotation:

[UniqueKey] // Unique Key 
public int FirstColumn  { get; set;}
[UniqueKey] // Unique Key 
public int SecondColumn  { get; set;}

// The problem hier
1, 1  = OK 
1 ,2  = NO OK 1 IS UNIQUE

The problem for this approach; How can I combine them? I have an idea to extend this Microsoft implementation for example:

[UniqueKey, 1] // Unique Key 
public int FirstColumn  { get; set;}
[UniqueKey ,1] // Unique Key 
public int SecondColumn  { get; set;}

Later in the IDatabaseInitializer as described in the Microsoft example you can combine the keys according to the given integer. One thing has to be noted though: If the unique property is of type string then you have to set the MaxLength.

How to evaluate a boolean variable in an if block in bash?

Note that the if $myVar; then ... ;fi construct has a security problem you might want to avoid with

case $myvar in
  (true)    echo "is true";;
  (false)   echo "is false";;
  (rm -rf*) echo "I just dodged a bullet";;
esac

You might also want to rethink why if [ "$myvar" = "true" ] appears awkward to you. It's a shell string comparison that beats possibly forking a process just to obtain an exit status. A fork is a heavy and expensive operation, while a string comparison is dead cheap. Think a few CPU cycles versus several thousand. My case solution is also handled without forks.

What is the meaning of ImagePullBackOff status on a Kubernetes pod?

I too had this problem, when I checked I image that I was pulling from a private registry was removed If we describe pod it will show pulling event and the image it's trying to pull

kubectl describe pod <POD_NAME>

Events:
 Type     Reason   Age                  From              Message
 ----     ------   ----                 ----              -------
 Normal   Pulling  18h (x35 over 20h)   kubelet, gsk-kub  Pulling image "registeryName:tag"
 Normal   BackOff  11m (x822 over 20h)  kubelet, gsk-kub  Back-off pulling image "registeryName:tag"
 Warning  Failed   91s (x858 over 20h)  kubelet, gsk-kub  Error: ImagePullBackOff

Adding days to a date in Java

Simple, without any other API:

To add 8 days:

Date today=new Date();
long ltime=today.getTime()+8*24*60*60*1000;
Date today8=new Date(ltime);

What is hashCode used for? Is it unique?

This is from the msdn article here:

https://blogs.msdn.microsoft.com/tomarcher/2006/05/10/are-hash-codes-unique/

"While you will hear people state that hash codes generate a unique value for a given input, the fact is that, while difficult to accomplish, it is technically feasible to find two different data inputs that hash to the same value. However, the true determining factors regarding the effectiveness of a hash algorithm lie in the length of the generated hash code and the complexity of the data being hashed."

So just use a hash algorithm suitable to your data size and it will have unique hashcodes.

What is the optimal algorithm for the game 2048?

This is not a direct answer to OP's question, this is more of the stuffs (experiments) I tried so far to solve the same problem and obtained some results and have some observations that I want to share, I am curious if we can have some further insights from this.

I just tried my minimax implementation with alpha-beta pruning with search-tree depth cutoff at 3 and 5. I was trying to solve the same problem for a 4x4 grid as a project assignment for the edX course ColumbiaX: CSMM.101x Artificial Intelligence (AI).

I applied convex combination (tried different heuristic weights) of couple of heuristic evaluation functions, mainly from intuition and from the ones discussed above:

  1. Monotonicity
  2. Free Space Available

In my case, the computer player is completely random, but still i assumed adversarial settings and implemented the AI player agent as the max player.

I have 4x4 grid for playing the game.

Observation:

If I assign too much weights to the first heuristic function or the second heuristic function, both the cases the scores the AI player gets are low. I played with many possible weight assignments to the heuristic functions and take a convex combination, but very rarely the AI player is able to score 2048. Most of the times it either stops at 1024 or 512.

I also tried the corner heuristic, but for some reason it makes the results worse, any intuition why?

Also, I tried to increase the search depth cut-off from 3 to 5 (I can't increase it more since searching that space exceeds allowed time even with pruning) and added one more heuristic that looks at the values of adjacent tiles and gives more points if they are merge-able, but still I am not able to get 2048.

I think it will be better to use Expectimax instead of minimax, but still I want to solve this problem with minimax only and obtain high scores such as 2048 or 4096. I am not sure whether I am missing anything.

Below animation shows the last few steps of the game played by the AI agent with the computer player:

enter image description here

Any insights will be really very helpful, thanks in advance. (This is the link of my blog post for the article: https://sandipanweb.wordpress.com/2017/03/06/using-minimax-with-alpha-beta-pruning-and-heuristic-evaluation-to-solve-2048-game-with-computer/ and the youtube video: https://www.youtube.com/watch?v=VnVFilfZ0r4)

The following animation shows the last few steps of the game played where the AI player agent could get 2048 scores, this time adding the absolute value heuristic too:

enter image description here

The following figures show the game tree explored by the player AI agent assuming the computer as adversary for just a single step:

enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here

Windows batch files: .bat vs .cmd?

Still, on Windows 7, BAT files have also this difference : If you ever create files TEST.BAT and TEST.CMD in the same directory, and you run TEST in that directory, it'll run the BAT file.

C:\>echo %PATHEXT%
.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC

C:\Temp>echo echo bat > test.bat

C:\Temp>echo echo cmd > test.cmd

C:\Temp>test

C:\Temp>echo bat
bat

C:\Temp>

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

Just to add - Safari 2 and earlier definitely didn't support PUT and DELETE. I get the impression 3 did, but I don't have it around to test anymore. Safari 4 definitely does support PUT and DELETE.

awk - concatenate two string variable and assign to a third

Just use var = var1 var2 and it will automatically concatenate the vars var1 and var2:

awk '{new_var=$1$2; print new_var}' file

You can put an space in between with:

awk '{new_var=$1" "$2; print new_var}' file

Which in fact is the same as using FS, because it defaults to the space:

awk '{new_var=$1 FS $2; print new_var}' file

Test

$ cat file
hello how are you
i am fine
$ awk '{new_var=$1$2; print new_var}' file
hellohow
iam
$ awk '{new_var=$1 FS $2; print new_var}' file
hello how
i am

You can play around with it in ideone: http://ideone.com/4u2Aip

How to printf "unsigned long" in C?

  • %lu for unsigned long
  • %llu for unsigned long long

How to change the map center in Leaflet.js

You can also use:

map.setView(new L.LatLng(40.737, -73.923), 8);

It just depends on what behavior you want. map.panTo() will pan to the location with zoom/pan animation, while map.setView() immediately set the new view to the desired location/zoom level.

Adding a leading zero to some values in column in MySQL

A previous answer using LPAD() is optimal. However, in the event you want to do special or advanced processing, here is a method that allows more iterative control over the padding. Also serves as an example using other constructs to achieve the same thing.

UPDATE
    mytable
SET
    mycolumn = CONCAT(
        REPEAT(
            "0",
            8 - LENGTH(mycolumn)
        ),
        mycolumn
    )
WHERE
    LENGTH(mycolumn) < 8;

How do you make a deep copy of an object?

Deep copying can only be done with each class's consent. If you have control over the class hierarchy then you can implement the clonable interface and implement the Clone method. Otherwise doing a deep copy is impossible to do safely because the object may also be sharing non-data resources (e.g. database connections). In general however deep copying is considered bad practice in the Java environment and should be avoided via the appropriate design practices.

Hashing a dictionary?

To preserve key order, instead of hash(str(dictionary)) or hash(json.dumps(dictionary)) I would prefer quick-and-dirty solution:

from pprint import pformat
h = hash(pformat(dictionary))

It will work even for types like DateTime and more that are not JSON serializable.

Oracle SQL Developer: Unable to find a JVM

The solution that worked for me: If you have Sqldeveloper with java incorporated, you can use the \sqldeveloper\bin\sqldeveloper.bat to launch sqldeveloper as told here.

remove url parameters with javascript or jquery

For example we have:

example.com/list/search?q=Somethink

And you need use variable url like this by window.location.href:

example.com/list/edit

From url:

example.com/list/search?q=Somethink
example.com/list/
var url = (window.location.href);
    url = url.split('/search')[0];
    url = (url + '/edit');

This is simple solution:-)

PHP error: "The zip extension and unzip command are both missing, skipping."

Not to belabor the point, but if you are working in a Dockerfile, you would solve this particular issue with Composer by installing the unzip utility. Below is an example using the official PHP image to install unzip and the zip PHP extension for good measure.

FROM php:7.4-apache

# Install Composer
COPY --from=composer /usr/bin/composer /usr/bin/composer

# Install unzip utility and libs needed by zip PHP extension 
RUN apt-get update && apt-get install -y \
    zlib1g-dev \
    libzip-dev \
    unzip
RUN docker-php-ext-install zip

This is a helpful GitHub issue where the above is lovingly lifted from.

How to read a file in reverse order?

for line in reversed(open("filename").readlines()):
    print line.rstrip()

And in Python 3:

for line in reversed(list(open("filename"))):
    print(line.rstrip())

is there a css hack for safari only NOT chrome?

At the end I use a little JavaScript to achieve it:

if (navigator.vendor.startsWith('Apple'))
    document.documentElement.classList.add('on-apple');

then in my CSS to target Apple browser engine the selector will be:

.on-apple .my-class{
    ...
}

How do I use a delimiter with Scanner.useDelimiter in Java?

The scanner can also use delimiters other than whitespace.

Easy example from Scanner API:

 String input = "1 fish 2 fish red fish blue fish";

 // \\s* means 0 or more repetitions of any whitespace character 
 // fish is the pattern to find
 Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");

 System.out.println(s.nextInt());   // prints: 1
 System.out.println(s.nextInt());   // prints: 2
 System.out.println(s.next());      // prints: red
 System.out.println(s.next());      // prints: blue

 // don't forget to close the scanner!!
 s.close(); 

The point is to understand the regular expressions (regex) inside the Scanner::useDelimiter. Find an useDelimiter tutorial here.


To start with regular expressions here you can find a nice tutorial.

Notes

abc…    Letters
123…    Digits
\d      Any Digit
\D      Any Non-digit character
.       Any Character
\.      Period
[abc]   Only a, b, or c
[^abc]  Not a, b, nor c
[a-z]   Characters a to z
[0-9]   Numbers 0 to 9
\w      Any Alphanumeric character
\W      Any Non-alphanumeric character
{m}     m Repetitions
{m,n}   m to n Repetitions
*       Zero or more repetitions
+       One or more repetitions
?       Optional character
\s      Any Whitespace
\S      Any Non-whitespace character
^…$     Starts and ends
(…)     Capture Group
(a(bc)) Capture Sub-group
(.*)    Capture all
(ab|cd) Matches ab or cd

Print series of prime numbers in python

Using filter function.

l=range(1,101)
for i in range(2,10): # for i in range(x,y), here y should be around or <= sqrt(101)
    l = filter(lambda x: x==i or x%i, l)

print l

How can I use jQuery to move a div across the screen

Just a quick little function I drummed up that moves DIVs from their current spot to a target spot, one pixel step at a time. I tried to comment as best as I could, but the part you're interested in, is in example 1 and example 2, right after [$(function() { // jquery document.ready]. Put your bounds checking code there, and then exit the interval if conditions are met. Requires jQuery.

First the Demo: http://jsfiddle.net/pnYWY/

First the DIVs...

<style>
  .moveDiv {
    position:absolute;
    left:20px;
    top:20px;
    width:10px;
    height:10px;
    background-color:#ccc;
  }

  .moveDivB {
    position:absolute;
    left:20px;
    top:20px;
    width:10px;
    height:10px;
    background-color:#ccc;
  }
</style>


<div class="moveDiv"></div>
<div class="moveDivB"></div>

example 1) Start

// first animation (fire right away)
var myVar = setInterval(function(){
    $(function() { // jquery document.ready

        // returns true if it just took a step
        // returns false if the div has arrived
        if( !move_div_step(55,25,'.moveDiv') )
        {
            // arrived...
            console.log('arrived'); 
            clearInterval(myVar);
        }

    });
},50); // set speed here in ms for your delay

example 2) Delayed Start

// pause and then fire an animation..
setTimeout(function(){
    var myVarB = setInterval(function(){
        $(function() { // jquery document.ready
            // returns true if it just took a step
            // returns false if the div has arrived
            if( !move_div_step(25,55,'.moveDivB') )
            {
                // arrived...
                console.log('arrived'); 
                clearInterval(myVarB);
            }
        });
    },50); // set speed here in ms for your delay
},5000);// set speed here for delay before firing

Now the Function:

function move_div_step(xx,yy,target) // takes one pixel step toward target
{
    // using a line algorithm to move a div one step toward a given coordinate.
    var div_target = $(target);

    // get current x and current y
    var x = div_target.position().left; // offset is relative to document; position() is relative to parent;
    var y = div_target.position().top;

    // if x and y are = to xx and yy (destination), then div has arrived at it's destination.
    if(x == xx && y == yy)
        return false;

    // find the distances travelled
    var dx = xx - x;
    var dy = yy - y;

    // preventing time travel
    if(dx < 0)          dx *= -1;
    if(dy < 0)          dy *= -1;

    // determine speed of pixel travel...
    var sx=1, sy=1;

    if(dx > dy)         sy = dy/dx;
    else if(dy > dx)    sx = dx/dy;

    // find our one...
    if(sx == sy) // both are one..
    {
        if(x <= xx) // are we going forwards?
        {
            x++; y++;
        }
        else  // .. we are going backwards.
        {
            x--; y--;
        }       
    }
    else if(sx > sy) // x is the 1
    {
        if(x <= xx) // are we going forwards..?
            x++;
        else  // or backwards?
            x--;

        y += sy;
    }
    else if(sy > sx) // y is the 1 (eg: for every 1 pixel step in the y dir, we take 0.xxx step in the x
    {
        if(y <= yy) // going forwards?
            y++;
        else  // .. or backwards?
            y--;

        x += sx;
    }

    // move the div
    div_target.css("left", x);
    div_target.css("top",  y);

    return true;
}  // END :: function move_div_step(xx,yy,target)

How to add an ORDER BY clause using CodeIgniter's Active Record methods?

function getProductionGroupItems($itemId){
     $this->db->select("*");
     $this->db->where("id",$itemId);
     $this->db->or_where("parent_item_id",$itemId);

    /*********** order by *********** */
     $this->db->order_by("id", "asc");

     $q=$this->db->get("recipe_products");
     if($q->num_rows()>0){
         foreach($q->result() as $row){
             $data[]=$row;
         }
         return $data;
     }
    return false;
}