Programs & Examples On #Nhprof

A profiler designed specifically for NHibernate.

What key shortcuts are to comment and uncomment code?

Use the keys CtrlK,C to comment out the line and CtrlK,U to uncomment the line.

How to put img inline with text

Please make use of the code below to display images inline:

<img style='vertical-align:middle;' src='somefolder/icon.gif'>
<div style='vertical-align:middle; display:inline;'>
Your text here
</div>

How to acces external json file objects in vue.js app

If your file looks like this:

[
    {
        "firstname": "toto",
        "lastname": "titi"
    },
    {
        "firstname": "toto2",
        "lastname": "titi2"
    },
]

You can do:

import json from './json/data.json';
// ....
json.forEach(x => { console.log(x.firstname, x.lastname); });

AngularJS : How do I switch views from a controller function?

Without doing a full revamp of the default routing (#/ViewName) environment, I was able to do a slight modification of Cody's tip and got it working great.

the controller

.controller('GeneralCtrl', ['$route', '$routeParams', '$location',
        function($route, $routeParams, $location) {
            ...
            this.goToView = function(viewName){
                $location.url('/' + viewName);
            }
        }]
    );

the view

...
<li ng-click="general.goToView('Home')">HOME</li>
...

What brought me to this solution was when I was attempting to integrate a Kendo Mobile UI widget into an angular environment I was losing the context of my controller and the behavior of the regular anchor tag was also being hijacked. I re-established my context from within the Kendo widget and needed to use a method to navigate...this worked.

Thanks for the previous posts!

Get current location of user in Android without using GPS or internet

What you are looking to do is get the position using the LocationManager.NETWORK_PROVIDER instead of LocationManager.GPS_PROVIDER. The NETWORK_PROVIDER will resolve on the GSM or wifi, which ever available. Obviously with wifi off, GSM will be used. Keep in mind that using the cell network is accurate to basically 500m.

http://developer.android.com/guide/topics/location/obtaining-user-location.html has some really great information and sample code.

After you get done with most of the code in OnCreate(), add this:

// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
      // Called when a new location is found by the network location provider.
      makeUseOfNewLocation(location);
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}

    public void onProviderEnabled(String provider) {}

    public void onProviderDisabled(String provider) {}
  };

// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

You could also have your activity implement the LocationListener class and thus implement onLocationChanged() in your activity.

How to restore/reset npm configuration to default values?

To reset user defaults

Run this in the command line (or git bash on windows):

echo "" > $(npm config get userconfig)
npm config edit

To reset global defaults

echo "" > $(npm config get globalconfig)
npm config --global edit

If you need sudo then run this instead:

sudo sh -c 'echo "" > $(npm config get globalconfig)'

How to Create a Form Dynamically Via Javascript

some thing as follows ::

Add this After the body tag

This is a rough sketch, you will need to modify it according to your needs.

<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");

var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");

var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");

f.appendChild(i);
f.appendChild(s);

//and some more input elements here
//and dont forget to add a submit button

document.getElementsByTagName('body')[0].appendChild(f);

</script>

How do I update the GUI from another thread?

This in my C# 3.0 variation of Ian Kemp's solution:

public static void SetPropertyInGuiThread<C,V>(this C control, Expression<Func<C, V>> property, V value) where C : Control
{
    var memberExpression = property.Body as MemberExpression;
    if (memberExpression == null)
        throw new ArgumentException("The 'property' expression must specify a property on the control.");

    var propertyInfo = memberExpression.Member as PropertyInfo;
    if (propertyInfo == null)
        throw new ArgumentException("The 'property' expression must specify a property on the control.");

    if (control.InvokeRequired)
        control.Invoke(
            (Action<C, Expression<Func<C, V>>, V>)SetPropertyInGuiThread,
            new object[] { control, property, value }
        );
    else
        propertyInfo.SetValue(control, value, null);
}

You call it like this:

myButton.SetPropertyInGuiThread(b => b.Text, "Click Me!")
  1. It adds null-checking to the result of the "as MemberExpression".
  2. It improves the static type-safety.

Otherwise, the original is a very nice solution.

Invert colors of an image in CSS or JavaScript

For inversion from 0 to 1 and back you can use this library InvertImages, which provides support for IE 10. I also tested with IE 11 and it should work.

<hr> tag in Twitter Bootstrap not functioning correctly?

the css property of <hr> are :

hr {
  -moz-border-bottom-colors: none;
  -moz-border-image: none;
  -moz-border-left-colors: none;
  -moz-border-right-colors: none;
  -moz-border-top-colors: none;
  border-color: #EEEEEE -moz-use-text-color #FFFFFF;
  border-style: solid none;
  border-width: 1px 0;
  margin: 18px 0;
}

It correspond to a 1px horizontal line with a very light grey and vertical margin of 18px.

and because <hr> is inside a <div> without class the width depends on the content of the <div>

if you would like the <hr> to be full width, replace <div> with <div class='row'><div class='span12'> (with according closing tags).

If you expect something different, describe what you expect by adding a comment.

What is the meaning of @_ in Perl?

You can also use shift for individual variables in most cases:

$var1 = shift;

This is a topic in which you should research further as Perl has a number of interesting ways of accessing outside information inside your sub routine.

Restful API service

Note that the solution from Robby Pond is somehow lacking: in this way you only allow todo one api call at a time since the IntentService only handles one intent at a time. Often you want to perform parallel api calls. If you want todo this you have to extend Service instead of IntentService and create your own thread.

Groovy - Convert object to JSON string

Do you mean like:

import groovy.json.*

class Me {
    String name
}

def o = new Me( name: 'tim' )

println new JsonBuilder( o ).toPrettyString()

How can I remove duplicate rows?

I prefer the subquery\having count(*) > 1 solution to the inner join because I found it easier to read and it was very easy to turn into a SELECT statement to verify what would be deleted before you run it.

--DELETE FROM table1 
--WHERE id IN ( 
     SELECT MIN(id) FROM table1 
     GROUP BY col1, col2, col3 
     -- could add a WHERE clause here to further filter
     HAVING count(*) > 1
--)

Is there a C# case insensitive equals operator?

or

if (StringA.Equals(StringB, StringComparison.CurrentCultureIgnoreCase)) {

but you need to be sure that StringA is not null. So probably better tu use:

string.Equals(StringA , StringB, StringComparison.CurrentCultureIgnoreCase);

as John suggested

EDIT: corrected the bug

Postgresql, update if row with some unique value exists, else insert

This has been asked many times. A possible solution can be found here: https://stackoverflow.com/a/6527838/552671

This solution requires both an UPDATE and INSERT.

UPDATE table SET field='C', field2='Z' WHERE id=3;
INSERT INTO table (id, field, field2)
       SELECT 3, 'C', 'Z'
       WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);

With Postgres 9.1 it is possible to do it with one query: https://stackoverflow.com/a/1109198/2873507

How to insert blank lines in PDF?

You can trigger a newline by inserting Chunk.NEWLINE into your document. Here's an example.

public static void main(String args[]) {
    try {
        // create a new document
        Document document = new Document( PageSize.A4, 20, 20, 20, 20 );
        PdfWriter.getInstance( document, new FileOutputStream( "HelloWorld.pdf" ) );

        document.open();

        document.add( new Paragraph( "Hello, World!" ) );
        document.add( new Paragraph( "Hello, World!" ) );

        // add a couple of blank lines
        document.add( Chunk.NEWLINE );
        document.add( Chunk.NEWLINE );

        // add one more line with text
        document.add( new Paragraph( "Hello, World!" ) );

        document.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

Below is a screen shot showing part of the PDF that the code above produces.

Hello PDF with blank lines inserted

Algorithm for Determining Tic Tac Toe Game Over

If the board is n × n then there are n rows, n columns, and 2 diagonals. Check each of those for all-X's or all-O's to find a winner.

If it only takes x < n consecutive squares to win, then it's a little more complicated. The most obvious solution is to check each x × x square for a winner. Here's some code that demonstrates that.

(I didn't actually test this *cough*, but it did compile on the first try, yay me!)

public class TicTacToe
{
    public enum Square { X, O, NONE }

    /**
     * Returns the winning player, or NONE if the game has
     * finished without a winner, or null if the game is unfinished.
     */
    public Square findWinner(Square[][] board, int lengthToWin) {
        // Check each lengthToWin x lengthToWin board for a winner.    
        for (int top = 0; top <= board.length - lengthToWin; ++top) {
            int bottom = top + lengthToWin - 1;

            for (int left = 0; left <= board.length - lengthToWin; ++left) {
                int right = left + lengthToWin - 1;

                // Check each row.
                nextRow: for (int row = top; row <= bottom; ++row) {
                    if (board[row][left] == Square.NONE) {
                        continue;
                    }

                    for (int col = left; col <= right; ++col) {
                        if (board[row][col] != board[row][left]) {
                            continue nextRow;
                        }
                    }

                    return board[row][left];
                }

                // Check each column.
                nextCol: for (int col = left; col <= right; ++col) {
                    if (board[top][col] == Square.NONE) {
                        continue;
                    }

                    for (int row = top; row <= bottom; ++row) {
                        if (board[row][col] != board[top][col]) {
                            continue nextCol;
                        }
                    }

                    return board[top][col];
                }

                // Check top-left to bottom-right diagonal.
                diag1: if (board[top][left] != Square.NONE) {
                    for (int i = 1; i < lengthToWin; ++i) {
                        if (board[top+i][left+i] != board[top][left]) {
                            break diag1;
                        }
                    }

                    return board[top][left];
                }

                // Check top-right to bottom-left diagonal.
                diag2: if (board[top][right] != Square.NONE) {
                    for (int i = 1; i < lengthToWin; ++i) {
                        if (board[top+i][right-i] != board[top][right]) {
                            break diag2;
                        }
                    }

                    return board[top][right];
                }
            }
        }

        // Check for a completely full board.
        boolean isFull = true;

        full: for (int row = 0; row < board.length; ++row) {
            for (int col = 0; col < board.length; ++col) {
                if (board[row][col] == Square.NONE) {
                    isFull = false;
                    break full;
                }
            }
        }

        // The board is full.
        if (isFull) {
            return Square.NONE;
        }
        // The board is not full and we didn't find a solution.
        else {
            return null;
        }
    }
}

How do I replace NA values with zeros in an R dataframe?

If we are trying to replace NAs when exporting, for example when writing to csv, then we can use:

  write.csv(data, "data.csv", na = "0")

xlrd.biffh.XLRDError: Excel xlsx file; not supported

As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:

xlrd has explicitly removed support for anything other than xls files.

In your case, the solution is to:

  • make sure you are on a recent version of Pandas, at least 1.0.1, and preferably the latest release. 1.2 will make his even clearer.
  • install openpyxl: https://openpyxl.readthedocs.io/en/stable/
  • change your Pandas code to be:
    df1 = pd.read_excel(
         os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
         engine='openpyxl',
    )
    

How to get the selected item of a combo box to a string variable in c#

Try this:

string selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
MessageBox.Show(selected);

How to change UIPickerView height

Advantages:

  1. Makes setFrame of UIPickerView behave like it should
  2. No transform code within your UIViewController
  3. Works within viewWillLayoutSubviews to rescale/position the UIPickerView
  4. Works on the iPad without UIPopover
  5. The superclass always receives a valid height
  6. Works with iOS 5

Disadvantages:

  1. Requires you to subclass UIPickerView
  2. Requires the use of pickerView viewForRow to undo the transformation for the subViews
  3. UIAnimations might not work

Solution:

Subclass UIPickerView and overwrite the two methods using the following code. It combines subclassing, fixed height and the transformation approach.

#define FIXED_PICKER_HEIGHT 216.0f
- (void) setFrame:(CGRect)frame
{
    CGFloat targetHeight = frame.size.height;
    CGFloat scaleFactor = targetHeight / FIXED_PICKER_HEIGHT;
    frame.size.height = FIXED_PICKER_HEIGHT;//fake normal conditions for super
    self.transform = CGAffineTransformIdentity;//fake normal conditions for super
    [super setFrame:frame];
    frame.size.height = targetHeight;
    CGFloat dX=self.bounds.size.width/2, dY=self.bounds.size.height/2;
    self.transform = CGAffineTransformTranslate(CGAffineTransformScale(CGAffineTransformMakeTranslation(-dX, -dY), 1, scaleFactor), dX, dY);
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    //Your code goes here

    CGFloat inverseScaleFactor = FIXED_PICKER_HEIGHT/self.frame.size.height;
    CGAffineTransform scale = CGAffineTransformMakeScale(1, inverseScaleFactor);
    view.transform = scale;
    return view;
}

Using new line(\n) in string and rendering the same in HTML

You could use a pre tag instead of a div. This would automatically display your \n's in the correct way.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
         var display_txt = "1st line text" +"\n" + "2nd line text";
         $('#somediv').html(display_txt).css("color", "green");
});
</script>
</head>
<body>

<pre>
<p id="somediv"></p>
</pre>

</body>
</html>

How to rotate a 3D object on axis three.js?

Just in case...in r52 the method is called setEulerFromRotationMatrix instead of getRotationFromMatrix

Unable to access JSON property with "-" dash

In addition to this answer, note that in Node.js if you access JSON with the array syntax [] all nested JSON keys should follow that syntax

This is the wrong way

json.first.second.third['comment']

and will will give you the 'undefined' error.

This is the correct way

json['first']['second']['third']['comment'] 

Duplicate Entire MySQL Database

I sometimes do a mysqldump and pipe the output into another mysql command to import it into a different database.

mysqldump --add-drop-table -u wordpress -p wordpress | mysql -u wordpress -p wordpress_backup

Swift 3 - Comparing Date objects

Another way to do it:

    switch date1.compare(date2) {
        case .orderedAscending:
            break

        case .orderedDescending:
            break;

        case .orderedSame:
            break
    }

Padding or margin value in pixels as integer using jQuery

I probably use github.com/bramstein/jsizes jquery plugin for paddings and margins in very comfortable way, Thanks...

How to Create an excel dropdown list that displays text with a numeric hidden value

Data validation drop down

There is a list option in Data validation. If this is combined with a VLOOKUP formula you would be able to convert the selected value into a number.

The steps in Excel 2010 are:

  • Create your list with matching values.
  • On the Data tab choose Data Validation
  • The Data validation form will be displayed
  • Set the Allow dropdown to List
  • Set the Source range to the first part of your list
  • Click on OK (User messages can be added if required)

In a cell enter a formula like this

=VLOOKUP(A2,$D$3:$E$5,2,FALSE)

which will return the matching value from the second part of your list.

Screenshot of Data validation list

Form control drop down

Alternatively, Form controls can be placed on a worksheet. They can be linked to a range and return the position number of the selected value to a specific cell.

The steps in Excel 2010 are:

  • Create your list of data in a worksheet
  • Click on the Developer tab and dropdown on the Insert option
  • In the Form section choose Combo box or List box
  • Use the mouse to draw the box on the worksheet
  • Right click on the box and select Format control
  • The Format control form will be displayed
  • Click on the Control tab
  • Set the Input range to your list of data
  • Set the Cell link range to the cell where you want the number of the selected item to appear
  • Click on OK

Screenshot of form control

MySQL equivalent of DECODE function in Oracle

Try this:

Select Name, ELT(Age-12,'Thirteen','Fourteen','Fifteen','Sixteen',
   'Seventeen','Eighteen','Nineteen','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult') AS AgeBracket FROM Person

Is there a better way to compare dictionary values

You can use sets for this too

>>> a = {'x': 1, 'y': 2}
>>> b = {'y': 2, 'x': 1}
>>> set(a.iteritems())-set(b.iteritems())
set([])
>>> a['y']=3
>>> set(a.iteritems())-set(b.iteritems())
set([('y', 3)])
>>> set(b.iteritems())-set(a.iteritems())
set([('y', 2)])
>>> set(b.iteritems())^set(a.iteritems())
set([('y', 3), ('y', 2)])

.Contains() on a list of custom class objects

You need to implement IEquatable or override Equals() and GetHashCode()

For example:

public class CartProduct : IEquatable<CartProduct>
{
    public Int32 ID;
    public String Name;
    public Int32 Number;
    public Decimal CurrentPrice;

    public CartProduct(Int32 ID, String Name, Int32 Number, Decimal CurrentPrice)
    {
        this.ID = ID;
        this.Name = Name;
        this.Number = Number;
        this.CurrentPrice = CurrentPrice;
    }

    public String ToString()
    {
        return Name;
    }

    public bool Equals( CartProduct other )
    {
        // Would still want to check for null etc. first.
        return this.ID == other.ID && 
               this.Name == other.Name && 
               this.Number == other.Number && 
               this.CurrentPrice == other.CurrentPrice;
    }
}

How can I use the apply() function for a single column?

Given a sample dataframe df as:

a,b
1,2
2,3
3,4
4,5

what you want is:

df['a'] = df['a'].apply(lambda x: x + 1)

that returns:

   a  b
0  2  2
1  3  3
2  4  4
3  5  5

How to change DataTable columns order

We Can use this method for changing the column index but should be applied to all the columns if there are more than two number of columns otherwise it will show all the Improper values from data table....................

How to generate a number of most distinctive colors in R?

Not an answer to OP's question but it's worth mentioning that there is the viridis package which has good color palettes for sequential data. They are perceptually uniform, colorblind safe and printer-friendly.

To get the palette, simply install the package and use the function viridis_pal(). There are four options "A", "B", "C" and "D" to choose

install.packages("viridis")
library(viridis)
viridis_pal(option = "D")(n)  # n = number of colors seeked

enter image description here

enter image description here

enter image description here

There is also an excellent talk explaining the complexity of good colormaps on YouTube:

A Better Default Colormap for Matplotlib | SciPy 2015 | Nathaniel Smith and Stéfan van der Walt

How to read line by line or a whole text file at once?

I know this is a really really old thread but I'd like to also point out another way which is actually really simple... This is some sample code:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {

    ifstream file("filename.txt");
    string content;

    while(file >> content) {
        cout << content << ' ';
    }
    return 0;
}

IsNullOrEmpty with Object

object MyObject = null;

if (MyObject != null && !string.IsNullOrEmpty(MyObject.ToString())) { ... }

PLS-00428: an INTO clause is expected in this SELECT statement

In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.

The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.

DECLARE
   PROD_ROW_ID   VARCHAR (10) := NULL;
   VIS_ROW_ID    NUMBER;
   DSC           VARCHAR (512);
BEGIN
   SELECT ROW_ID
     INTO VIS_ROW_ID
     FROM SIEBEL.S_PROD_INT
    WHERE PART_NUM = 'S0146404';

   BEGIN
      SELECT    RTRIM (VIS.SERIAL_NUM)
             || ','
             || RTRIM (PLANID.DESC_TEXT)
             || ','
             || CASE
                   WHEN PLANID.HIGH = 'TEST123'
                   THEN
                      CASE
                         WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
                         THEN
                            'Y'
                         ELSE
                            'N'
                      END
                   ELSE
                      'N'
                END
             || ','
             || 'GB'
             || ','
             || RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
        INTO DSC
        FROM SIEBEL.S_LST_OF_VAL PLANID
             INNER JOIN SIEBEL.S_PROD_INT PROD
                ON PROD.PART_NUM = PLANID.VAL
             INNER JOIN SIEBEL.S_ASSET NETFLIX
                ON PROD.PROD_ID = PROD.ROW_ID
             INNER JOIN SIEBEL.S_ASSET VIS
                ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
             INNER JOIN SIEBEL.S_PROD_INT VISPROD
                ON VIS.PROD_ID = VISPROD.ROW_ID
       WHERE     PLANID.TYPE = 'Test Plan'
             AND PLANID.ACTIVE_FLG = 'Y'
             AND VISPROD.PART_NUM = VIS_ROW_ID
             AND PROD.STATUS_CD = 'Active'
             AND VIS.SERIAL_NUM IS NOT NULL;
   END;
END;
/

References

http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/

Get only part of an Array in Java?

You could wrap your array as a list, and request a sublist of it.

MyClass[] array = ...;
List<MyClass> subArray = Arrays.asList(array).subList(index, array.length);

Casting LinkedHashMap to Complex Object

I had similar Issue where we have GenericResponse object containing list of values

 ResponseEntity<ResponseDTO> responseEntity = restTemplate.exchange(
                redisMatchedDriverUrl,
                HttpMethod.POST,
                requestEntity,
                ResponseDTO.class
        );

Usage of objectMapper helped in converting LinkedHashMap into respective DTO objects

 ObjectMapper mapper = new ObjectMapper();

 List<DriverLocationDTO> driverlocationsList = mapper.convertValue(responseDTO.getData(), new TypeReference<List<DriverLocationDTO>>() { });

Split comma separated column data into additional columns

split_part() does what you want in one step:

SELECT split_part(col, ',', 1) AS col1
     , split_part(col, ',', 2) AS col2
     , split_part(col, ',', 3) AS col3
     , split_part(col, ',', 4) AS col4
FROM   tbl;

Add as many lines as you have items in col (the possible maximum). Columns exceeding data items will be empty strings ('').

Responsively change div size keeping aspect ratio

(function( $ ) {
  $.fn.keepRatio = function(which) {
      var $this = $(this);
      var w = $this.width();
      var h = $this.height();
      var ratio = w/h;
      $(window).resize(function() {
          switch(which) {
              case 'width':
                  var nh = $this.width() / ratio;
                  $this.css('height', nh + 'px');
                  break;
              case 'height':
                  var nw = $this.height() * ratio;
                  $this.css('width', nw + 'px');
                  break;
          }
      });

  }
})( jQuery );      

$(document).ready(function(){
    $('#foo').keepRatio('width');
});

Working example: http://jsfiddle.net/QtftX/1/

How to get back to most recent version in Git?

To return to the latest version:

git checkout <branch-name> 

For example, git checkout master or git checkout dev

Variable length (Dynamic) Arrays in Java

Yes: use ArrayList.

In Java, "normal" arrays are fixed-size. You have to give them a size and can't expand them or contract them. To change the size, you have to make a new array and copy the data you want - which is inefficient and a pain for you.

Fortunately, there are all kinds of built-in classes that implement common data structures, and other useful tools too. You'll want to check the Java 6 API for a full list of them.

One caveat: ArrayList can only hold objects (e.g. Integers), not primitives (e.g. ints). In MOST cases, autoboxing/autounboxing will take care of this for you silently, but you could get some weird behavior depending on what you're doing.

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

Redirect all output to file in Bash

Use >> to append:

command >> file

Update multiple rows using select statement

Run a select to make sure it is what you want

SELECT t1.value AS NEWVALUEFROMTABLE1,t2.value AS OLDVALUETABLE2,*
FROM Table2 t2
INNER JOIN Table1 t1 on t1.ID = t2.ID

Update

UPDATE Table2
SET Value = t1.Value
FROM Table2 t2
INNER JOIN Table1 t1 on t1.ID = t2.ID

Also, consider using BEGIN TRAN so you can roll it back if needed, but make sure you COMMIT it when you are satisfied.

docker command not found even though installed with apt-get

sudo apt-get install docker # DO NOT do this

is a different library on ubuntu.

Use sudo apt-get install docker-ce to install the correct docker.

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

Static variable retains it's previous value until the program exit. Static is used by calling directly class_Name.Method() or class_Name.Property. No object reference is needed. The most popular use of static is C#'s Math class. Math.Sin(), Math.Cos(), Math.Sqrt().

What does "request for member '*******' in something not a structure or union" mean?

It also happens if you're trying to access an instance when you have a pointer, and vice versa:

struct foo
{
  int x, y, z;
};

struct foo a, *b = &a;

b.x = 12;  /* This will generate the error, should be b->x or (*b).x */

As pointed out in a comment, this can be made excruciating if someone goes and typedefs a pointer, i.e. includes the * in a typedef, like so:

typedef struct foo* Foo;

Because then you get code that looks like it's dealing with instances, when in fact it's dealing with pointers:

Foo a_foo = get_a_brand_new_foo();
a_foo->field = FANTASTIC_VALUE;

Note how the above looks as if it should be written a_foo.field, but that would fail since Foo is a pointer to struct. I strongly recommend against typedef:ed pointers in C. Pointers are important, don't hide your asterisks. Let them shine.

grep regex whitespace behavior

This looks like a behavior difference in the handling of \s between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).

Note:

GNU grep 2.5.4
echo "foo bar" | grep "\s"
   (doesn't match)

whereas

GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar

Probably less trouble (as \s is not documented):

Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar

My advice is to avoid using \s ... use [ \t]* or [[:space:]] or something like it instead.

MySQL Check if username and password matches in Database

Instead of selecting all the columns in count count(*) you can limit count for one column count(UserName).

You can limit the whole search to one row by using Limit 0,1

SELECT COUNT(UserName)
  FROM TableName
 WHERE UserName = 'User' AND
       Password = 'Pass'
 LIMIT 0, 1

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

Getting byte array through input type = file

This is simple way to convert files to Base64 and avoid "maximum call stack size exceeded at FileReader.reader.onload" with the file has big size.

_x000D_
_x000D_
document.querySelector('#fileInput').addEventListener('change',   function () {_x000D_
_x000D_
    var reader = new FileReader();_x000D_
    var selectedFile = this.files[0];_x000D_
_x000D_
    reader.onload = function () {_x000D_
        var comma = this.result.indexOf(',');_x000D_
        var base64 = this.result.substr(comma + 1);_x000D_
        console.log(base64);_x000D_
    }_x000D_
    reader.readAsDataURL(selectedFile);_x000D_
}, false);
_x000D_
<input id="fileInput" type="file" />
_x000D_
_x000D_
_x000D_

javac option to compile all java files under a given directory recursively

If your shell supports it, would something like this work ?

javac com/**/*.java 

If your shell does not support **, then maybe

javac com/*/*/*.java

works (for all packages with 3 components - adapt for more or less).

Hexadecimal to Integer in Java

Try this

public static long Hextonumber(String hexval)
    {
        hexval="0x"+hexval;
//      String decimal="0x00000bb9";
        Long number = Long.decode(hexval);
//.......       System.out.println("String [" + hexval + "] = " + number);
        return number;
        //3001
    }

Multiline strings in VB.NET

I figured out how to use both <![CDATA[ along with <%= for variables, which allows you to code without worry.

You basically have to terminate the CDATA tags before the VB variable and then re-add it after so the CDATA does not capture the VB code. You need to wrap the entire code block in a tag because you will you have multiple CDATA blocks.

Dim script As String = <code><![CDATA[
  <script type="text/javascript">
    var URL = ']]><%= domain %><![CDATA[/mypage.html';
  </script>]]>
</code>.value

Paste a multi-line Java String in Eclipse

You can use this Eclipse Plugin: http://marketplace.eclipse.org/node/491839#.UIlr8ZDwCUm This is a multi-line string editor popup. Place your caret in a string literal press ctrl-shift-alt-m and paste your text.

How do I check if a given string is a legal/valid file name under Windows?

In my opinion, the only proper answer to this question is to try to use the path and let the OS and filesystem validate it. Otherwise you are just reimplementing (and probably poorly) all the validation rules that the OS and filesystem already use and if those rules are changed in the future you will have to change your code to match them.

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

To do this easily, the use of Stack is better. Create a Stack Then inside Stack add Align or Positioned and set position according to your needed, You can add multiple Container.

Container
  child: Stack(
    children: <Widget>[
      Align(
         alignment: FractionalOffset.center,
         child: Text(
            "? 1000",
         )
      ),
      Positioned(
        bottom: 0,
        child: Container(
           width: double.infinity,
           height: 30,
           child: Text(
             "Balance", ,
           )
         ),
       )
    ],
  )
)

enter image description here

Stack a widget that positions its children relative to the edges of its box.

Stack class is useful if you want to overlap several children in a simple way, for example having some text and an image, overlaid with a gradient and a button attached to the bottom.

Mac zip compress without __MACOSX folder?

Do you mean the zip command-line tool or the Finder's Compress command?

For zip, you can try the --data-fork option. If that doesn't do it, you might try --no-extra, although that seems to ignore other file metadata that might be valuable, like uid/gid and file times.

For the Finder's Compress command, I don't believe there are any options to control its behavior. It's for the simple case.

The other tool, and maybe the one that the Finder actually uses under the hood, is ditto. With the -c -k options, it creates zip archives. With this tool, you can experiment with --norsrc, --noextattr, --noqtn, --noacl and/or simply leave off the --sequesterRsrc option (which, according to the man page, may be responsible for the __MACOSX subdirectory). Although, perhaps the absence of --sequesterRsrc simply means to use AppleDouble format, which would create ._ files all over the place instead of one __MACOSX directory.

VBA Date as integer

You can use bellow code example for date string like mdate and Now() like toDay, you can also calculate deference between both date like Aging

Public Sub test(mdate As String)
    Dim toDay As String
    mdate = Round(CDbl(CDate(mdate)), 0)
    toDay = Round(CDbl(Now()), 0)
    Dim Aging as String
    Aging = toDay - mdate
    MsgBox ("So aging is -" & Aging & vbCr & "from the date - " & _
    Format(mdate, "dd-mm-yyyy")) & " to " & Format(toDay, "dd-mm-yyyy"))
End Sub

NB: Used CDate for convert Date String to Valid Date

I am using this in Office 2007 :)

How do I trim a file extension from a String in Java?

I would do like this:

String title_part = "title part1.txt";
int i;
for(i=title_part.length()-1 ; i>=0 && title_part.charAt(i)!='.' ; i--);
title_part = title_part.substring(0,i);

Starting to the end till the '.' then call substring.

Edit: Might not be a golf but it's effective :)

PostgreSQL psql terminal command

These are not command line args. Run psql. Manage to log into database (so pass the hostname, port, user and database if needed). And then write it in the psql program.

Example (below are two commands, write the first one, press enter, wait for psql to login, write the second):

psql -h host -p 5900 -U username database
\pset format aligned

Break string into list of characters in Python

fO = open(filename, 'rU')
lst = list(fO.read())

How to implement if-else statement in XSLT?

The most straight-forward approach is to do a second if-test but with the condition inverted. This technique is shorter, easier on the eyes, and easier to get right than a choose-when-otherwise nested block:

<xsl:variable name="CreatedDate" select="@createDate"/>
     <xsl:variable name="IDAppendedDate" select="2012-01-01" />
     <b>date: <xsl:value-of select="$CreatedDate"/></b> 
     <xsl:if test="$CreatedDate &gt; $IDAppendedDate">
        <h2> mooooooooooooo </h2>
     </xsl:if>
     <xsl:if test="$CreatedDate &lt;= $IDAppendedDate">
        <h2> dooooooooooooo </h2>
     </xsl:if>

Here's a real-world example of the technique being used in the style-sheet for a government website: http://w1.weather.gov/xml/current_obs/latest_ob.xsl

How to do a Jquery Callback after form submit?

I do not believe there is a callback-function like the one you describe.

What is normal here is to do the alterations using some server-side language, like PHP.

In PHP you could for instance fetch a hidden field from your form and do some changes if it is present.

PHP:

  $someHiddenVar = $_POST["hidden_field"];
    if (!empty($someHiddenVar)) {
        // do something 
    }

One way to go about it in Jquery is to use Ajax. You could listen to submit, return false to cancel its default behaviour and use jQuery.post() instead. jQuery.post has a success-callback.

$.post("test.php", $("#testform").serialize(), function(data) {
  $('.result').html(data);
});

http://api.jquery.com/jQuery.post/

How to display div after click the button in Javascript?

HTML

<div id="myDiv" style="display:none;" class="answer_list" >WELCOME</div>
<input type="button" name="answer" onclick="ShowDiv()" />

JavaScript

function ShowDiv() {
    document.getElementById("myDiv").style.display = "";
}

Or if you wanted to use jQuery with a nice little animation:

<input id="myButton" type="button" name="answer" />

$('#myButton').click(function() {
  $('#myDiv').toggle('slow', function() {
    // Animation complete.
  });
});

PHP date() format when inserting into datetime in MySQL

This is a more accurate way to do it. It places decimals behind the seconds giving more precision.

$now = date('Y-m-d\TH:i:s.uP', time());

Notice the .uP.

More info: https://stackoverflow.com/a/6153162/8662476

Global npm install location on windows?

If you're just trying to find out where npm is installing your global module (the title of this thread), look at the output when running npm install -g sample_module

$ npm install -g sample_module C:\Users\user\AppData\Roaming\npm\sample_module -> C:\Users\user\AppData\Roaming\npm\node_modules\sample_module\bin\sample_module.js + [email protected] updated 1 package in 2.821s

How to run a subprocess with Python, wait for it to exit and get the full stdout as a string?

subprocess.check_output(...)

calls the process, raises if its error code is nonzero, and otherwise returns its stdout. It's just a quick shorthand so you don't have to worry about PIPEs and things.

Insert all values of a table into another table in SQL

I think this statement might do what you want.

INSERT INTO newTableName (SELECT column1, column2, column3 FROM oldTable);

java.lang.OutOfMemoryError: GC overhead limit exceeded

@takrl: The default setting for this option is:

java -XX:+UseConcMarkSweepGC

which means, this option is not active by default. So when you say you used the option "+XX:UseConcMarkSweepGC" I assume you were using this syntax:

java -XX:+UseConcMarkSweepGC

which means you were explicitly activating this option. For the correct syntax and default settings of Java HotSpot VM Options @ this document

Get contentEditable caret index position

//global savedrange variable to store text range in
var savedrange = null;

function getSelection()
{
    var savedRange;
    if(window.getSelection && window.getSelection().rangeCount > 0) //FF,Chrome,Opera,Safari,IE9+
    {
        savedRange = window.getSelection().getRangeAt(0).cloneRange();
    }
    else if(document.selection)//IE 8 and lower
    { 
        savedRange = document.selection.createRange();
    }
    return savedRange;
}

$('#contentbox').keyup(function() { 
    var currentRange = getSelection();
    if(window.getSelection)
    {
        //do stuff with standards based object
    }
    else if(document.selection)
    { 
        //do stuff with microsoft object (ie8 and lower)
    }
});

Note: the range object its self can be stored in a variable, and can be re-selected at any time unless the contents of the contenteditable div change.

Reference for IE 8 and lower: http://msdn.microsoft.com/en-us/library/ms535872(VS.85).aspx

Reference for standards (all other) browsers: https://developer.mozilla.org/en/DOM/range (its the mozilla docs, but code works in chrome, safari, opera and ie9 too)

jQuery datepicker years shown

If you look down the demo page a bit, you'll see a "Restricting Datepicker" section. Use the dropdown to specify the "Year dropdown shows last 20 years" demo , and hit view source:

$("#restricting").datepicker({ 
    yearRange: "-20:+0", // this is the option you're looking for
    showOn: "both", 
    buttonImage: "templates/images/calendar.gif", 
    buttonImageOnly: true 
});

You'll want to do the same (obviously changing -20 to -100 or something).

Daemon Threads Explanation

Let's say you're making some kind of dashboard widget. As part of this, you want it to display the unread message count in your email box. So you make a little thread that will:

  1. Connect to the mail server and ask how many unread messages you have.
  2. Signal the GUI with the updated count.
  3. Sleep for a little while.

When your widget starts up, it would create this thread, designate it a daemon, and start it. Because it's a daemon, you don't have to think about it; when your widget exits, the thread will stop automatically.

kill a process in bash

To interrupt it, you can try pressing ctrl c to send a SIGINT. If it doesn't stop it, you may try to kill it using kill -9 <pid>, which sends a SIGKILL. The latter can't be ignored/intercepted by the process itself (the one being killed).

To move the active process to background, you can press ctrl z. The process is sent to background and you get back to the shell prompt. Use the fg command to do the opposite.

How do you get a query string on Flask?

We can do this by using request.query_string.

Example:

Lets consider view.py

from my_script import get_url_params

@app.route('/web_url/', methods=('get', 'post'))
def get_url_params_index():
    return Response(get_url_params())

You also make it more modular by using Flask Blueprints - https://flask.palletsprojects.com/en/1.1.x/blueprints/

Lets consider first name is being passed as a part of query string /web_url/?first_name=john

## here is my_script.py

## import required flask packages
from flask import request
def get_url_params():
    ## you might further need to format the URL params through escape.    
    firstName = request.args.get('first_name') 
    return firstName
    

As you see this is just a small example - you can fetch multiple values + formate those and use it or pass it onto the template file.

svn cleanup: sqlite: database disk image is malformed

If you install the Tortoise SVN, Please go to task manager and stop it. Then try to delete the folder. it will work

What do 'real', 'user' and 'sys' mean in the output of time(1)?

In very simple terms, I like to think about it like this:

  • real is the actual amount of time it took to run the command (as if you had timed it with a stopwatch)

  • user and sys are how much 'work' the CPU had to do to execute the command. This 'work' is expressed in units of time.

Generally speaking:

  • user is how much work the CPU did to run to run the command's code
  • sys is how much work the CPU had to do to handle 'system overhead' type tasks (such as allocating memory, file I/O, ect.) in order to support the running command

Since these last two times are counting 'work' done, they don't include time a thread might have spent waiting (such as waiting on another process or for disk I/O to finish).

real, however, is a measure of actual runtime and not 'work', so it does include any time spent waiting.

JavaScript - populate drop down list with array

You'll need to loop through your array elements, create a new DOM node for each and append it to your object.

var select = document.getElementById("selectNumber"); 
var options = ["1", "2", "3", "4", "5"]; 

for(var i = 0; i < options.length; i++) {
    var opt = options[i];
    var el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;
    select.appendChild(el);
}?

Live example

static linking only some libraries

to link dynamic and static library within one line, you must put static libs after dynamic libs and object files, like this:

gcc -lssl main.o -lFooLib -o main

otherwise, it will not work. it does take me sometime to figure it out.

How to remove all elements in String array in java?

list.clear() is documented for clearing the ArrayList.

list.removeAll() has no documentation at all in Eclipse.

How do I display the value of a Django form field in a template?

I wanted to display the value of a formset field. I concluded this solution, which should work for normal forms too:

{% if form.email.data %} {{ form.email.data }}
{% else %} {{ form.initial.email }} 
{% endif %}

The above solutions didn't worked very well for me, and I doubt they would work in case of prefixed forms (such as wizards and formsets). The solutions using {{ form.data.email }} can't work, because it is a dictionary lookup, and with prefixed forms your field name would look something like '1-email' (wizard and prefixed form) or 'form-1-email' (formset), and the minus sign (-) are not allowed in dotted template lookup expressions.

{{form.field_name.value}} is Django 1.3+ only.

How to append to the end of an empty list?

append actually changes the list. Also, it takes an item, not a list. Hence, all you need is

for i in range(n):
   list1.append(i)

(By the way, note that you can use range(n), in this case.)

I assume your actual use is more complicated, but you may be able to use a list comprehension, which is more pythonic for this:

list1 = [i for i in range(n)]

Or, in this case, in Python 2.x range(n) in fact creates the list that you want already, although in Python 3.x, you need list(range(n)).

How to find a text inside SQL Server procedures / triggers?

I've used these in the past:

In this particular case, where you need to replace a specific string across stored procedures, the first link is probably more relevant.

A little off-topic, the Quick Find add-in is also useful for searching object names with SQL Server Management Studio. There's a modified version available with some improvements, and another newer version also available on Codeplex with some other useful add-ins as well.

Google Maps API OVER QUERY LIMIT per second limit

Often when you need to show so many points on the map, you'd be better off using the server-side approach, this article explains when to use each:

Geocoding Strategies: https://developers.google.com/maps/articles/geocodestrat

The client-side limit is not exactly "10 requests per second", and since it's not explained in the API docs I wouldn't rely on its behavior.

GCC dump preprocessor defines

A portable approach that works equally well on Linux or Windows (where there is no /dev/null):

echo | gcc -dM -E -

For c++ you may use (replace c++11 with whatever version you use):

echo | gcc -x c++ -std=c++11 -dM -E -

It works by telling gcc to preprocess stdin (which is produced by echo) and print all preprocessor defines (search for -dletters). If you want to know what defines are added when you include a header file you can use -dD option which is similar to -dM but does not include predefined macros:

echo "#include <stdlib.h>" | gcc -x c++ -std=c++11 -dD -E -

Note, however, that empty input still produces lots of defines with -dD option.

Check if an element is present in an array

ECMAScript 2016 incorporates an includes() method for arrays that specifically solves the problem, and so is now the preferred method.

[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(1, 2);  // false (second parameter is the index position in this array at which to begin searching)

As of JULY 2018, this has been implemented in almost all major browsers, if you need to support an older browser a polyfill is available.

Edit: Note that this returns false if the item in the array is an object. This is because similar objects are two different objects in JavaScript.

Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

You can set environment variables in the notebook using os.environ. Do the following before initializing TensorFlow to limit TensorFlow to first GPU.

import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"   # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"]="0"

You can double check that you have the correct devices visible to TF

from tensorflow.python.client import device_lib
print device_lib.list_local_devices()

I tend to use it from utility module like notebook_util

import notebook_util
notebook_util.pick_gpu_lowest_memory()
import tensorflow as tf

"Python version 2.7 required, which was not found in the registry" error when attempting to install netCDF4 on Windows 8

I had the same issue when using an .exe to install a Python package (because I use Anaconda and it didn't add Python to the registry). I fixed the problem by running this script:

#
# script to register Python 2.0 or later for use with 
# Python extensions that require Python registry settings
#
# written by Joakim Loew for Secret Labs AB / PythonWare
#
# source:
# http://www.pythonware.com/products/works/articles/regpy20.htm
#
# modified by Valentine Gogichashvili as described in http://www.mail-archive.com/[email protected]/msg10512.html

import sys

from _winreg import *

# tweak as necessary
version = sys.version[:3]
installpath = sys.prefix

regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)
installkey = "InstallPath"
pythonkey = "PythonPath"
pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (
    installpath, installpath, installpath
)

def RegisterPy():
    try:
        reg = OpenKey(HKEY_CURRENT_USER, regpath)
    except EnvironmentError as e:
        try:
            reg = CreateKey(HKEY_CURRENT_USER, regpath)
            SetValue(reg, installkey, REG_SZ, installpath)
            SetValue(reg, pythonkey, REG_SZ, pythonpath)
            CloseKey(reg)
        except:
            print "*** Unable to register!"
            return
        print "--- Python", version, "is now registered!"
        return
    if (QueryValue(reg, installkey) == installpath and
        QueryValue(reg, pythonkey) == pythonpath):
        CloseKey(reg)
        print "=== Python", version, "is already registered!"
        return
    CloseKey(reg)
    print "*** Unable to register!"
    print "*** You probably have another Python installation!"

if __name__ == "__main__":
    RegisterPy()

How to write to a JSON file in the correct format

This question is for ruby 1.8 but it still comes on top when googling.

in ruby >= 1.9 you can use

File.write("public/temp.json",tempHash.to_json)

other than what mentioned in other answers, in ruby 1.8 you can also use one liner form

File.open("public/temp.json","w"){ |f| f.write tempHash.to_json }

How can I upgrade NumPy?

All the same.

   sudo easy_install numpy

My Traceback

Searching for numpy

Best match: numpy 1.13.0

Adding numpy 1.13.0 to easy-install.pth file

Using /Library/Python/2.7/site-packages

Processing dependencies for numpy

LaTeX table too wide. How to make it fit?

You have to take whole columns under resizebox. This code worked for me

\begin{table}[htbp]
\caption{Sample Table.}\label{tab1}
\resizebox{\columnwidth}{!}{\begin{tabular}{|l|l|l|l|l|}
\hline
URL &  First Time Visit & Last Time Visit & URL Counts & Value\\
\hline
https://web.facebook.com/ & 1521241972 & 1522351859 & 177 & 56640\\
http://localhost/phpmyadmin/ & 1518413861 & 1522075694 & 24 & 39312\\
https://mail.google.com/mail/u/ & 1516596003 & 1522352010 & 36 & 33264\\
https://github.com/shawon100& 1517215489 & 1522352266 & 37 & 27528\\
https://www.youtube.com/ & 1517229227 & 1521978502 & 24 & 14792\\
\hline
\end{tabular}}
\end{table}

Do I use <img>, <object>, or <embed> for SVG files?

I recommend using the combination of

<svg viewBox="" width="" height="">
<path fill="#xxxxxx" d="M203.3,71.6c-.........."></path>
</svg>

Initializing default values in a struct

Yes. bar.a and bar.b are set to true, but bar.c is undefined. However, certain compilers will set it to false.

See a live example here: struct demo

According to C++ standard Section 8.5.12:

if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value

For primitive built-in data types (bool, char, wchar_t, short, int, long, float, double, long double), only global variables (all static storage variables) get default value of zero if they are not explicitly initialized.

If you don't really want undefined bar.c to start with, you should also initialize it like you did for bar.a and bar.b.

iTunes Connect Screenshots Sizes for all iOS (iPhone/iPad/Apple Watch) devices

To get screenshots of the proper size without having to create them manually -- run your app in the latest version of Xcode and choose the iPhone you need screenshots for, then hit cmd-s while viewing the simulator. This will save a screenshot to your desktop in the full resolution that you need for submission.

As noted below by @HoffZ, be sure that the scale is set to 100%.

In Xcode select simulator you want:

Xcode simulators

In the Simulator menu set the scale to 100%:

Set Scale to 100%

Press cmd-s to save:

Save Screenshot

How to insert a picture into Excel at a specified cell position with VBA

Looking at posted answers I think this code would be also an alternative for someone. Nobody above used .Shapes.AddPicture in their code, only .Pictures.Insert()

Dim myPic As Object
Dim picpath As String

picpath = "C:\Users\photo.jpg" 'example photo path

Set myPic = ws.Shapes.AddPicture(picpath, False, True, 20, 20, -1, -1)

With myPic
    .Width = 25
    .Height = 25
    .Top = xlApp.Cells(i, 20).Top 'according to variables from correct answer
    .Left = xlApp.Cells(i, 20).Left
    .LockAspectRatio = msoFalse
End With

I'm working in Excel 2013. Also realized that You need to fill all the parameters in .AddPicture, because of error "Argument not optional". Looking at this You may ask why I set Height and Width as -1, but that doesn't matter cause of those parameters are set underneath between With brackets.

Hope it may be also useful for someone :)

Best way to get application folder path

If you know to get the root directory:

string rootPath = Path.GetPathRoot(Application.StartupPath)

How to insert a new line in Linux shell script?

echo $'Create the snapshots\nSnapshot created\n'

Division in Python 2.7. and 3.3

In Python 2.x, make sure to have at least one operand of your division in float. Multiple ways you may achieve this as the following examples:

20. / 15
20 / float(15)

R : how to simply repeat a command?

You could use replicate or sapply:

R> colMeans(replicate(10000, sample(100, size=815, replace=TRUE, prob=NULL))) R> sapply(seq_len(10000), function(...) mean(sample(100, size=815, replace=TRUE, prob=NULL))) 

replicate is a wrapper for the common use of sapply for repeated evaluation of an expression (which will usually involve random number generation).

CSS Progress Circle

What about that?

HTML

<div class="chart" id="graph" data-percent="88"></div>

Javascript

var el = document.getElementById('graph'); // get canvas

var options = {
    percent:  el.getAttribute('data-percent') || 25,
    size: el.getAttribute('data-size') || 220,
    lineWidth: el.getAttribute('data-line') || 15,
    rotate: el.getAttribute('data-rotate') || 0
}

var canvas = document.createElement('canvas');
var span = document.createElement('span');
span.textContent = options.percent + '%';

if (typeof(G_vmlCanvasManager) !== 'undefined') {
    G_vmlCanvasManager.initElement(canvas);
}

var ctx = canvas.getContext('2d');
canvas.width = canvas.height = options.size;

el.appendChild(span);
el.appendChild(canvas);

ctx.translate(options.size / 2, options.size / 2); // change center
ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI); // rotate -90 deg

//imd = ctx.getImageData(0, 0, 240, 240);
var radius = (options.size - options.lineWidth) / 2;

var drawCircle = function(color, lineWidth, percent) {
        percent = Math.min(Math.max(0, percent || 1), 1);
        ctx.beginPath();
        ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, false);
        ctx.strokeStyle = color;
        ctx.lineCap = 'round'; // butt, round or square
        ctx.lineWidth = lineWidth
        ctx.stroke();
};

drawCircle('#efefef', options.lineWidth, 100 / 100);
drawCircle('#555555', options.lineWidth, options.percent / 100);

and CSS

div {
    position:relative;
    margin:80px;
    width:220px; height:220px;
}
canvas {
    display: block;
    position:absolute;
    top:0;
    left:0;
}
span {
    color:#555;
    display:block;
    line-height:220px;
    text-align:center;
    width:220px;
    font-family:sans-serif;
    font-size:40px;
    font-weight:100;
    margin-left:5px;
}

http://jsfiddle.net/Aapn8/3410/

Basic code was taken from Simple PIE Chart http://rendro.github.io/easy-pie-chart/

How can I add new item to the String array?

String a []=new String[1];

  a[0].add("kk" );
  a[1].add("pp");

Try this one...

Inserting an image with PHP and FPDF

Please note that you should not use any png when you are testing this , first work with jpg .

$myImage = "images/logos/mylogo.jpg";  // this is where you get your Image

$pdf->Image($myImage, 5, $pdf->GetY(), 33.78);

Find if value in column A contains value from column B?

You could try this

=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),FALSE, TRUE)

-or-

=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),"FALSE", "File found in row "   & MATCH(<single column I value>,<entire column E range>,0))

you could replace <single column I value> and <entire column E range> with named ranged. That'd probably be the easiest.

Just drag that formula all the way down the length of your I column in whatever column you want.

MySQL: Quick breakdown of the types of joins

Full Outer join don't exist in mysql , you might need to use a combination of left and right join.

How to write a simple Html.DropDownListFor()?

Avoid of lot of fat fingering by starting with a Dictionary in the Model

namespace EzPL8.Models
{
    public class MyEggs
    {
        public Dictionary<int, string> Egg { get; set; }

        public MyEggs()
        {
            Egg = new Dictionary<int, string>()
            {
                { 0, "No Preference"},
                { 1, "I hate eggs"},
                { 2, "Over Easy"},
                { 3, "Sunny Side Up"},
                { 4, "Scrambled"},
                { 5, "Hard Boiled"},
                { 6, "Eggs Benedict"}
            };

    }


    }

In the View convert it to a list for display

@Html.DropDownListFor(m => m.Egg.Keys,
                         new SelectList(
                             Model.Egg, 
                             "Key", 
                             "Value"))

How to deal with missing src/test/java source folder in Android/Maven project?

Select project -> New -> Folder (not source folder) -> Select the project again -> Enter the folder name as (src/test/java) -> finish. That's it.

If the test source is missing, it would link it automatically. If not, then require to link it manually.

XPath to get all child nodes (elements, comments, and text) without parent

From the documentation of XPath ( http://www.w3.org/TR/xpath/#location-paths ):

child::* selects all element children of the context node

child::text() selects all text node children of the context node

child::node() selects all the children of the context node, whatever their node type

So I guess your answer is:

$doc/PRESENTEDIN/X/child::node()

And if you want a flatten array of all nested nodes:

$doc/PRESENTEDIN/X/descendant::node()

ERROR 2013 (HY000): Lost connection to MySQL server at 'reading authorization packet', system error: 0

From documentation:

More rarely, it can happen when the client is attempting the initial connection to the server. In this case, if your connect_timeout value is set to only a few seconds, you may be able to resolve the problem by increasing it to ten seconds, perhaps more if you have a very long distance or slow connection. You can determine whether you are experiencing this more uncommon cause by using SHOW STATUS LIKE 'aborted_connections'. It will increase by one for each initial connection attempt that the server aborts. You may see “reading authorization packet” as part of the error message; if so, that also suggests that this is the solution that you need.

Try increasing connect_timeout in your my.cnf file

Another style:

MySQL: Lost connection to MySQL server at 'reading initial communication packet'

  1. At some point, it was impossible for remote clients to connect to the MySQL server.

  2. The client (some application on a Windows platform) gave a vague description like Connection unexpectedly terminated.

  3. When remotely logging in with the MySQL client the following error appeared:

    ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 0

On FreeBSD this happens because there was no match found in /etc/hosts.allow. Adding the following line before the line saying ALL:ALL fixes this:

mysqld: ALL: allow

On non-FreeBSD Unix systems, it is worth to check the files /etc/hosts.allow and /etc/hosts.deny. If you are restricting connections, make sure this line is in /etc/hosts.allow:

mysqld: ALL

or check if the host is listed in /etc/hosts.deny.

In Arch Linux, a similar line can be added to /etc/hosts.allow:

mysqld: ALL

Querying data by joining two tables in two database on different servers

If a linked server is not allowed by your dba, you can use OPENROWSET. Books Online will provide the syntax you need.

Iterating through populated rows

I'm going to make a couple of assumptions in my answer. I'm assuming your data starts in A1 and there are no empty cells in the first column of each row that has data.

This code will:

  1. Find the last row in column A that has data
  2. Loop through each row
  3. Find the last column in current row with data
  4. Loop through each cell in current row up to last column found.

This is not a fast method but will iterate through each one individually as you suggested is your intention.


Sub iterateThroughAll()
    ScreenUpdating = False
    Dim wks As Worksheet
    Set wks = ActiveSheet

    Dim rowRange As Range
    Dim colRange As Range

    Dim LastCol As Long
    Dim LastRow As Long
    LastRow = wks.Cells(wks.Rows.Count, "A").End(xlUp).Row

    Set rowRange = wks.Range("A1:A" & LastRow)

    'Loop through each row
    For Each rrow In rowRange
        'Find Last column in current row
        LastCol = wks.Cells(rrow, wks.Columns.Count).End(xlToLeft).Column
        Set colRange = wks.Range(wks.Cells(rrow, 1), wks.Cells(rrow, LastCol))

        'Loop through all cells in row up to last col
        For Each cell In colRange
            'Do something to each cell
            Debug.Print (cell.Value)
        Next cell
    Next rrow
    ScreenUpdating = True
End Sub

What are all possible pos tags of NLTK?

The book has a note how to find help on tag sets, e.g.:

nltk.help.upenn_tagset()

Others are probably similar. (Note: Maybe you first have to download tagsets from the download helper's Models section for this)

Responsive iframe using Bootstrap

The best solution that worked great for me.

You have to: Copy this code to your main CSS file,

.responsive-video {
    position: relative;
    padding-bottom: 56.25%;
    padding-top: 60px; overflow: hidden;
}

.responsive-video iframe,
.responsive-video object,
.responsive-video embed {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

and then put your embeded video to

<div class="responsive-video">
    <iframe ></iframe>
</div>

That’s it! Now you can use responsive videos on your site.

Escape sequence \f - form feed - what exactly is it?

It skips to the start of the next page. (Applies mostly to terminals where the output device is a printer rather than a VDU.)

Understanding Python super() with __init__() methods

Just a heads up... with Python 2.7, and I believe ever since super() was introduced in version 2.2, you can only call super() if one of the parents inherit from a class that eventually inherits object (new-style classes).

Personally, as for python 2.7 code, I'm going to continue using BaseClassName.__init__(self, args) until I actually get the advantage of using super().

How to decide when to use Node.js?

I can share few points where&why to use node js.

  1. For realtime applications like chat,collaborative editing better we go with nodejs as it is event base where fire event and data to clients from server.
  2. Simple and easy to understand as it is javascript base where most of people have idea.
  3. Most of current web applications going towards angular js&backbone, with node it is easy to interact with client side code as both will use json data.
  4. Lot of plugins available.

Drawbacks:-

  1. Node will support most of databases but best is mongodb which won't support complex joins and others.
  2. Compilation Errors...developer should handle each and every exceptions other wise if any error accord application will stop working where again we need to go and start it manually or using any automation tool.

Conclusion:- Nodejs best to use for simple and real time applications..if you have very big business logic and complex functionality better should not use nodejs. If you want to build an application along with chat and any collaborative functionality.. node can be used in specific parts and remain should go with your convenience technology.

Simulate a specific CURL in PostMan

sometimes whenever you copy cURL, it contains --compressed. Remove it while import->Paste Raw Text-->click on import. It will also solve the problem if you are getting the syntax error in postman while importing any cURL.

Generally, when people copy cURL from any proxy tools like Charles, it happens.

How to do a JUnit assert on a message in a logger

Effectively you are testing a side-effect of a dependent class. For unit testing you need only to verify that

logger.info()

was called with the correct parameter. Hence use a mocking framework to emulate logger and that will allow you to test your own class's behaviour.

Using Server.MapPath() inside a static field in ASP.NET MVC

I think you can try this for calling in from a class

 System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");

*----------------Sorry I oversight, for static function already answered the question by adrift*

System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Update

I got exception while using System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Ex details : System.ArgumentException: The relative virtual path 'SignatureImages' is not allowed here. at System.Web.VirtualPath.FailIfRelativePath()

Solution (tested in static webmethod)

System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/"); Worked

Which variable size to use (db, dw, dd) with x86 assembly?

Quick review,

  • DB - Define Byte. 8 bits
  • DW - Define Word. Generally 2 bytes on a typical x86 32-bit system
  • DD - Define double word. Generally 4 bytes on a typical x86 32-bit system

From x86 assembly tutorial,

The pop instruction removes the 4-byte data element from the top of the hardware-supported stack into the specified operand (i.e. register or memory location). It first moves the 4 bytes located at memory location [SP] into the specified register or memory location, and then increments SP by 4.

Your num is 1 byte. Try declaring it with DD so that it becomes 4 bytes and matches with pop semantics.

Extract a subset of a dataframe based on a condition involving a field

Here are the two main approaches. I prefer this one for its readability:

bar <- subset(foo, location == "there")

Note that you can string together many conditionals with & and | to create complex subsets.

The second is the indexing approach. You can index rows in R with either numeric, or boolean slices. foo$location == "there" returns a vector of T and F values that is the same length as the rows of foo. You can do this to return only rows where the condition returns true.

foo[foo$location == "there", ]

clear javascript console in Google Chrome

Press CTRL+L Shortcut to clear log, even if you have ticked Preserve log option.
Hope this helps.

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

Also you need to check if individual record is not getting updated in the logic because with update trigger in the place causes time out error too.

So, the solution is to make sure you perform bulk update after the loop/cursor instead of one record at a time in the loop.

FileNotFoundException while getting the InputStream object from HttpURLConnection

FileNotFound in this case means you got a 404 from your server - could it be that the server does not like "POST" requests?

Session 'app' error while installing APK

Trying cleaning AND rebuilding your project: In Android Studio, open up the Build tab at the top left and try both the Clean and Rebuild options.

switch() statement usage

In short, yes. But there are times when you might favor one vs. the other. Google "case switch vs. if else". There are some discussions already on SO too. Also, here is a good video that talks about it in the context of MATLAB:

http://blogs.mathworks.com/pick/2008/01/02/matlab-basics-switch-case-vs-if-elseif/

Personally, when I have 3 or more cases, I usually just go with case/switch.

What are "res" and "req" parameters in Express functions?

Request and response.

To understand the req, try out console.log(req);.

Setting query string using Fetch GET request

A concise ES6 approach:

fetch('https://example.com?' + new URLSearchParams({
    foo: 'value',
    bar: 2,
}))

URLSearchParams's toString() function will convert the query args into a string that can be appended onto the URL. In this example, toString() is called implicitly when it gets concatenated with the URL. You will likely want to call toString() explicitly to improve readability.

IE does not support URLSearchParams (or fetch), but there are polyfills available.

If using node, you can add the fetch API through a package like node-fetch. URLSearchParams comes with node, and can be found as a global object since version 10. In older version you can find it at require('url').URLSearchParams.

Console.log(); How to & Debugging javascript

Learn to use a javascript debugger. Venkman (for Firefox) or the Web Inspector (part of Chome & Safari) are excellent tools for debugging what's going on.

You can set breakpoints and interrogate the state of the machine as you're interacting with your script; step through parts of your code to make sure everything is working as planned, etc.

Here is an excellent write up from WebMonkey on JavaScript Debugging for Beginners. It's a great place to start.

PHP PDO with foreach and fetch

$users = $dbh->query($sql);
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

Here $users is a PDOStatement object over which you can iterate. The first iteration outputs all results, the second does nothing since you can only iterate over the result once. That's because the data is being streamed from the database and iterating over the result with foreach is essentially shorthand for:

while ($row = $users->fetch()) ...

Once you've completed that loop, you need to reset the cursor on the database side before you can loop over it again.

$users = $dbh->query($sql);
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
$result = $users->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
    echo $key . "-" . $value . "<br/>";
}

Here all results are being output by the first loop. The call to fetch will return false, since you have already exhausted the result set (see above), so you get an error trying to loop over false.

In the last example you are simply fetching the first result row and are looping over it.

How do I force a DIV block to extend to the bottom of a page even if it has no content?

you can kinda hack it with the min-height declaration

<div style="min-height: 100%">stuff</div>

Auto reloading python Flask app upon code changes

Flask applications can optionally be executed in debug mode. In this mode, two very convenient modules of the development server called the reloader and the debugger are enabled by default. When the reloader is enabled, Flask watches all the source code files of your project and automatically restarts the server when any of the files are modified.

By default, debug mode is disabled. To enable it, set a FLASK_DEBUG=1 environment variable before invoking flask run:

(venv) $ export FLASK_APP=hello.py for Windows use > set FLASK_APP=hello.py

(venv) $ export FLASK_DEBUG=1 for Windows use > set FLASK_DEBUG=1

(venv) $ flask run

* Serving Flask app "hello"
* Forcing debug mode on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 273-181-528

Having a server running with the reloader enabled is extremely useful during development, because every time you modify and save a source file, the server automatically restarts and picks up the change.

How to delete stuff printed to console by System.out.println()?

Clearing screen in Java is not supported, but you can try some hacks to achieve this.

a) Use OS-depends command, like this for Windows:

Runtime.getRuntime().exec("cls");

b) Put bunch of new lines (this makes ilusion that screen is clear)

c) If you ever want to turn off System.out, you can try this:

System.setOut(new PrintStream(new OutputStream() {
    @Override public void write(int b) throws IOException {}
}));

How to print multiple variable lines in Java

Suppose we have variable date , month and year then we can write it in the java like this.

int date=15,month=4,year=2016;
System.out.println(date+ "/"+month+"/"+year);

output of this will be like below:

15/4/2016

Is there a destructor for Java?

Nope, no destructors here. The reason is that all Java objects are heap allocated and garbage collected. Without explicit deallocation (i.e. C++'s delete operator) there is no sensible way to implement real destructors.

Java does support finalizers, but they are meant to be used only as a safeguard for objects holding a handle to native resources like sockets, file handles, window handles, etc. When the garbage collector collects an object without a finalizer it simply marks the memory region as free and that's it. When the object has a finalizer, it's first copied into a temporary location (remember, we're garbage collecting here), then it's enqueued into a waiting-to-be-finalized queue and then a Finalizer thread polls the queue with very low priority and runs the finalizer.

When the application exits, the JVM stops without waiting for the pending objects to be finalized, so there practically no guarantees that your finalizers will ever run.

How to access static resources when mapping a global front controller servlet on /*

Add the folders which you don't want to trigger servlet processing to the <static-files> section of your appengine-web.xml file.

I just did this and looks like things are starting to work ok. Here's my structure:

/

/pages/<.jsp files>

/css

I added "/pages/**" and "/css/**" to the <static-files> section and I can now forward to a .jsp file from inside a servlet doGet without causing an infinite loop.

Get the value of bootstrap Datetimepicker in JavaScript

It seems the doc evolved.

One should now use : $("#datetimepicker1").data("DateTimePicker").date().

NB : Doing so return a Moment object, not a Date object

System.Net.WebException HTTP status code

this works only if WebResponse is a HttpWebResponse.

try
{
    ...
}
catch (System.Net.WebException exc)
{
    var webResponse = exc.Response as System.Net.HttpWebResponse;
    if (webResponse != null && 
        webResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
    {
        MessageBox.Show("401");
    }
    else
        throw;
}

Bootstrap modal: close current, open new

I had the same issue as @Gravity Grave whereby scrolling doesn't work if you use

data-toggle="modal" data-target="TARGET-2" 

in conjunction with

data-dismiss="modal"

The scroll doesn't work correctly and reverts to scrolling the page rather than the modal. This is due to data-dismiss removing the modal-open class from the tag.

My solution in the end was to set the html of the inner component on the modal and use css to fade the text in/out.

TypeError: string indices must be integers, not str // working with dict

I see that you are looking for an implementation of the problem more than solving that error. Here you have a possible solution:

from itertools import chain

def involved(courses, person):
    courses_info = chain.from_iterable(x.values() for x in courses.values())
    return filter(lambda x: x['teacher'] == person, courses_info)

print involved(courses, 'Dave')

The first thing I do is getting the list of the courses and then filter by teacher's name.

How to represent empty char in Java Character class

An empty String is a wrapper on a char[] with no elements. You can have an empty char[]. But you cannot have an "empty" char. Like other primitives, a char has to have a value.

You say you want to "replace a character without leaving a space".

If you are dealing with a char[], then you would create a new char[] with that element removed.

If you are dealing with a String, then you would create a new String (String is immutable) with the character removed.

Here are some samples of how you could remove a char:

public static void main(String[] args) throws Exception {

    String s = "abcdefg";
    int index = s.indexOf('d');

    // delete a char from a char[]
    char[] array = s.toCharArray();
    char[] tmp = new char[array.length-1];
    System.arraycopy(array, 0, tmp, 0, index);
    System.arraycopy(array, index+1, tmp, index, tmp.length-index);
    System.err.println(new String(tmp));

    // delete a char from a String using replace
    String s1 = s.replace("d", "");
    System.err.println(s1);

    // delete a char from a String using StringBuilder
    StringBuilder sb = new StringBuilder(s);
    sb.deleteCharAt(index);
    s1 = sb.toString();
    System.err.println(s1);

}

How do I embed a mp4 movie into my html?

If you have an mp4 video residing at your server, and you want the visitors to stream that over your HTML page.

<video width="480" height="320" controls="controls">
<source src="http://serverIP_or_domain/location_of_video.mp4" type="video/mp4">
</video>

Android: I lost my android key store, what should I do?

No, there is no chance to do that. You just learned how important a backup can be.

Facebook Graph API : get larger pictures in one request

In pictures URL found in the Graph responses (the "http://photos-c.ak.fbcdn.net/" ones), just replace the default "_s.jpg" by "_n.jpg" (? normal size) or "_b.jpg" (? big size) or "_t.jpg" (thumbnail).

Hacakable URLs/REST API make the Web better.

How to add minutes to current time in swift

Two approaches:

  1. Use Calendar and date(byAdding:to:wrappingComponents:). E.g., in Swift 3 and later:

    let calendar = Calendar.current
    let date = calendar.date(byAdding: .minute, value: 5, to: startDate)
    
  2. Just use + operator (see +(_:_:)) to add a TimeInterval (i.e. a certain number of seconds). E.g. to add five minutes, you can:

    let date = startDate + 5 * 60
    

    (Note, the order is specific here: The date on the left side of the + and the seconds on the right side.)

    You can also use addingTimeInterval, if you’d prefer:

    let date = startDate.addingTimeInterval(5 * 60)
    

Bottom line, +/addingTimeInterval is easiest for simple scenarios, but if you ever want to add larger units (e.g., days, months, etc.), you would likely want to use the calendrical calculations because those adjust for daylight savings, whereas addingTimeInterval doesn’t.


For Swift 2 renditions, see the previous revision of this answer.

What does "for" attribute do in HTML <label> tag?

The for attribute shows that this label stands for related input field, or check box or radio button or any other data entering field associated with it. for example

<li>
    <label>{translate:blindcopy}</label>
    <a class="" href="#" title="{translate:savetemplate}" onclick="" ><i class="fa fa-list" class="button" ></i></a> &nbsp 
            <input type="text" id="BlindCopy" name="BlindCopy" class="splitblindcopy" />

</li>

How to Git stash pop specific stash in 1.8.3?

On Windows Powershell I run this:

git stash apply "stash@{1}"

Create sequence of repeated values, in sequence?

You missed the each= argument to rep():

R> n <- 3
R> rep(1:5, each=n)
 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
R> 

so your example can be done with a simple

R> rep(1:8, each=20)

How to select all records from one table that do not exist in another table?

Watch out for pitfalls. If the field Name in Table1 contain Nulls you are in for surprises. Better is:

SELECT name
FROM table2
WHERE name NOT IN
    (SELECT ISNULL(name ,'')
     FROM table1)

PHP Function Comments

You can get the comments of a particular method by using the ReflectionMethod class and calling ->getDocComment().

http://www.php.net/manual/en/reflectionclass.getdoccomment.php

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

You can also "fix" this by replacing the image with its inline Base64 representation:

img.src= "data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==";
Useful, when you do not intend to publish the page on the web, but instead use it on local machines only.

How can I repeat a character in Bash?

Here's what I use to print a line of characters across the screen in linux (based on terminal/screen width)

Print "=" across the screen:

printf '=%.0s' $(seq 1 $(tput cols))

Explanation:

Print an equal sign as many times as the given sequence:

printf '=%.0s' #sequence

Use the output of a command (this is a bash feature called Command Substitution):

$(example_command)

Give a sequence, I've used 1 to 20 as an example. In the final command the tput command is used instead of 20:

seq 1 20

Give the number of columns currently used in the terminal:

tput cols

What is the difference between T(n) and O(n)?

Theta is a shorthand way of referring to a special situtation where the big O and Omega are the same.

Thus, if one claims The Theta is expression q, then they are also necessarily claiming that Big O is expression q and Omega is expression q.


Rough analogy:

If: Theta claims, "That animal has 5 legs." then it follows that: Big O is true ("That animal has less than or equal to 5 legs.") and Omega is true("That animal has more than or equal to 5 legs.")

It's only a rough analogy because the expressions aren't necessarily specific numbers, but instead functions of varying orders of magnitude such as log(n), n, n^2, (etc.).

How to add a browser tab icon (favicon) for a website?

For Chrome to display the page icon (favicon), you need to check your website from a hosting server or you can use local host while developing and testing your website on your PC.

Installing Apple's Network Link Conditioner Tool

For Xcode 8 you gotta download a package named Additional Tools for Xcode 8

For other versions (8.1, 8.2) get the package here

Double click and open the dmg and go to Hardware directory. Double click on Network Link Conditioner.prefPane.

enter image description here

Click on install

enter image description here

Now Network Link Conditioner will be available in System Preferences.

For versions older than Xcode 8, the package to be downloaded is called Hardware IO Tools for Xcode. Get it from this page

How do you migrate an IIS 7 site to another server?

Microsoft Web Deploy v3 can export and import all your files, the configuration settings, etc. It puts it all into a zip archive ready to import on the new server. It can even upgrade to newer versions of IIS (v7-v8).

http://www.iis.net/extensions/WebDeploymentTool

After installing the tool: Right click your server or website in IIS Management Console, select 'Deploy', 'Export Application...' and run through the export.

On the new server, import the exported zip archive in the same way.

VBA copy cells value and format

This page from Microsoft's Excel VBA documentation helped me: https://docs.microsoft.com/en-us/office/vba/api/excel.xlpastetype

It gives a bunch of options to customize how you paste. For instance, you could xlPasteAll (probably what you're looking for), or xlPasteAllUsingSourceTheme, or even xlPasteAllExceptBorders.

How to grant permission to users for a directory using command line in Windows?

With an Excel vba script to provision and create accounts. I was needing to grant full rights permissions to the folder and subfolders that were created by the tool using our administrators 'x' account to our new user.

cacls looked something like this: cacls \FileServer\Users\Username /e /g Domain\Username:C

I needed to migrate this code to Windows 7 and beyond. My solution turned out to be:

icacls \FileServer\Users\Username /grant:r Domain\Username:(OI)(CI)F /t

/grant:r - Grants specified user access rights. Permissions replace previously granted explicit permissions. Without :r, permissions are added to any previously granted explicit permissions

(OI)(CI) - This folder, subfolders, and files.

F - Full Access

/t - Traverse all subfolders to match files/directories.

What this gave me was a folder on this server that the user could only see that folder and created subfolders, that they could read and write files. As well as create new folders.

How to avoid Number Format Exception in java?

I suggest to do 2 things:

  • validate the input on client side before passing it to the Servlet
  • catch the exception and show an error message within the user frontend as Tobiask mentioned. This case should normally not happen, but never trust your clients. ;-)

Centering a Twitter Bootstrap button

If you have more than one button, then you can do the following.

<div class="center-block" style="max-width:400px">
  <a href="#" class="btn btn-success">Accept</a>
  <a href="#" class="btn btn-danger"> Reject</a>
</div>

Why is using the JavaScript eval function a bad idea?

I would go as far as to say that it doesn't really matter if you use eval() in javascript which is run in browsers.*(caveat)

All modern browsers have a developer console where you can execute arbitrary javascript anyway and any semi-smart developer can look at your JS source and put whatever bits of it they need to into the dev console to do what they wish.

*As long as your server endpoints have the correct validation & sanitisation of user supplied values, it should not matter what gets parsed and eval'd in your client side javascript.

If you were to ask if it's suitable to use eval() in PHP however, the answer is NO, unless you whitelist any values which may be passed to your eval statement.

FAIL - Application at context path /Hello could not be started

You need to close the XML with </web-app>, not with <web-app>.

How to use a BackgroundWorker?

I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;  //Tell the user how the process went
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}

//Start Process
private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
    //Check if background worker is doing anything and send a cancellation if it is
    if (backgroundWorker1.IsBusy)
    {
        backgroundWorker1.CancelAsync();
    }

}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);

        //Check if there is a request to cancel the process
        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            backgroundWorker1.ReportProgress(0);
            return;
        }
    }
    //If the process exits the loop, ensure that progress is set to 100%
    //Remember in the loop we set i < 100 so in theory the process will complete at 99%
    backgroundWorker1.ReportProgress(100);
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
         lblStatus.Text = "Process was cancelled";
    }
    else if (e.Error != null)
    {
         lblStatus.Text = "There was an error running the process. The thread aborted";
    }
    else
    {
       lblStatus.Text = "Process was completed";
    }
}

What is the difference between static_cast<> and C style casting?

In short:

  1. static_cast<>() gives you a compile time checking ability, C-Style cast doesn't.
  2. static_cast<>() is more readable and can be spotted easily anywhere inside a C++ source code, C_Style cast is'nt.
  3. Intentions are conveyed much better using C++ casts.

More Explanation:

The static cast performs conversions between compatible types. It is similar to the C-style cast, but is more restrictive. For example, the C-style cast would allow an integer pointer to point to a char.

char c = 10;       // 1 byte
int *p = (int*)&c; // 4 bytes

Since this results in a 4-byte pointer ( a pointer to 4-byte datatype) pointing to 1 byte of allocated memory, writing to this pointer will either cause a run-time error or will overwrite some adjacent memory.

*p = 5; // run-time error: stack corruption

In contrast to the C-style cast, the static cast will allow the compiler to check that the pointer and pointee data types are compatible, which allows the programmer to catch this incorrect pointer assignment during compilation.

int *q = static_cast<int*>(&c); // compile-time error

You can also check this page on more explanation on C++ casts : Click Here

What is a "cache-friendly" code?

Be aware that caches do not just cache continuous memory. They have multiple lines (at least 4) so discontinous and overlapping memory can often be stored just as efficiently.

What is missing from all the above examples is measured benchmarks. There are many myths about performance. Unless you measure it you do not know. Do not complicate your code unless you have a measured improvement.

How can I convert a Timestamp into either Date or DateTime object?

java.sql.Timestamp is a subclass of java.util.Date. So, just upcast it.

Date dtStart = resultSet.getTimestamp("dtStart");
Date dtEnd = resultSet.getTimestamp("dtEnd");

Using SimpleDateFormat and creating Joda DateTime should be straightforward from this point on.

Sending emails through SMTP with PHPMailer

I had very similar problem for something like an hour, until I figured out what went wrong. My problem was, that I used SSL, instead of ssl. Check is case sensitive in the code. AlexV guided me to the source of the problem. That helo/ehlo -stuff seems irrelevant.

Mysql where id is in array

Your query translates to:

SELECT name FROM users WHERE id IN ('Array');

Or something to that affect.

Try using prepared queries instead, something like:

$numbers = explode(',', $string);
$prepare = array_map(function(){ return '?'; }, $numbers);
$statement = mysqli_prepare($link , "SELECT name FROM users WHERE id IN ('".implode(',', $prepare)."')");
if($statement) {
   $ints = array_map(function(){ return 'i'; }, $numbers);
   call_user_func_array("mysqli_stmt_bind_param", array_merge(
      array($statement, implode('', $ints)), $numbers
   ));
   $results = mysqli_stmt_execute($statement);
   // do something with results 
   // ...
}

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

The accepted answer is correct regarding the Invoke-Command cmdlet, but more broadly speaking, cmdlets can have parameter sets where groups of input parameters are defined, such that you can't use two parameters that aren't members of the same parameter set.

If you're running into this error with any other cmdlet, look up its Microsoft documentation, and see if the the top of the page has distinct sets of parameters listed. For example, the documentation for Set-AzureDeployment defines three sets at the top of the page.

Get last field using awk substr

In this case it is better to use basename instead of awk:

 $ basename /home/parent/child1/child2/filename
 filename

What is copy-on-write?

Just to provide another example, Mercurial uses copy-on-write to make cloning local repositories a really "cheap" operation.

The principle is the same as the other examples, except that you're talking about physical files instead of objects in memory. Initially, a clone is not a duplicate but a hard link to the original. As you change files in the clone, copies are written to represent the new version.

Window vs Page vs UserControl for WPF navigation?

A Window object is just what it sounds like: its a new Window for your application. You should use it when you want to pop up an entirely new window. I don't often use more than one Window in WPF because I prefer to put dynamic content in my main Window that changes based on user action.

A Page is a page inside your Window. It is mostly used for web-based systems like an XBAP, where you have a single browser window and different pages can be hosted in that window. It can also be used in Navigation Applications like sellmeadog said.

A UserControl is a reusable user-created control that you can add to your UI the same way you would add any other control. Usually I create a UserControl when I want to build in some custom functionality (for example, a CalendarControl), or when I have a large amount of related XAML code, such as a View when using the MVVM design pattern.

When navigating between windows, you could simply create a new Window object and show it

var NewWindow = new MyWindow();
newWindow.Show();

but like I said at the beginning of this answer, I prefer not to manage multiple windows if possible.

My preferred method of navigation is to create some dynamic content area using a ContentControl, and populate that with a UserControl containing whatever the current view is.

<Window x:Class="MyNamespace.MainWindow" ...>
    <DockPanel>
        <ContentControl x:Name="ContentArea" />
    </DockPanel>
</Window>

and in your navigate event you can simply set it using

ContentArea.Content = new MyUserControl();

But if you're working with WPF, I'd highly recommend the MVVM design pattern. I have a very basic example on my blog that illustrates how you'd navigate using MVVM, using this pattern:

<Window x:Class="SimpleMVVMExample.ApplicationView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:SimpleMVVMExample"
        Title="Simple MVVM Example" Height="350" Width="525">

   <Window.Resources>
      <DataTemplate DataType="{x:Type local:HomeViewModel}">
         <local:HomeView /> <!-- This is a UserControl -->
      </DataTemplate>
      <DataTemplate DataType="{x:Type local:ProductsViewModel}">
         <local:ProductsView /> <!-- This is a UserControl -->
      </DataTemplate>
   </Window.Resources>

   <DockPanel>
      <!-- Navigation Buttons -->
      <Border DockPanel.Dock="Left" BorderBrush="Black"
                                    BorderThickness="0,0,1,0">
         <ItemsControl ItemsSource="{Binding PageViewModels}">
            <ItemsControl.ItemTemplate>
               <DataTemplate>
                  <Button Content="{Binding Name}"
                          Command="{Binding DataContext.ChangePageCommand,
                             RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
                          CommandParameter="{Binding }"
                          Margin="2,5"/>
               </DataTemplate>
            </ItemsControl.ItemTemplate>
         </ItemsControl>
      </Border>

      <!-- Content Area -->
      <ContentControl Content="{Binding CurrentPageViewModel}" />
   </DockPanel>
</Window>

Screenshot1 Screenshot2

How can I make a link from a <td> table cell

Yes, that's possible, albeit not literally the <td>, but what's in it. The simple trick is, to make sure that the content extends to the borders of the cell (it won't include the borders itself though).

As already explained, this isn't semantically correct. An a element is an inline element and should not be used as block-level element. However, here's an example (but JavaScript plus a td:hover CSS style will be much neater) that works in most browsers:

<td>
  <a href="http://example.com">
    <div style="height:100%;width:100%">
      hello world
    </div>
  </a>
</td>

PS: it's actually neater to change a in a block-level element using CSS as explained in another solution in this thread. it won't work well in IE6 though, but that's no news ;)

Alternative (non-advised) solution

If your world is only Internet Explorer (rare, nowadays), you can violate the HTML standard and write this, it will work as expected, but will be highly frowned upon and be considered ill-advised (you haven't heard this from me). Any other browser than IE will not render the link, but will show the table correctly.

<table>
    <tr>
        <a href="http://example.com"><td  width="200">hello world</td></a>
    </tr>
</table>

How to stop a goroutine

You can't kill a goroutine from outside. You can signal a goroutine to stop using a channel, but there's no handle on goroutines to do any sort of meta management. Goroutines are intended to cooperatively solve problems, so killing one that is misbehaving would almost never be an adequate response. If you want isolation for robustness, you probably want a process.

asp.net: Invalid postback or callback argument

You can add ViewStateMode="Disabled"

asp:UpdatePanel ID="UpdatePanel1" runat="server" ViewStateMode="Disabled"

Check if space is in a string

Use this:

word = raw_input("Please enter a single word : ")
while True:
    if " " in word:
        word = raw_input("Please enter a single word : ")
    else:
        print "Thanks"
        break

How do I trim whitespace from a string?

I wanted to remove the too-much spaces in a string (also in between the string, not only in the beginning or end). I made this, because I don't know how to do it otherwise:

string = "Name : David         Account: 1234             Another thing: something  " 

ready = False
while ready == False:
    pos = string.find("  ")
    if pos != -1:
       string = string.replace("  "," ")
    else:
       ready = True
print(string)

This replaces double spaces in one space until you have no double spaces any more

How can I solve "Non-static method xxx:xxx() should not be called statically in PHP 5.4?

Disabling the alert message is not a way to solve the problem. Despite the PHP core is continue to work it makes a dangerous assumptions and actions.

Never ignore the error where PHP should make an assumptions of something!!!!

If the class organized as a singleton you can always use function getInstance() and then use getData()

Likse:

$classObj = MyClass::getInstance();
$classObj->getData();

If the class is not a singleton, use

 $classObj = new MyClass();
 $classObj->getData();

A project with an Output Type of Class Library cannot be started directly

    Right Click on "Solution Explorer" -> "Properties"
    Expand "Common Properties"
    Select "Start Up Project"
    click the radio button "Single Start_up Project"
    select your Project name from the drop down list.

If still not working after the above steps, then try this.

    Expand solutions explorer.
    Right click on project name -> "Properties"
    Go to "Application" tab
    Select "Output type" 
 From the drop down list select the appropriate type according to your application.
    "Windows application" or
    "Console application"

Then save (ctrl + S)

Try debugging (F5)

GIT commit as different user without email / or only email

The --author option doesn't work:

*** Please tell me who you are.

Run

  git config --global user.email "[email protected]"
  git config --global user.name "Your Name"

This does:

git -c user.name='A U Thor' -c [email protected] commit

How to install trusted CA certificate on Android device?

Here's an alternate solution that actually adds your certificate to the built in list of default certificates: Trusting all certificates using HttpClient over HTTPS

However, it will only work for your application. There's no way to programmatically do it for all applications on a user's device, since that would be a security risk.

Constructor overloading in Java - best practice

Constructor overloading is like method overloading. Constructors can be overloaded to create objects in different ways.

The compiler differentiates constructors based on how many arguments are present in the constructor and other parameters like the order in which the arguments are passed.

For further details about java constructor, please visit https://tecloger.com/constructor-in-java/

Find duplicate characters in a String and count the number of occurances using Java

  public class StringCountwithOutHashMap {
  public static void main(String[] args) {
    System.out.println("Plz Enter Your String: ");
    Scanner sc = new Scanner(System.in);
    String s1 = sc.nextLine();
    int count = 0;
    for (int i = 0; i < s1.length(); i++) {
        for (int j = 0; j < s1.length(); j++) {
            if (s1.charAt(i) == s1.charAt(j)) {
                count++;
            } 
        } 
        System.out.println(s1.charAt(i) + " --> " + count);
        String d = String.valueOf(s1.charAt(i)).trim();
        s1 = s1.replaceAll(d, "");
        count = 0;
    }}}

How to really read text file from classpath in Java

You say "I am trying to read a text file which is set in CLASSPATH system variable." My guess this is on Windows and you are using this ugly dialog to edit the "System Variables".

Now you run your Java program in the console. And that doesn't work: The console gets a copy of the values of the system variables once when it is started. This means any change in the dialog afterwards doesn't have any effect.

There are these solutions:

  1. Start a new console after every change

  2. Use set CLASSPATH=... in the console to set the copy of the variable in the console and when your code works, paste the last value into the variable dialog.

  3. Put the call to Java into .BAT file and double click it. This will create a new console every time (thus copying the current value of the system variable).

BEWARE: If you also have a User variable CLASSPATH then it will shadow your system variable. That is why it is usually better to put the call to your Java program into a .BAT file and set the classpath in there (using set CLASSPATH=) rather than relying on a global system or user variable.

This also makes sure that you can have more than one Java program working on your computer because they are bound to have different classpaths.

How to open an external file from HTML

Your first idea used to be the way but I've also noticed issues doing this using Firefox, try a straight http:// to the file - href='http://server/directory/file.xlsx'

How to use a SQL SELECT statement with Access VBA

Here is another way to use SQL SELECT statement in VBA:

 sSQL = "SELECT Variable FROM GroupTable WHERE VariableCode = '" & Me.comboBox & "'" 
 Set rs = CurrentDb.OpenRecordset(sSQL)
 On Error GoTo resultsetError 
 dbValue = rs!Variable
 MsgBox dbValue, vbOKOnly, "RS VALUE"
resultsetError:
 MsgBox "Error Retrieving value from database",VbOkOnly,"Database Error"

Center a DIV horizontally and vertically

The legitimate way to do that irrespective of size of the div for any browser size is :

   div{
    margin:auto;
    height: 200px;
    width: 200px;
    position:fixed;
    top:0;
    bottom:0;
    left:0;
    right:0;
    background:red;
   }

Live Code

Styling JQuery UI Autocomplete

Based on @md-nazrul-islam reply, This is what I did with SCSS:

ul.ui-autocomplete {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
    float: left;
    display: none;
    min-width: 160px;
    margin: 0 0 10px 25px;
    list-style: none;
    background-color: #ffffff;
    border: 1px solid #ccc;
    border-color: rgba(0, 0, 0, 0.2);
    //@include border-radius(5px);
    @include box-shadow( rgba(0, 0, 0, 0.1) 0 5px 10px );
    @include background-clip(padding-box);
    *border-right-width: 2px;
    *border-bottom-width: 2px;

    li.ui-menu-item{
        padding:0 .5em;
        line-height:2em;
        font-size:.8em;
        &.ui-state-focus{
            background: #F7F7F7;
        }
    }

}

How to run a class from Jar which is not the Main-Class in its Manifest file

You can execute any class which has a public final static main method from a JAR file, even if the jar file has a Main-Class defined.

Execute Main-Class:

java -jar MyJar.jar  // will execute the Main-Class

Execute another class with a public static void main method:

java -cp MyJar.jar com.mycomp.myproj.AnotherClassWithMainMethod

Note: the first uses -jar, the second uses -cp.

Does bootstrap 4 have a built in horizontal divider?

in Bootstrap 5 you can do something like this:

<div class="py-2 my-1 text-center position-relative mx-2">
            <div class="position-absolute w-100 top-50 start-50 translate-middle" style="z-index: 2">
                <span class="d-inline-block bg-white px-2 text-muted">or</span>
            </div>
            <div class="position-absolute w-100 top-50 start-0 border-muted border-top"></div>
</div>

Eclipse does not start when I run the exe?

In my case the problem was not having a proper javabin folder in the PATH variable.

Open the PATH variable and make sure it points to a proper JRE bin folder.

How can I determine the status of a job?

This is an old question, but I just had a similar situation where I needed to check on the status of jobs on SQL Server. A lot of people mentioned the sysjobactivity table and pointed to the MSDN documentation which is great. However, I'd also like to highlight the Job Activity Monitor which provides the status on all jobs that are defined on your server.

Trigger change event of dropdown

alternatively you can put onchange attribute on the dropdownlist itself, that onchange will call certain jquery function like this.

<input type="dropdownlist" onchange="jqueryFunc()">

<script type="text/javascript">
$(function(){
    jqueryFunc(){
        //something goes here
    }
});
</script>

hope this one helps you, and please note that this code is just a rough draft, not tested on any ide. thanks

How to check date of last change in stored procedure or function in SQL server

Try this for stored procedures:

SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'P'
AND name = 'myProc'