Programs & Examples On #Text to html

Use css gradient over background image

The accepted answer works well. Just for completeness (and since I like it's shortness), I wanted to share how to to it with compass (SCSS/SASS):

body{
  $colorStart: rgba(0,0,0,0);
  $colorEnd: rgba(0,0,0,0.8);
  @include background-image(linear-gradient(to bottom, $colorStart, $colorEnd), url("bg.jpg"));
}

Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

numpy.dot(a, b, out=None)

Dot product of two arrays.

For N dimensions it is a sum product over the last axis of a and the second-to-last of b.

Documentation: numpy.dot.

How can I make the computer beep in C#?

In .Net 2.0, you can use Console.Beep().

// Default beep
Console.Beep();

You can also specify the frequency and length of the beep in milliseconds.

// Beep at 5000 Hz for 1 second
Console.Beep(5000, 1000);

For more information refer http://msdn.microsoft.com/en-us/library/8hftfeyw%28v=vs.110%29.aspx

Converting String To Float in C#

You can use the following:

float asd = (float) Convert.ToDouble("41.00027357629127");

How to place div in top right hand corner of page

Try css:

.topcorner{
    position:absolute;
    top:10px;
    right: 10px;
 }

you can play with the top and right properties.

If you want to float the div even when you scroll down, just change position:absolute; to position:fixed;.

Hope it helps.

The specified child already has a parent. You must call removeView() on the child's parent first

In my case I was accidentally returning a child view from within Layout.onCreateView() as shown below:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_reject, container, false);

    Button button = view.findViewById(R.id.some_button);

    return button; // <-- Problem is this
}

The solution was to return the parent view instead of the child view.

One line if-condition-assignment

num1 = 20 * someBoolValue or num1

How to pad a string to a fixed length with spaces in Python?

If you have python version 3.6 or higher you can use f strings

>>> string = "John"
>>> f"{string:<15}"
'John           '

Or if you'd like it to the left

>>> f"{string:>15}"
'          John'

Centered

>>> f"{string:^15}"
'     John      '

For more variations, feel free to check out the docs: https://docs.python.org/3/library/string.html#format-string-syntax

Windows 7, 64 bit, DLL problems

I had the same problem. After spending hours searching on the web, I found a solution for me.

I copied the file combase.dll file (C:\Windows\System32) to the release folder, and it resolved the problem.

How can I determine the type of an HTML element in JavaScript?

nodeName is the attribute you are looking for. For example:

var elt = document.getElementById('foo');
console.log(elt.nodeName);

Note that nodeName returns the element name capitalized and without the angle brackets, which means that if you want to check if an element is an <div> element you could do it as follows:

elt.nodeName == "DIV"

While this would not give you the expected results:

elt.nodeName == "<div>"

Simplest way to restart service on a remote computer

DESCRIPTION: SC is a command line program used for communicating with the NT Service Controller and services. USAGE: sc [command] [service name] ...

    The option <server> has the form "\\ServerName"
    Further help on commands can be obtained by typing: "sc [command]"
    Commands:
      query-----------Queries the status for a service, or
                      enumerates the status for types of services.
      queryex---------Queries the extended status for a service, or
                      enumerates the status for types of services.
      start-----------Starts a service.
      pause-----------Sends a PAUSE control request to a service.
      interrogate-----Sends an INTERROGATE control request to a service.
      continue--------Sends a CONTINUE control request to a service.
      stop------------Sends a STOP request to a service.
      config----------Changes the configuration of a service (persistant).
      description-----Changes the description of a service.
      failure---------Changes the actions taken by a service upon failure.
      qc--------------Queries the configuration information for a service.
      qdescription----Queries the description for a service.
      qfailure--------Queries the actions taken by a service upon failure.
      delete----------Deletes a service (from the registry).
      create----------Creates a service. (adds it to the registry).
      control---------Sends a control to a service.
      sdshow----------Displays a service's security descriptor.
      sdset-----------Sets a service's security descriptor.
      GetDisplayName--Gets the DisplayName for a service.
      GetKeyName------Gets the ServiceKeyName for a service.
      EnumDepend------Enumerates Service Dependencies.

    The following commands don't require a service name:
    sc <server> <command> <option>
      boot------------(ok | bad) Indicates whether the last boot should
                      be saved as the last-known-good boot configuration
      Lock------------Locks the Service Database
      QueryLock-------Queries the LockStatus for the SCManager Database

EXAMPLE: sc start MyService

How to set text size in a button in html

Without using inline CSS you could set the text size of all your buttons using:

input[type="submit"], input[type="button"] {
  font-size: 14px;
}

Hide Twitter Bootstrap nav collapse on click

$(function() {
    $('.nav a').on('click', function(){ 
        if($('.navbar-toggle').css('display') !='none'){
            $('.navbar-toggle').trigger( "click" );
        }
    });
});

How to schedule a task to run when shutting down windows

What I can suggest doing is creating a shortcut to the .bat file (for example on your desktop) and a when you want to shutdown your computer (and run the .bat file) click on the shortcut you created. After doing this, edit the .bat file and add this line of code to the end or where needed:

c:\windows\system32\shutdown -s -f -t 00

What this does it is

  1. Runs the shutdown process
  2. Displays a alert
  3. Forces all running processes to stop
  4. Executes immediately

Embedding SVG into ReactJS

There is a package that converts it for you and returns the svg as a string to implement into your reactJS file.

https://www.npmjs.com/package/convert-svg-react

How to move mouse cursor using C#?

Take a look at the Cursor.Position Property. It should get you started.

private void MoveCursor()
{
   // Set the Current cursor, move the cursor's Position,
   // and set its clipping rectangle to the form. 

   this.Cursor = new Cursor(Cursor.Current.Handle);
   Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
   Cursor.Clip = new Rectangle(this.Location, this.Size);
}

how to set the default value to the drop down list control?

lstDepartment.DataTextField = "DepartmentName";
lstDepartment.DataValueField = "DepartmentID";
lstDepartment.DataSource = dtDept;
lstDepartment.DataBind();
'Set the initial value:
lstDepartment.SelectedValue = depID;
lstDepartment.Attributes.Remove("InitialValue");
lstDepartment.Attributes.Add("InitialValue", depID);

And in your cancel method:

lstDepartment.SelectedValue = lstDepartment.Attributes("InitialValue");

And in your update method:

lstDepartment.Attributes("InitialValue") = lstDepartment.SelectedValue;

Way to ng-repeat defined number of times instead of repeating over array?

For users using CoffeeScript, you can use a range comprehension:

Directive

link: (scope, element, attrs) ->
  scope.range = [1..+attrs.range]

or Controller

$scope.range = [1..+$someVariable]
$scope.range = [1..5] # Or just an integer

Template

<div ng-repeat="i in range">[ the rest of your code ]</div>

The cast to value type 'Int32' failed because the materialized value is null

Had this error message when I was trying to select from a view.

The problem was the view recently had gained some new null rows (in SubscriberId column), and it had not been updated in EDMX (EF database first).

The column had to be Nullable type for it to work.

var dealer = Context.Dealers.Where(x => x.dealerCode == dealerCode).FirstOrDefault();

Before view refresh:

public int SubscriberId { get; set; }

After view refresh:

public Nullable<int> SubscriberId { get; set; }

Deleting and adding the view back in EDMX worked.

Hope it helps someone.

How often should you use git-gc?

Note that the downside of garbage-collecting your repository is that, well, the garbage gets collected. As we all know as computer users, files we consider garbage right now might turn out to be very valuable three days in the future. The fact that git keeps most of its debris around has saved my bacon several times – by browsing all the dangling commits, I have recovered much work that I had accidentally canned.

So don’t be too much of a neat freak in your private clones. There’s little need for it.

OTOH, the value of data recoverability is questionable for repos used mainly as remotes, eg. the place all the devs push to and/or pulled from. There, it might be sensible to kick off a GC run and a repacking frequently.

How to set the timeout for a TcpClient?

If using async & await and desire to use a time out without blocking, then an alternative and simpler approach from the answer provide by mcandal is to execute the connect on a background thread and await the result. For example:

Task<bool> t = Task.Run(() => client.ConnectAsync(ipAddr, port).Wait(1000));
await t;
if (!t.Result)
{
   Console.WriteLine("Connect timed out");
   return; // Set/return an error code or throw here.
}
// Successful Connection - if we get to here.

See the Task.Wait MSDN article for more info and other examples.

Colors in JavaScript console

I create now the log-css.js https://codepen.io/luis7lobo9b/pen/QWyobwY

// log-css.js v1
const log = console.log.bind();
const css = function(item, color = '#fff', background = 'none', fontSize = '12px', fontWeight = 700, fontFamily) {
    return ['%c ' + item + ' ', 'color:' + color + ';background:' + background + ';font-size:' + fontSize + ';font-weight:' + fontWeight + (fontFamily ? ';font-family:' + fontFamily : '')];
};
// example
log(...css('Lorem ipsum dolor sit amet, consectetur adipisicing elit.', 'rebeccapurple', '#000', '14px'));

Why Is Subtracting These Two Times (in 1927) Giving A Strange Result?

The moral of this strangeness is:

  • Use dates and times in UTC wherever possible.
  • If you can not display a date or time in UTC, always indicate the time-zone.
  • If you can not require an input date/time in UTC, require an explicitly indicated time-zone.

Get protocol + host name from URL

The standard library function urllib.parse.urlsplit() is all you need. Here is an example for Python3:

>>> import urllib.parse
>>> o = urllib.parse.urlsplit('https://user:[email protected]:8080/dir/page.html?q1=test&q2=a2#anchor1')
>>> o.scheme
'https'
>>> o.netloc
'user:[email protected]:8080'
>>> o.hostname
'www.example.com'
>>> o.port
8080
>>> o.path
'/dir/page.html'
>>> o.query
'q1=test&q2=a2'
>>> o.fragment
'anchor1'
>>> o.username
'user'
>>> o.password
'pass'

Ruby: Calling class method from instance

Similar your question, you could use:

class Truck
  def default_make
    # Do something
  end

  def initialize
    super
    self.default_make
  end
end

WCF Service, the type provided as the service attribute values…could not be found

Turns out that the Eval.svc.cs needed its namespace changed to EvalServiceLibary, rather than EvalServiceSite.

Remove scrollbar from iframe

If anyone here is having a problem with disabling scrollbars on the iframe, it could be because the iframe's content has scrollbars on elements below the html element!

Some layouts set html and body to 100% height, and use a #wrapper div with overflow: auto; (or scroll), thereby moving the scrolling to the #wrapper element.

In such a case, nothing you do will prevent the scrollbars from showing up except editing the other page's content.

Powershell: convert string to number

Simply casting the string as an int won't work reliably. You need to convert it to an int32. For this you can use the .NET convert class and its ToInt32 method. The method requires a string ($strNum) as the main input, and the base number (10) for the number system to convert to. This is because you can not only convert to the decimal system (the 10 base number), but also to, for example, the binary system (base 2).

Give this method a try:

[string]$strNum = "1.500"
[int]$intNum = [convert]::ToInt32($strNum, 10)

$intNum

For-loop vs while loop in R

The variable in the for loop is an integer sequence, and so eventually you do this:

> y=as.integer(60000)*as.integer(60000)
Warning message:
In as.integer(60000) * as.integer(60000) : NAs produced by integer overflow

whereas in the while loop you are creating a floating point number.

Its also the reason these things are different:

> seq(0,2,1)
[1] 0 1 2
> seq(0,2)
[1] 0 1 2

Don't believe me?

> identical(seq(0,2),seq(0,2,1))
[1] FALSE

because:

> is.integer(seq(0,2))
[1] TRUE
> is.integer(seq(0,2,1))
[1] FALSE

Add UIPickerView & a Button in Action sheet - How?

Yep ! I finally Find it.

implement following code on your button click event, to pop up action sheet as given in the image of question.

UIActionSheet *aac = [[UIActionSheet alloc] initWithTitle:@"How many?"
                                             delegate:self
                                    cancelButtonTitle:nil
                               destructiveButtonTitle:nil
                                    otherButtonTitles:nil];

UIDatePicker *theDatePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0, 44.0, 0.0, 0.0)];
if(IsDateSelected==YES)
{
    theDatePicker.datePickerMode = UIDatePickerModeDate;
    theDatePicker.maximumDate=[NSDate date];
}else {
    theDatePicker.datePickerMode = UIDatePickerModeTime;
}

self.dtpicker = theDatePicker;
[theDatePicker release];
[dtpicker addTarget:self action:@selector(dateChanged) forControlEvents:UIControlEventValueChanged];

pickerDateToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
pickerDateToolbar.barStyle = UIBarStyleBlackOpaque;
[pickerDateToolbar sizeToFit];

NSMutableArray *barItems = [[NSMutableArray alloc] init];

UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[barItems addObject:flexSpace];

UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(DatePickerDoneClick)];
[barItems addObject:doneBtn];

[pickerDateToolbar setItems:barItems animated:YES];

[aac addSubview:pickerDateToolbar];
[aac addSubview:dtpicker];
[aac showInView:self.view];
[aac setBounds:CGRectMake(0,0,320, 464)];

How to check if my string is equal to null?

I prefer to use:

if(!StringUtils.isBlank(myString)) { // checks if myString is whitespace, empty, or null
    // do something
}

Read StringUtils.isBlank() vs String.isEmpty().

Intellij JAVA_HOME variable

If you'd like to have your JAVA_HOME recognised by intellij, you can do one of these:

  • Start your intellij from terminal /Applications/IntelliJ IDEA 14.app/Contents/MacOS (this will pick your bash env variables)
  • Add login env variable by executing: launchctl setenv JAVA_HOME "/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home"

To directly answer your question, you can add launchctl line in your ~/.bash_profile

As others have answered you can ignore JAVA_HOME by setting up SDK in project structure.

find all the name using mysql query which start with the letter 'a'

I would go for substr() functionality in MySql.

Basically, this function takes account of three parameters i.e. substr(str,pos,len)

http://www.w3resource.com/mysql/string-functions/mysql-substr-function.php

SELECT * FROM artists 
WHERE lower(substr(name,1,1)) in ('a','b','c');

When to use If-else if-else over switch statements and vice versa

Use switch every time you have more than 2 conditions on a single variable, take weekdays for example, if you have a different action for every weekday you should use a switch.

Other situations (multiple variables or complex if clauses you should Ifs, but there isn't a rule on where to use each.

AngularJS- Login and Authentication in each route and controller

I wrote a post a few months back on how to set up user registration and login functionality with Angular, you can check it out at http://jasonwatmore.com/post/2015/03/10/AngularJS-User-Registration-and-Login-Example.aspx

I check if the user is logged in the $locationChangeStart event, here is my main app.js showing this:

(function () {
    'use strict';
 
    angular
        .module('app', ['ngRoute', 'ngCookies'])
        .config(config)
        .run(run);
 
    config.$inject = ['$routeProvider', '$locationProvider'];
    function config($routeProvider, $locationProvider) {
        $routeProvider
            .when('/', {
                controller: 'HomeController',
                templateUrl: 'home/home.view.html',
                controllerAs: 'vm'
            })
 
            .when('/login', {
                controller: 'LoginController',
                templateUrl: 'login/login.view.html',
                controllerAs: 'vm'
            })
 
            .when('/register', {
                controller: 'RegisterController',
                templateUrl: 'register/register.view.html',
                controllerAs: 'vm'
            })
 
            .otherwise({ redirectTo: '/login' });
    }
 
    run.$inject = ['$rootScope', '$location', '$cookieStore', '$http'];
    function run($rootScope, $location, $cookieStore, $http) {
        // keep user logged in after page refresh
        $rootScope.globals = $cookieStore.get('globals') || {};
        if ($rootScope.globals.currentUser) {
            $http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.authdata; // jshint ignore:line
        }
 
        $rootScope.$on('$locationChangeStart', function (event, next, current) {
            // redirect to login page if not logged in and trying to access a restricted page
            var restrictedPage = $.inArray($location.path(), ['/login', '/register']) === -1;
            var loggedIn = $rootScope.globals.currentUser;
            if (restrictedPage && !loggedIn) {
                $location.path('/login');
            }
        });
    }
 
})();

getResources().getColor() is deprecated

well it's deprecated in android M so you must make exception for android M and lower. Just add current theme on getColor function. You can get current theme with getTheme().

This will do the trick in fragment, you can replace getActivity() with getBaseContext(), yourContext, etc which hold your current context

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white, getActivity().getTheme()));
}else {
    yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white));
}

*p.s : color is deprecated in M, but drawable is deprecated in L

Putting GridView data in a DataTable

user this full solution to convert gridview to datatable

 public DataTable gridviewToDataTable(GridView gv)
        {

            DataTable dtCalculate = new DataTable("TableCalculator");

            // Create Column 1: Date
            DataColumn dateColumn = new DataColumn();
            dateColumn.DataType = Type.GetType("System.DateTime");
            dateColumn.ColumnName = "date";

            // Create Column 3: TotalSales
            DataColumn loanBalanceColumn = new DataColumn();
            loanBalanceColumn.DataType = Type.GetType("System.Double");
            loanBalanceColumn.ColumnName = "loanbalance";


            DataColumn offsetBalanceColumn = new DataColumn();
            offsetBalanceColumn.DataType = Type.GetType("System.Double");
            offsetBalanceColumn.ColumnName = "offsetbalance";


            DataColumn netloanColumn = new DataColumn();
            netloanColumn.DataType = Type.GetType("System.Double");
            netloanColumn.ColumnName = "netloan";


            DataColumn interestratecolumn = new DataColumn();
            interestratecolumn.DataType = Type.GetType("System.Double");
            interestratecolumn.ColumnName = "interestrate";

            DataColumn interestrateperdaycolumn = new DataColumn();
            interestrateperdaycolumn.DataType = Type.GetType("System.Double");
            interestrateperdaycolumn.ColumnName = "interestrateperday";

            // Add the columns to the ProductSalesData DataTable
            dtCalculate.Columns.Add(dateColumn);
            dtCalculate.Columns.Add(loanBalanceColumn);
            dtCalculate.Columns.Add(offsetBalanceColumn);
            dtCalculate.Columns.Add(netloanColumn);
            dtCalculate.Columns.Add(interestratecolumn);
            dtCalculate.Columns.Add(interestrateperdaycolumn);

            foreach (GridViewRow row in gv.Rows)
            {
                DataRow dr;
                dr = dtCalculate.NewRow();

                dr["date"] = DateTime.Parse(row.Cells[0].Text);
                dr["loanbalance"] = double.Parse(row.Cells[1].Text);
                dr["offsetbalance"] = double.Parse(row.Cells[2].Text);
                dr["netloan"] = double.Parse(row.Cells[3].Text);
                dr["interestrate"] = double.Parse(row.Cells[4].Text);
                dr["interestrateperday"] = double.Parse(row.Cells[5].Text);


                dtCalculate.Rows.Add(dr);
            }



            return dtCalculate;
        }

Python Decimals format

Here's a function that will do the trick:

def myformat(x):
    return ('%.2f' % x).rstrip('0').rstrip('.')

And here are your examples:

>>> myformat(1.00)
'1'
>>> myformat(1.20)
'1.2'
>>> myformat(1.23)
'1.23'
>>> myformat(1.234)
'1.23'
>>> myformat(1.2345)
'1.23'

Edit:

From looking at other people's answers and experimenting, I found that g does all of the stripping stuff for you. So,

'%.3g' % x

works splendidly too and is slightly different from what other people are suggesting (using '{0:.3}'.format() stuff). I guess take your pick.

How to compare arrays in JavaScript?

While the top answer to this question is correct and good, the code provided could use some improvement.

Below is my own code for comparing arrays and objects. The code is short and simple:

Array.prototype.equals = function(otherArray) {
  if (!otherArray || this.length != otherArray.length) return false;
  return this.reduce(function(equal, item, index) {
    var otherItem = otherArray[index];
    var itemType = typeof item, otherItemType = typeof otherItem;
    if (itemType !== otherItemType) return false;
    return equal && (itemType === "object" ? item.equals(otherItem) : item === otherItem);
  }, true);
};

if(!Object.prototype.keys) {
  Object.prototype.keys = function() {
    var a = [];
    for (var key in this) {
      if (this.hasOwnProperty(key)) a.push(key);
    }
    return a;
  }
  Object.defineProperty(Object.prototype, "keys", {enumerable: false});
}

Object.prototype.equals = function(otherObject) {
  if (!otherObject) return false;
  var object = this, objectKeys = object.keys();
  if (!objectKeys.equals(otherObject.keys())) return false;
  return objectKeys.reduce(function(equal, key) {
    var value = object[key], otherValue = otherObject[key];
    var valueType = typeof value, otherValueType = typeof otherValue;
    if (valueType !== otherValueType) return false;
    // this will call Array.prototype.equals for arrays and Object.prototype.equals for objects
    return equal && (valueType === "object" ? value.equals(otherValue) : value === otherValue);
  }, true);
}
Object.defineProperty(Object.prototype, "equals", {enumerable: false});

This code supports arrays nested in objects and objects nested in arrays.

You can see a full suite of tests and test the code yourself at this repl: https://repl.it/Esfz/3

What is the purpose of class methods?

This is an interesting topic. My take on it is that python classmethod operates like a singleton rather than a factory (which returns a produced an instance of a class). The reason it is a singleton is that there is a common object that is produced (the dictionary) but only once for the class but shared by all instances.

To illustrate this here is an example. Note that all instances have a reference to the single dictionary. This is not Factory pattern as I understand it. This is probably very unique to python.

class M():
 @classmethod
 def m(cls, arg):
     print "arg was",  getattr(cls, "arg" , None),
     cls.arg = arg
     print "arg is" , cls.arg

 M.m(1)   # prints arg was None arg is 1
 M.m(2)   # prints arg was 1 arg is 2
 m1 = M()
 m2 = M() 
 m1.m(3)  # prints arg was 2 arg is 3  
 m2.m(4)  # prints arg was 3 arg is 4 << this breaks the factory pattern theory.
 M.m(5)   # prints arg was 4 arg is 5

How to get relative path from absolute path

If you have a readonly text box, could you not not make it a label and set AutoEllipsis=true?

alternatively there are posts with code for generating the autoellipsis yourself: (this does it for a grid, you would need to pass i the width for the text box instead. It isn't quite right as it hacks off a bit more than is necessary, and I haven;t got around to finding where the calculation is incorrect. it would be easy enough to modify to remove the first part of the directory rather than the last if you desire.

Private Function AddEllipsisPath(ByVal text As String, ByVal colIndex As Integer, ByVal grid As DataGridView) As String
    'Get the size with the column's width 
    Dim colWidth As Integer = grid.Columns(colIndex).Width

    'Calculate the dimensions of the text with the current font
    Dim textSize As SizeF = MeasureString(text, grid.Font)

    Dim rawText As String = text
    Dim FileNameLen As Integer = text.Length - text.LastIndexOf("\")
    Dim ReplaceWith As String = "\..."

    Do While textSize.Width > colWidth
        ' Trim to make room for the ellipsis
        Dim LastFolder As Integer = rawText.LastIndexOf("\", rawText.Length - FileNameLen - 1)

        If LastFolder < 0 Then
            Exit Do
        End If

        rawText = rawText.Substring(0, LastFolder) + ReplaceWith + rawText.Substring(rawText.Length - FileNameLen)

        If ReplaceWith.Length > 0 Then
            FileNameLen += 4
            ReplaceWith = ""
        End If
        textSize = MeasureString(rawText, grid.Font)
    Loop

    Return rawText
End Function

Private Function MeasureString(ByVal text As String, ByVal fontInfo As Font) As SizeF
    Dim size As SizeF
    Dim emSize As Single = fontInfo.Size
    If emSize = 0 Then emSize = 12

    Dim stringFont As New Font(fontInfo.Name, emSize)

    Dim bmp As New Bitmap(1000, 100)
    Dim g As Graphics = Graphics.FromImage(bmp)

    size = g.MeasureString(text, stringFont)
    g.Dispose()
    Return size
End Function

How do you do relative time in Rails?

If you're building a Rails application, you should use

Time.zone.now
Time.zone.today
Time.zone.yesterday

This gives you time or date in the timezone with which you've configured your Rails application.

For example, if you configure your application to use UTC, then Time.zone.now will always be in UTC time (it won't be impacted by the change of British Summertime for example).

Calculating relative time is easy, eg

Time.zone.now - 10.minute
Time.zone.today.days_ago(5)

Python data structure sort list alphabetically

[] denotes a list, () denotes a tuple and {} denotes a dictionary. You should take a look at the official Python tutorial as these are the very basics of programming in Python.

What you have is a list of strings. You can sort it like this:

In [1]: lst = ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']

In [2]: sorted(lst)
Out[2]: ['Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim', 'constitute']

As you can see, words that start with an uppercase letter get preference over those starting with a lowercase letter. If you want to sort them independently, do this:

In [4]: sorted(lst, key=str.lower)
Out[4]: ['constitute', 'Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim']

You can also sort the list in reverse order by doing this:

In [12]: sorted(lst, reverse=True)
Out[12]: ['constitute', 'Whim', 'Stem', 'Sedge', 'Intrigue', 'Eflux']

In [13]: sorted(lst, key=str.lower, reverse=True)
Out[13]: ['Whim', 'Stem', 'Sedge', 'Intrigue', 'Eflux', 'constitute']

Please note: If you work with Python 3, then str is the correct data type for every string that contains human-readable text. However, if you still need to work with Python 2, then you might deal with unicode strings which have the data type unicode in Python 2, and not str. In such a case, if you have a list of unicode strings, you must write key=unicode.lower instead of key=str.lower.

Python error: "IndexError: string index out of range"

There were several problems in your code. Here you have a functional version you can analyze (Lets set 'hello' as the target word):

word = 'hello'
so_far = "-" * len(word)       # Create variable so_far to contain the current guess

while word != so_far:          # if still not complete
    print(so_far)
    guess = input('>> ')       # get a char guess

    if guess in word:
        print("\nYes!", guess, "is in the word!")

        new = ""
        for i in range(len(word)):  
            if guess == word[i]:
                new += guess        # fill the position with new value
            else:
                new += so_far[i]    # same value as before
        so_far = new
    else:
        print("try_again")

print('finish')

I tried to write it for py3k with a py2k ide, be careful with errors.

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

Is it possible to wait until all javascript files are loaded before executing javascript code?

You can use .getScript() and run your code after it loads:

 $.getScript("my_lovely_script.js", function(){

    alert("Script loaded and executed.");
    // here you can use anything you defined in the loaded script

 });

You can see a better explanation here: How do I include a JavaScript file in another JavaScript file?

How do you copy and paste into Git Bash

In windows I'm not sure about copy but for paste works Ctrl+Insert. In Linux copy: CTRL+SHIFT+C, paste: CTRL+SHIFT+V

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

I know this is old but this answer still applies to newer Core releases.

If by chance your DbContext implementation is in a different project than your startup project and you run ef migrations, you'll see this error because the command will not be able to invoke the application's startup code leaving your database provider without a configuration. To fix it, you have to let ef migrations know where they're at.

dotnet ef migrations add MyMigration [-p <relative path to DbContext project>, -s <relative path to startup project>]

Both -s and -p are optionals that default to the current folder.

How can I quantify difference between two images?

You can compare two images using functions from PIL.

import Image
import ImageChops

im1 = Image.open("splash.png")
im2 = Image.open("splash2.png")

diff = ImageChops.difference(im2, im1)

The diff object is an image in which every pixel is the result of the subtraction of the color values of that pixel in the second image from the first image. Using the diff image you can do several things. The simplest one is the diff.getbbox() function. It will tell you the minimal rectangle that contains all the changes between your two images.

You can probably implement approximations of the other stuff mentioned here using functions from PIL as well.

AngularJS custom filter function

Here's an example of how you'd use filter within your AngularJS JavaScript (rather than in an HTML element).

In this example, we have an array of Country records, each containing a name and a 3-character ISO code.

We want to write a function which will search through this list for a record which matches a specific 3-character code.

Here's how we'd do it without using filter:

$scope.FindCountryByCode = function (CountryCode) {
    //  Search through an array of Country records for one containing a particular 3-character country-code.
    //  Returns either a record, or NULL, if the country couldn't be found.
    for (var i = 0; i < $scope.CountryList.length; i++) {
        if ($scope.CountryList[i].IsoAlpha3 == CountryCode) {
            return $scope.CountryList[i];
        };
    };
    return null;
};

Yup, nothing wrong with that.

But here's how the same function would look, using filter:

$scope.FindCountryByCode = function (CountryCode) {
    //  Search through an array of Country records for one containing a particular 3-character country-code.
    //  Returns either a record, or NULL, if the country couldn't be found.

    var matches = $scope.CountryList.filter(function (el) { return el.IsoAlpha3 == CountryCode; })

    //  If 'filter' didn't find any matching records, its result will be an array of 0 records.
    if (matches.length == 0)
        return null;

    //  Otherwise, it should've found just one matching record
    return matches[0];
};

Much neater.

Remember that filter returns an array as a result (a list of matching records), so in this example, we'll either want to return 1 record, or NULL.

Hope this helps.

Splitting a Java String by the pipe symbol using split("|")

You need

test.split("\\|");

split uses regular expression and in regex | is a metacharacter representing the OR operator. You need to escape that character using \ (written in String as "\\" since \ is also a metacharacter in String literals and require another \ to escape it).

You can also use

test.split(Pattern.quote("|"));

and let Pattern.quote create the escaped version of the regex representing |.

How to bind a List to a ComboBox?

If you are using a ToolStripComboBox there is no DataSource exposed (.NET 4.0):

List<string> someList = new List<string>();
someList.Add("value");
someList.Add("value");
someList.Add("value");

toolStripComboBox1.Items.AddRange(someList.ToArray());

Which to use <div class="name"> or <div id="name">?

class is used when u want to set properties for a group of elements, but id can be set for only one element.

How to select an item in a ListView programmatically?

        int i=99;//is what row you want to select and focus
        listViewRamos.FocusedItem = listViewRamos.Items[0];
        listViewRamos.Items[i].Selected = true;
        listViewRamos.Select();
        listViewRamos.EnsureVisible(i);//This is the trick

Mockito: Mock private field initialization

Following code can be used to initialize mapper in REST client mock. The mapper field is private and needs to be set during unit test setup.

import org.mockito.internal.util.reflection.FieldSetter;

new FieldSetter(client, Client.class.getDeclaredField("mapper")).set(new Mapper());

UIGestureRecognizer on UIImageView

Swift 2.0 Solution

You create a tap, pinch or swipe gesture recognizer in the same manor. Below I'll walk you through 4 steps to getting your recognizer up and running.

4 Steps

1.) Inherit from UIGestureRecognizerDelegate by adding it to your class signature.

class ViewController: UIViewController, UIGestureRecognizerDelegate {...}

2.) Control drag from your image to your viewController to create an IBOutlet:

@IBOutlet weak var tapView: UIImageView!

3.) In your viewDidLoad add the following code:

// create an instance of UITapGestureRecognizer and tell it to run 
// an action we'll call "handleTap:"
let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
// we use our delegate
tap.delegate = self
// allow for user interaction
tapView.userInteractionEnabled = true
// add tap as a gestureRecognizer to tapView
tapView.addGestureRecognizer(tap)

4.) Create the function that will be called when your gesture recognizer is tapped. (You can exclude the = nil if you choose).

func handleTap(sender: UITapGestureRecognizer? = nil) {
    // just creating an alert to prove our tap worked!
    let tapAlert = UIAlertController(title: "hmmm...", message: "this actually worked?", preferredStyle: UIAlertControllerStyle.Alert)
    tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
    self.presentViewController(tapAlert, animated: true, completion: nil)
}

Your final code should look something like this:

class ViewController: UIViewController, UIGestureRecognizerDelegate {

    @IBOutlet weak var tapView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
        tap.delegate = self
        tapView.userInteractionEnabled = true
        tapView.addGestureRecognizer(tap)
    }

    func handleTap(sender: UITapGestureRecognizer? = nil) {
        let tapAlert = UIAlertController(title: "hmmm...", message: "this actually worked?", preferredStyle: UIAlertControllerStyle.Alert)
        tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
        self.presentViewController(tapAlert, animated: true, completion: nil)
    }
}

How to disable right-click context-menu in JavaScript

If your page really relies on the fact that people won't be able to see that menu, you should know that modern browsers (for example Firefox) let the user decide if he really wants to disable it or not. So you have no guarantee at all that the menu would be really disabled.

JSONDecodeError: Expecting value: line 1 column 1

If you look at the output you receive from print() and also in your Traceback, you'll see the value you get back is not a string, it's a bytes object (prefixed by b):

b'{\n  "note":"This file    .....

If you fetch the URL using a tool such as curl -v, you will see that the content type is

Content-Type: application/json; charset=utf-8

So it's JSON, encoded as UTF-8, and Python is considering it a byte stream, not a simple string. In order to parse this, you need to convert it into a string first.

Change the last line of code to this:

info = json.loads(js.decode("utf-8"))

Remove Item in Dictionary based on Value

Here is a method you can use:

    public static void RemoveAllByValue<K, V>(this Dictionary<K, V> dictionary, V value)
    {
        foreach (var key in dictionary.Where(
                kvp => EqualityComparer<V>.Default.Equals(kvp.Value, value)).
                Select(x => x.Key).ToArray())
            dictionary.Remove(key);
    }

How to add Active Directory user group as login in SQL Server

Go to the SQL Server Management Studio, navigate to Security, go to Logins and right click it. A Menu will come up with a button saying "New Login". There you will be able to add users and/or groups from Active Directory to your SQL Server "permissions". Hope this helps

How do search engines deal with AngularJS applications?

This has drastically changed.

http://searchengineland.com/bing-offers-recommendations-for-seo-friendly-ajax-suggests-html5-pushstate-152946

If you use: $locationProvider.html5Mode(true); you are set.

No more rendering pages.

How to make CSS width to fill parent?

Use the styles

left: 0px;

or/and

right: 0px;

or/and

top: 0px;

or/and

bottom: 0px;

I think for most cases that will do the job

How can I show an image using the ImageView component in javafx and fxml?

src/sample/images/shopp.png

**
    Parent root =new StackPane();
    ImageView imageView=new ImageView(new Image(getClass().getResourceAsStream("images/shopp.png")));
    ((StackPane) root).getChildren().add(imageView);

**

Comparing Dates in Oracle SQL

31-DEC-95 isn't a string, nor is 20-JUN-94. They're numbers with some extra stuff added on the end. This should be '31-DEC-95' or '20-JUN-94' - note the single quote, '. This will enable you to do a string comparison.

However, you're not doing a string comparison; you're doing a date comparison. You should transform your string into a date. Either by using the built-in TO_DATE() function, or a date literal.

TO_DATE()

select employee_id
  from employee
 where employee_date_hired > to_date('31-DEC-95','DD-MON-YY')

This method has a few unnecessary pitfalls

  • As a_horse_with_no_name noted in the comments, DEC, doesn't necessarily mean December. It depends on your NLS_DATE_LANGUAGE and NLS_DATE_FORMAT settings. To ensure that your comparison with work in any locale you can use the datetime format model MM instead
  • The year '95 is inexact. You know you mean 1995, but what if it was '50, is that 1950 or 2050? It's always best to be explicit
select employee_id
  from employee
 where employee_date_hired > to_date('31-12-1995','DD-MM-YYYY')

Date literals

A date literal is part of the ANSI standard, which means you don't have to use an Oracle specific function. When using a literal you must specify your date in the format YYYY-MM-DD and you cannot include a time element.

select employee_id
  from employee
 where employee_date_hired > date '1995-12-31'

Remember that the Oracle date datatype includes a time elemement, so the date without a time portion is equivalent to 1995-12-31 00:00:00.

If you want to include a time portion then you'd have to use a timestamp literal, which takes the format YYYY-MM-DD HH24:MI:SS[.FF0-9]

select employee_id
  from employee
 where employee_date_hired > timestamp '1995-12-31 12:31:02'

Further information

NLS_DATE_LANGUAGE is derived from NLS_LANGUAGE and NLS_DATE_FORMAT is derived from NLS_TERRITORY. These are set when you initially created the database but they can be altered by changing your inialization parameters file - only if really required - or at the session level by using the ALTER SESSION syntax. For instance:

alter session set nls_date_format = 'DD.MM.YYYY HH24:MI:SS';

This means:

  • DD numeric day of the month, 1 - 31
  • MM numeric month of the year, 01 - 12 ( January is 01 )
  • YYYY 4 digit year - in my opinion this is always better than a 2 digit year YY as there is no confusion with what century you're referring to.
  • HH24 hour of the day, 0 - 23
  • MI minute of the hour, 0 - 59
  • SS second of the minute, 0-59

You can find out your current language and date language settings by querying V$NLS_PARAMETERSs and the full gamut of valid values by querying V$NLS_VALID_VALUES.

Further reading


Incidentally, if you want the count(*) you need to group by employee_id

select employee_id, count(*)
  from employee
 where employee_date_hired > date '1995-12-31'
 group by employee_id

This gives you the count per employee_id.

Simplest way to wait some asynchronous tasks complete, in Javascript?

I see you are using mongoose so you are talking about server-side JavaScript. In that case I advice looking at async module and use async.parallel(...). You will find this module really helpful - it was developed to solve the problem you are struggling with. Your code may look like this

var async = require('async');

var calls = [];

['aaa','bbb','ccc'].forEach(function(name){
    calls.push(function(callback) {
        conn.collection(name).drop(function(err) {
            if (err)
                return callback(err);
            console.log('dropped');
            callback(null, name);
        });
    }
)});

async.parallel(calls, function(err, result) {
    /* this code will run after all calls finished the job or
       when any of the calls passes an error */
    if (err)
        return console.log(err);
    console.log(result);
});

Why can't I shrink a transaction log file, even after backup?

Don't you need this

DBCC SHRINKFILE ('Wxlog0', 0)

Just be sure that you are aware of the dangers: see here: Do not truncate your ldf files!

And here Backup Log with Truncate_Only: Like a Bear Trap

Test if a property is available on a dynamic variable

Here is the other way:

using Newtonsoft.Json.Linq;

internal class DymanicTest
{
    public static string Json = @"{
            ""AED"": 3.672825,
            ""AFN"": 56.982875,
            ""ALL"": 110.252599,
            ""AMD"": 408.222002,
            ""ANG"": 1.78704,
            ""AOA"": 98.192249,
            ""ARS"": 8.44469
}";

    public static void Run()
    {
        dynamic dynamicObject = JObject.Parse(Json);

        foreach (JProperty variable in dynamicObject)
        {
            if (variable.Name == "AMD")
            {
                var value = variable.Value;
            }
        }
    }
}

How do I update zsh to the latest version?

If you're not using Homebrew, this is what I just did on MAC OS X Lion (10.7.5):

  1. Get the latest version of the ZSH sourcecode

  2. Untar the download into its own directory then install: ./configure && make && make test && sudo make install

  3. This installs the the zsh binary at /usr/local/bin/zsh.

  4. You can now use the shell by loading up a new terminal and executing the binary directly, but you'll want to make it your default shell...

  5. To make it your default shell you must first edit /etc/shells and add the new path. Then you can either run chsh -s /usr/local/bin/zsh or go to System Preferences > Users & Groups > right click your user > Advanced Options... > and then change "Login shell".

  6. Load up a terminal and check you're now in the correct version with echo $ZSH_VERSION. (I wasn't at first, and it took me a while to figure out I'd configured iTerm to use a specific shell instead of the system default).

Check if an array item is set in JS

The most effective way:

if (array.indexOf(element) > -1) {
   alert('Bingooo')
}

W3Schools

JSON for List of int

Assuming your ints are 0, 375, 668,5 and 6:

{
    "Id": "610",
    "Name": "15",
    "Description": "1.99",
    "ItemModList": [
                       0,
                       375,
                       668,
                       5,
                       6
                   ]
}

I suggest that you change "Id": "610" to "Id": 610 since it is a integer/long and not a string. You can read more about the JSON format and examples here http://json.org/

CSS Always On Top

Assuming that your markup looks like:

<div id="header" style="position: fixed;"></div>
<div id="content" style="position: relative;"></div>

Now both elements are positioned; in which case, the element at the bottom (in source order) will cover element above it (in source order).

Add a z-index on header; 1 should be sufficient.

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

You need to inject mock inside the class you're testing. At the moment you're interacting with the real object, not with the mock one. You can fix the code in a following way:

void testAbc(){
     myClass.myObj = myInteface;
     myClass.abc();
     verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}

although it would be a wiser choice to extract all initialization code into @Before

@Before
void setUp(){
     myClass = new myClass();
     myClass.myObj = myInteface;
}

@Test
void testAbc(){
     myClass.abc();
     verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}

How do you install GLUT and OpenGL in Visual Studio 2012?

Yes visual studio 2012 express has built in opengl library. the headers are in the folder C:\Program Files\Windows Kits\8.0\Include\um\gl and the lib files are in folder C:\Program Files\Windows Kits\8.0\Lib\win8\um\x86 & C:\Program Files\Windows Kits\8.0\Lib\win8\um\x64. but the problem is integrating the glut with the existing one.. i downloaded the library from http://www.xmission.com/~nate/glut/glut-3.7.6-bin.zip.. and deployed the files into .....\gl and ....\lib\win8\um\x32 and the dll to %system%/windows folders respectively.. Hope so this will solve the problem...

How to Determine the Screen Height and Width in Flutter

Using the following method we can get the device's physical height. Ex. 1080X1920

WidgetsBinding.instance.window.physicalSize.height
WidgetsBinding.instance.window.physicalSize.width

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

How to display a "busy" indicator with jQuery?

To extend Rodrigo's solution a little - for requests that are executed frequently, you may only want to display the loading image if the request takes more than a minimum time interval, otherwise the image will be continually popping up and quickly disappearing

var loading = false;

$.ajaxSetup({
    beforeSend: function () {
        // Display loading icon if AJAX call takes >1 second
        loading = true;
        setTimeout(function () {
            if (loading) {
                // show loading image
            }
        }, 1000);            
    },
    complete: function () {
        loading = false;
        // hide loading image
    }
});

How do I convert ticks to minutes?

TimeSpan.FromTicks(28000000000).TotalMinutes;

Change text (html) with .animate

Following the suggestion by JiminP....

I made a jsFiddle that will "smoothly" transition between two spans in case anyone is interested in seeing this in action. You have two main options:

  1. one span fades out at the same time as the other span is fading in
  2. one span fades out followed by the other span fading in.

The first time you click the button, number 1 above will occur. The second time you click the button, number 2 will occur. (I did this so you can visually compare the two effects.)

Try it Out: http://jsfiddle.net/jWcLz/594/

Details:

Number 1 above (the more difficult effect) is accomplished by positioning the spans directly on top of each other via CSS with absolute positioning. Also, the jQuery animates are not chained together, so that they can execute at the same time.

HTML

<div class="onTopOfEachOther">
    <span id='a'>Hello</span>
    <span id='b' style="display: none;">Goodbye</span>
</div>

<br />
<br />

<input type="button" id="btnTest" value="Run Test" />

CSS

.onTopOfEachOther {
    position: relative;
}
.onTopOfEachOther span {
    position: absolute;
    top: 0px;
    left: 0px;
}

JavaScript

$('#btnTest').click(function() {        
    fadeSwitchElements('a', 'b');    
}); 

function fadeSwitchElements(id1, id2)
{
    var element1 = $('#' + id1);
    var element2 = $('#' + id2);

    if(element1.is(':visible'))
    {
        element1.fadeToggle(500);
        element2.fadeToggle(500);
    }
    else
    {
         element2.fadeToggle(500, function() {
            element1.fadeToggle(500);
        });   
    }    
}

Select data from date range between two dates

SELECT *
FROM Product_sales
WHERE (
From_date >= '2013-08-19'
AND To_date <= '2013-08-23'
)
OR (
To_date >= '2013-08-19'
AND From_date <= '2013-08-23'
)

Ignore Duplicates and Create New List of Unique Values in Excel

Totero's answer is correct. The link is also very helpful.

Basically the formula you need is:

B2=INDEX($A$2:$A$20, MATCH(0, COUNTIF($B$1:B1, $A$2:$A$20), 0))

Then press ctrl+shift+enter (or it will not work using a array formula).

Two important things to keep in mind here: The complete list is in cells A2:A20, then this formula has to be pasted in cell B2 (Not B1 as that will give you circular reference). Secondly this is an array formula, so you need to press ctrl+shift+enter or it will not work correctly.

How to print HTML content on click of a button, but not the page?

If you add and remove the innerHTML, all javascript, css and more will be loaded twice, and the events will fire twice (happened to me), is better hide content, using jQuery and css like this:

function printDiv(selector) {
    $('body .site-container').css({display:'none'});
    var content = $(selector).clone();
    $('body .site-container').before(content);
    window.print();
    $(selector).first().remove();
    $('body .site-container').css({display:''});
}

The div "site-container" contain all site, so you can call the function like:

printDiv('.someDiv');

Jar mismatch! Fix your dependencies

I think you create a new workspace and import all project properly with his lib and also add external jar android-support-v4.jar in adb bundle in sdk extra files. I think its work for you. Hope all the best

And also use the android support lib it may be help you and also update your adt bundle

Xcode Product -> Archive disabled

In addition to the generic device (or "Any iOS Device" in newer versions of Xcode) mentioned in the other answers, it is possible that the "Archive" action is not selected for the current target in the scheme.

To view and edit at the current scheme, select Product > Schemes > Edit Scheme... (Cmd+<), then make sure that the "Archive" action is checked in the line corresponding to the desired target.

In the image below, Archive is not checked and the Archive action is greyed out in the Product menu. Checking the indicated checkbox fixed the issue for me.

scheme settings

Could not create the Java virtual machine

The problem got resolved when I edited the file /etc/bashrc with same contents as in /etc/profiles and in /etc/profiles.d/limits.sh and did a re-login.

Make one div visible and another invisible

If u want to use display=block it will make the content reader jump, so instead of using display you can set the left attribute to a negative value which does not exist in your html page to be displayed but actually it do.

I hope you must be understanding my point, if I am unable to make u understand u can message me back.

Get first element in PHP stdObject

Update PHP 7.4

Curly brace access syntax is deprecated since PHP 7.4

Update 2019

Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.

Simply iterate its using {}

Example:

$videos{0}->id

This way your object is not destroyed and you can easily iterate through object.

For PHP 5.6 and below use this

$videos{0}['id']

Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {
  [0]=>
  object(stdClass)#20 (22) {
    ["id"]=>
    string(1) "123"
  etc...

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element
$key = key($obj);

Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4


2022 Update:
After PHP 7.4, using current(), end(), etc functions on objects is deprecated.

In newer versions of PHP, use the ArrayIterator class:

$objIterator = new ArrayIterator($obj);

$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object

$key = $objIterator->key(); // and gets the key

How to filter JSON Data in JavaScript or jQuery?

The following code works for me:

_x000D_
_x000D_
var data = [{"name":"Lenovo Thinkpad 41A4298","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A2222","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},_x000D_
{"name":"Lenovo Thinkpad 41A424448","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},_x000D_
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}]_x000D_
_x000D_
var data_filter = data.filter( element => element.website =="yahoo")_x000D_
console.log(data_filter)
_x000D_
_x000D_
_x000D_

Comparing two .jar files

In Linux/CygWin a handy script I use at times is:

#Extract the jar (war or ear)
cd dir1
jar xvf jar-file1
for i in `ls *.class`
do
 javap $i > ${i}.txt #list the functions/variables etc
done

cd dir2
jar xvf jar-file2
for i in `ls *.class`
do
 javap $i > ${i}.txt #list the functions/variables etc
done

diff -r dir1 dir2 #diff recursively

How to declare an array in Python?

For calculations, use numpy arrays like this:

import numpy as np

a = np.ones((3,2))        # a 2D array with 3 rows, 2 columns, filled with ones
b = np.array([1,2,3])     # a 1D array initialised using a list [1,2,3]
c = np.linspace(2,3,100)  # an array with 100 points beteen (and including) 2 and 3

print(a*1.5)  # all elements of a times 1.5
print(a.T+b)  # b added to the transpose of a

these numpy arrays can be saved and loaded from disk (even compressed) and complex calculations with large amounts of elements are C-like fast.

Much used in scientific environments. See here for more.

How to clear the cache in NetBeans

In Window 7 the cache is located at C:/Users/USERNAME/AppData/Local/NetBeans/Cache

Android Support Design TabLayout: Gravity Center and Mode Scrollable

Very simple example and it always works.

/**
 * Setup stretch and scrollable TabLayout.
 * The TabLayout initial parameters in layout must be:
 * android:layout_width="wrap_content"
 * app:tabMaxWidth="0dp"
 * app:tabGravity="fill"
 * app:tabMode="fixed"
 *
 * @param context   your Context
 * @param tabLayout your TabLayout
 */
public static void setupStretchTabLayout(Context context, TabLayout tabLayout) {
    tabLayout.post(() -> {

        ViewGroup.LayoutParams params = tabLayout.getLayoutParams();
        if (params.width == ViewGroup.LayoutParams.MATCH_PARENT) { // is already set up for stretch
            return;
        }

        int deviceWidth = context.getResources()
                                 .getDisplayMetrics().widthPixels;

        if (tabLayout.getWidth() < deviceWidth) {
            tabLayout.setTabMode(TabLayout.MODE_FIXED);
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        } else {
            tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
            params.width = ViewGroup.LayoutParams.WRAP_CONTENT;
        }
        tabLayout.setLayoutParams(params);

    });

}

How to retrieve SQL result column value using column name in Python?

you must look for something called " dictionary in cursor "

i'm using mysql connector and i have to add this parameter to my cursor , so i can use my columns names instead of index's

db = mysql.connector.connect(
    host=db_info['mysql_host'],
    user=db_info['mysql_user'],
    passwd=db_info['mysql_password'],
    database=db_info['mysql_db'])

cur = db.cursor()

cur = db.cursor( buffered=True , dictionary=True)

Difference between app.use and app.get in express.js

Difference between app.use & app.get:

app.use ? It is generally used for introducing middlewares in your application and can handle all type of HTTP requests.

app.get ? It is only for handling GET HTTP requests.

Now, there is a confusion between app.use & app.all. No doubt, there is one thing common in them, that both can handle all kind of HTTP requests. But there are some differences which recommend us to use app.use for middlewares and app.all for route handling.

  1. app.use() ? It takes only one callback.
    app.all() ? It can take multiple callbacks.

  2. app.use() will only see whether url starts with specified path.
    But, app.all() will match the complete path.

For example,

app.use( "/book" , middleware);
// will match /book
// will match /book/author
// will match /book/subject

app.all( "/book" , handler);
// will match /book
// won't match /book/author   
// won't match /book/subject    

app.all( "/book/*" , handler);
// won't match /book        
// will match /book/author
// will match /book/subject
  1. next() call inside the app.use() will call either the next middleware or any route handler, but next() call inside app.all() will invoke the next route handler (app.all(), app.get/post/put... etc.) only. If there is any middleware after, it will be skipped. So, it is advisable to put all the middlewares always above the route handlers.

How to click a browser button with JavaScript automatically?

setInterval(function () {document.getElementById("myButtonId").click();}, 1000);

Create a jTDS connection string

As detailed in the jTDS Frequenlty Asked Questions, the URL format for jTDS is:

jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]

So, to connect to a database called "Blog" hosted by a MS SQL Server running on MYPC, you may end up with something like this:

jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS;user=sa;password=s3cr3t

Or, if you prefer to use getConnection(url, "sa", "s3cr3t"):

jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS

EDIT: Regarding your Connection refused error, double check that you're running SQL Server on port 1433, that the service is running and that you don't have a firewall blocking incoming connections.

How to enable Ad Hoc Distributed Queries

The following command may help you..

EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO

Unable to locate an executable at "/usr/bin/java/bin/java" (-1)

For me, the problem occurs when I've downloaded macOS Compressed Archive which underlying directory contains

jdk-11.0.8.jdk
- Contents
  - Home
    - bin
    - ...
  - MacOS
  - _CodeSignature

So, to solve the problem, JAVA_HOME should be pointed directly to /Path-to-JDK/Contents/Home.

How to convert string to string[]?

Casting can also help converting string to string[]. In this case, casting the string with ToArray() is demonstrated:

String myString = "My String";
String[] myString.Cast<char>().Cast<string>().ToArray();

How to make two plots side-by-side using Python?

Check this page out: http://matplotlib.org/examples/pylab_examples/subplots_demo.html

plt.subplots is similar. I think it's better since it's easier to set parameters of the figure. The first two arguments define the layout (in your case 1 row, 2 columns), and other parameters change features such as figure size:

import numpy as np
import matplotlib.pyplot as plt

x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(5, 3))
axes[0].plot(x1, y1)
axes[1].plot(x2, y2)
fig.tight_layout()

enter image description here

How do I find which program is using port 80 in Windows?

Use this nifty freeware utility:

CurrPorts is network monitoring software that displays the list of all currently opened TCP/IP and UDP ports on your local computer.

Enter image description here

Password must have at least one non-alpha character

Run it through a fairly simple regex: [^a-zA-Z]

And then check it's length separately:

if(string.Length > 7)

Difference between nVidia Quadro and Geforce cards?

I have read that while the underlying chips are essentially the same, the design of the board is different.

Gamers want performance, and tend to favor overclocking and other things to get high frame rates but which maybe burn out the hardware occasionally.

Businesses want reliability, and tend to favor underclocking so they can be sure that their people can keep working.

Also, I have read that the quadro boards use ECC memory.

If you don't know what ECC memory is about: it's a [relatively] well known fact that sometimes memory "flips bits (experiences errors)". This does not happen too often, but is an unavoidable consequence of the underlying physics of the memory cards and the world we live in. ECC memory adds a small percentage to the cost and a small penalty to the performance and has enough redundancy to correct occasional errors and to detect (but not correct) somewhat rarer errors. Gamers don't care about that kind of accuracy because for gamers those are just very rare visual glitches. Companies do care about that kind of accuracy because those glitches would wind up as glitches in their products or else would require more double or triple checking (which winds up being a 2x or 3x performance penalty for some part of their business).

Another issue I have read about has to do with hooking up the graphics card to third party hardware. In other words: sending the images to another card or to another machine instead of to the screen. Most gamers are just using canned software that doesn't have any use for such capabilities. Companies that use that kind of thing get orders of magnitude performance gains from the more direct connections.

How to set NODE_ENV to production/development in OS X

On OSX I'd recommend adding export NODE_ENV=development to your ~/.bash_profile and/or ~/.bashrc and/or ~/.profile.

Personally I add that entry to my ~/.bashrc and then have the ~/.bash_profile ~/.profile import the contents of that file, so it's consistent across environments.

After making these additions, be sure to restart your terminal to pick up settings.

How to change proxy settings in Android (especially in Chrome)

Found one solution for WIFI (works for Android 4.3, 4.4):

  1. Connect to WIFI network (e.g. 'Alex')
  2. Settings->WIFI
  3. Long tap on connected network's name (e.g. on 'Alex')
  4. Modify network config-> Show advanced options
  5. Set proxy settings

NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)

I had a similar problem while setting up boilerplate code. It was reading my bundle.js file as a directory. So as stated here. EISDIR mean its a directory and not a file. To fix the issue, I deleted the file and just recreated (it was originally created automatically). If you cannot find the file (because its hidden), simply use the terminal to find and delete it.

Git cli: get user info from username

git config --list

git config -l

will display your username and email together, along with other info

Numpy how to iterate over columns of array?

For example you want to find a mean of each column in matrix. Let's create the following matrix

mat2 = np.array([1,5,6,7,3,0,3,5,9,10,8,0], dtype=np.float64).reshape(3, 4)

The function for mean is

def my_mean(x):
    return sum(x)/len(x)

To do what is needed and store result in colon vector 'results'

results = np.zeros(4)
for i in range(0, 4):
    mat2[:, i] = my_mean(mat2[:, i])

results = mat2[1,:]      

The results are: array([4.33333333, 5. , 5.66666667, 4. ])

Equivalent of Oracle's RowID in SQL Server

I took this example from MS SQL example and you can see the @ID can be interchanged with integer or varchar or whatever. This was the same solution I was looking for, so I am sharing it. Enjoy!!

-- UPDATE statement with CTE references that are correctly matched.
DECLARE @x TABLE (ID int, Stad int, Value int, ison bit);
INSERT @x VALUES (1, 0, 10, 0), (2, 1, 20, 0), (6, 0, 40, 0), (4, 1, 50, 0), (5, 3, 60, 0), (9, 6, 20, 0), (7, 5, 10, 0), (8, 8, 220, 0);
DECLARE @Error int;
DECLARE @id int;

WITH cte AS (SELECT top 1 * FROM @x WHERE Stad=6)
UPDATE x -- cte is referenced by the alias.
SET ison=1, @id=x.ID
FROM cte AS x

SELECT *, @id as 'random' from @x
GO

if condition in sql server update query

DECLARE @JCnt int=null
SEt @JCnt=(SELECT COUNT( ISNUll(EmpCode,0)) FROM tbl_Employees WHERE EmpCode=1  )

UPDATE #TempCode
SET janCA= CASE WHEN @JCnt>0 THEN (SELECT SUM (ISNUll(Amount,0)) FROM tbl_Salary WHERE Code=1 )ELSE 0 END
WHERE code=1

How to list all the files in android phone by using adb shell?

I might be wrong but "find -name __" works fine for me. (Maybe it's just my phone.) If you just want to list all files, you can try

adb shell ls -R /

You probably need the root permission though.

Edit: As other answers suggest, use ls with grep like this:

adb shell ls -Ral yourDirectory | grep -i yourString

eg.

adb shell ls -Ral / | grep -i myfile

-i is for ignore-case. and / is the root directory.

Java resource as file

Try this:

ClassLoader.getResourceAsStream ("some/pkg/resource.properties");

There are more methods available, e.g. see here: http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html

How to have comments in IntelliSense for function in Visual Studio?

What you need is xml comments - basically, they follow this syntax (as vaguely described by Solmead):

C#

///<summary>
///This is a description of my function.
///</summary>
string myFunction() {
     return "blah";
}

VB

'''<summary>
'''This is a description of my function.
'''</summary>
Function myFunction() As String
    Return "blah"
End Function

CSS disable text selection

Use a wild card selector * for this purpose.

#div * { /* Narrowing, to specific elements, like  input, textarea is PREFFERED */
 -webkit-user-select: none;  
  -moz-user-select: none;    
  -ms-user-select: none;      
  user-select: none;
}

Now, every element inside a div with id div will have no selection.

Demo

how to convert integer to string?

NSArray *myArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3]];

Update for new Objective-C syntax:

NSArray *myArray = @[@1, @2, @3];

Those two declarations are identical from the compiler's perspective.

if you're just wanting to use an integer in a string for putting into a textbox or something:

int myInteger = 5;
NSString* myNewString = [NSString stringWithFormat:@"%i", myInteger];

JavaScriptSerializer - JSON serialization of enum as string

Not sure if this is still relevant but I had to write straight to a json file and I came up with the following piecing several stackoverflow answers together

public class LowercaseJsonSerializer
{
    private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
    {
        ContractResolver = new LowercaseContractResolver()
    };

    public static void Serialize(TextWriter file, object o)
    {
        JsonSerializer serializer = new JsonSerializer()
        {
            ContractResolver = new LowercaseContractResolver(),
            Formatting = Formatting.Indented,
            NullValueHandling = NullValueHandling.Ignore
        };
        serializer.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
        serializer.Serialize(file, o);
    }

    public class LowercaseContractResolver : DefaultContractResolver
    {
        protected override string ResolvePropertyName(string propertyName)
        {
            return Char.ToLowerInvariant(propertyName[0]) + propertyName.Substring(1);
        }
    }
}

It assures all my json keys are lowercase starting according to json "rules". Formats it cleanly indented and ignores nulls in the output. Aslo by adding a StringEnumConverter it prints enums with their string value.

Personally I find this the cleanest I could come up with, without having to dirty the model with annotations.

usage:

    internal void SaveJson(string fileName)
    {
        // serialize JSON directly to a file
        using (StreamWriter file = File.CreateText(@fileName))
        {
            LowercaseJsonSerializer.Serialize(file, jsonobject);
        }
    }

Get program execution time in the shell

For a line-by-line delta measurement, try gnomon.

A command line utility, a bit like moreutils's ts, to prepend timestamp information to the standard output of another command. Useful for long-running processes where you'd like a historical record of what's taking so long.

You can also use the --high and/or --medium options to specify a length threshold in seconds, over which gnomon will highlight the timestamp in red or yellow. And you can do a few other things, too.

example

C++ terminate called without an active exception

When a thread object goes out of scope and it is in joinable state, the program is terminated. The Standard Committee had two other options for the destructor of a joinable thread. It could quietly join -- but join might never return if the thread is stuck. Or it could detach the thread (a detached thread is not joinable). However, detached threads are very tricky, since they might survive till the end of the program and mess up the release of resources. So if you don't want to terminate your program, make sure you join (or detach) every thread.

Python Timezone conversion

# Program
import time
import os

os.environ['TZ'] = 'US/Eastern'
time.tzset()
print('US/Eastern in string form:',time.asctime()) 

os.environ['TZ'] = 'Australia/Melbourne'
time.tzset()
print('Australia/Melbourne in string form:',time.asctime())

os.environ['TZ'] = 'Asia/Kolkata'
time.tzset()
print('Asia/Kolkata in string form:',time.asctime()) 

Show loading image while $.ajax is performed

HTML Code :

<div class="ajax-loader">
  <img src="{{ url('guest/images/ajax-loader.gif') }}" class="img-responsive" />
</div>

CSS Code:

.ajax-loader {
  visibility: hidden;
  background-color: rgba(255,255,255,0.7);
  position: absolute;
  z-index: +100 !important;
  width: 100%;
  height:100%;
}

.ajax-loader img {
  position: relative;
  top:50%;
  left:50%;
}

JQUERY Code:

$.ajax({
  type:'POST',
  beforeSend: function(){
    $('.ajax-loader').css("visibility", "visible");
  },
  url:'/quantityPlus',
  data: {
   'productId':p1,
   'quantity':p2,
   'productPrice':p3},
   success:function(data){
     $('#'+p1+'value').text(data.newProductQuantity);
     $('#'+p1+'amount').text("? "+data.productAmount);
     $('#totalUnits').text(data.newNoOfUnits);
     $('#totalAmount').text("? "+data.newTotalAmount);
  },
  complete: function(){
    $('.ajax-loader').css("visibility", "hidden");
  }
});

}

Run command on the Ansible host

I've found a couple other ways you can write these which are a bit more readable IMHO.

- name: check out a git repository
  local_action: 
    module: git
    repo: git://foosball.example.org/path/to/repo.git
    dest: /local/path

OR

- name: check out a git repository
  local_action: git
  args:
    repo: git://foosball.example.org/path/to/repo.git
    dest: /local/path

Check whether an array is empty

There are two elements in array and this definitely doesn't mean that array is empty. As a quick workaround you can do following:

$errors = array_filter($errors);

if (!empty($errors)) {
}

array_filter() function's default behavior will remove all values from array which are equal to null, 0, '' or false.

Otherwise in your particular case empty() construct will always return true if there is at least one element even with "empty" value.

How to locate the php.ini file (xampp)

This is one of those "you were technically accurate, but you didn't answer my question" but it doesn't mean the above were wrong or misguided - they just didn't run into my issue.

So, I figure I'll give an answer.

As the others mentioned (spot on), I created a file:

<?php
phpinfo(); 
?>

So that worked great. However, it showed "(none)"

So where do you find (none)!?

In my case, on Windows, you just go to where php is installed; I had already had installed it in c:\php I believe it would be the same steps on other platforms.

Then, from a command line, powershell for ex, type: notepad c:\php\php.ini

Tell it yes, you do want to create it, then add whatever changes you needed in the first place. For me, for example:

extension_dir = "c:\php\ext"
extension=mysqli
upload_max_filesize = 25M
post_max_size = 13M
max_execution_time = 300

Then save. Fixed!

By the way - if you do "file new" and then "save as" Notepad will helpfully rename your file to php.ini.txt. Friends let friends NOT AVOID THE CLI.

Google Chrome redirecting localhost to https

NEW DEVELOPMENTS! (if you have Chrome 63+)

If your localhost domain is .dev then I don't think the previously accepted and working answers no longer apply. This is because as of the Chrome 63 Chrome will force .dev domains to HTTPS via preloaded HSTS.

What this means is, .dev basically won't work at all anymore unless you have proper signed SSL certificate -- no more self signed certificates allowed! Learn more at this blog post.

So to fix this issue now and to avoid this happening again in the future .test is one recommended domain because it is reserved by IETF for testing / dev purposes. You should also be able to use .localhost for local dev.

Relative instead of Absolute paths in Excel VBA

You could use one of these for the relative path root:

ActiveWorkbook.Path
ThisWorkbook.Path
App.Path

inject bean reference into a Quartz job in Spring?

A solution from Hary https://stackoverflow.com/a/37797575/4252764 works very well. It's simpler, doesn't need so many special factory beans, and support multiple triggers and jobs. Would just add that Quartz job can be made to be generic, with specific jobs implemented as regular Spring beans.

public interface BeanJob {
  void executeBeanJob();
}

public class GenericJob implements Job {

  @Override
  public void execute(JobExecutionContext context) throws JobExecutionException {
    JobDataMap dataMap = context.getMergedJobDataMap();
    ((BeanJob)dataMap.get("beanJob")).executeBeanJob();    
  }

}

@Component
public class RealJob implements BeanJob {
  private SomeService service;

  @Autowired
  public RealJob(SomeService service) {
    this.service = service;
  }

  @Override
  public void executeBeanJob() {
      //do do job with service
  }

}

MySQL add days to a date

This query stands good for fetching the values between current date and its next 3 dates

SELECT * FROM tableName
WHERE columName BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 3 DAY)

This will eventually add extra 3 days of buffer to the current date.

How to remove specific substrings from a set of strings in Python?

When there are multiple substrings to remove, one simple and effective option is to use re.sub with a compiled pattern that involves joining all the substrings-to-remove using the regex OR (|) pipe.

import re

to_remove = ['.good', '.bad']
strings = ['Apple.good','Orange.good','Pear.bad']

p = re.compile('|'.join(map(re.escape, to_remove))) # escape to handle metachars
[p.sub('', s) for s in strings]
# ['Apple', 'Orange', 'Pear']

Getting only hour/minute of datetime

Just use Hour and Minute properties

var date = DateTime.Now;
date.Hour;
date.Minute;

Or you can easily zero the seconds using

var zeroSecondDate = date.AddSeconds(-date.Second);

Add/remove class with jquery based on vertical scroll?

Add some transition effect to it if you like:

http://jsbin.com/boreme/17/edit?html,css,js

.clearHeader {
  height:50px;
  background:lightblue;
  position:fixed;
  top:0;
  left:0;
  width:100%;

  -webkit-transition: background 2s; /* For Safari 3.1 to 6.0 */
  transition: background 2s;
}

.clearHeader.darkHeader {
 background:#000;
}

Error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

You may also use element.insertAdjacentHTML('beforeend', data);

Please read the "Security considerations" on MDN.

How do I crop an image in Java?

You need to read about Java Image API and mouse-related API, maybe somewhere under the java.awt.event package.

For a start, you need to be able to load and display the image to the screen, maybe you'll use a JPanel.

Then from there, you will try implement a mouse motion listener interface and other related interfaces. Maybe you'll get tied on the mouseDragged method...

For a mousedragged action, you will get the coordinate of the rectangle form by the drag...

Then from these coordinates, you will get the subimage from the image you have and you sort of redraw it anew....

And then display the cropped image... I don't know if this will work, just a product of my imagination... just a thought!

How to set component default props on React component

For a function type prop you can use the following code:

AddAddressComponent.defaultProps = {
    callBackHandler: () => {}
};

AddAddressComponent.propTypes = {
    callBackHandler: PropTypes.func,
};

node.js http 'get' request with query string parameters

I have been struggling with how to add query string parameters to my URL. I couldn't make it work until I realized that I needed to add ? at the end of my URL, otherwise it won't work. This is very important as it will save you hours of debugging, believe me: been there...done that.

Below, is a simple API Endpoint that calls the Open Weather API and passes APPID, lat and lon as query parameters and return weather data as a JSON object. Hope this helps.

//Load the request module
var request = require('request');

//Load the query String module
var querystring = require('querystring');

// Load OpenWeather Credentials
var OpenWeatherAppId = require('../config/third-party').openWeather;

router.post('/getCurrentWeather', function (req, res) {
    var urlOpenWeatherCurrent = 'http://api.openweathermap.org/data/2.5/weather?'
    var queryObject = {
        APPID: OpenWeatherAppId.appId,
        lat: req.body.lat,
        lon: req.body.lon
    }
    console.log(queryObject)
    request({
        url:urlOpenWeatherCurrent,
        qs: queryObject
    }, function (error, response, body) {
        if (error) {
            console.log('error:', error); // Print the error if one occurred

        } else if(response && body) {
            console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
            res.json({'body': body}); // Print JSON response.
        }
    })
})  

Or if you want to use the querystring module, make the following changes

var queryObject = querystring.stringify({
    APPID: OpenWeatherAppId.appId,
    lat: req.body.lat,
    lon: req.body.lon
});

request({
   url:urlOpenWeatherCurrent + queryObject
}, function (error, response, body) {...})

Installing the Android USB Driver in Windows 7

Just download and install "Samsung Kies" from this link. and everything would work as required.

Before installing, uninstall the drivers you have installed for your device.

Update:

Two possible solutions:

  1. Try with the Google USB driver which comes with the SDK.
  2. Download and install the Samsung USB driver from this link as suggested by Mauricio Gracia Gutierrez

Resize a large bitmap file to scaled output file on Android

Resize the bitmap using the following code

    public static Bitmap decodeFile(File file, int reqWidth, int reqHeight){

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;        
    BitmapFactory.decodeFile(file.getPath(), options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(file.getPath(), options);
   }

    private static int calculateInSampleSize(
    BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        // Calculate ratios of height and width to requested height and width
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will guarantee
        // a final image with both dimensions larger than or equal to the
        // requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
     }

     return inSampleSize;
   }    

The same is also explained in the following tip/trick

http://www.codeproject.com/Tips/625810/Android-Image-Operations-Using-BitmapFactory

Get local href value from anchor (a) tag

document.getElementById("link").getAttribute("href"); If you have more than one <a> tag, for example:

_x000D_
_x000D_
<ul>_x000D_
  <li>_x000D_
    <a href="1"></a>_x000D_
  </li>_x000D_
  <li>_x000D_
    <a href="2"></a>_x000D_
  </li>_x000D_
  <li>_x000D_
    <a href="3"></a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

You can do it like this: document.getElementById("link")[0].getAttribute("href"); to access the first array of <a> tags, or depends on the condition you make.

Write values in app.config file

private static string GetSetting(string key)
{
    return ConfigurationManager.AppSettings[key];
}

private static void SetSetting(string key, string value)
{
    Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    configuration.AppSettings.Settings[key].Value = value;
    configuration.Save(ConfigurationSaveMode.Full, true);
    ConfigurationManager.RefreshSection("appSettings");
}

Pushing an existing Git repository to SVN

I recently had to migrate several Git repositories to SVN, and after trying all solutions I could find, what finally worked for me was Mercurial (yes, using a third VCS). Using this guide, I came up with the following process (on Linux, but the basic idea should work on Windows as well).

  1. The necessary packages:

    $ sudo apt-get install git subversion mercurial python-subversion
    
  2. Mercurial needs to be configured by adding the following to ~/.hgrc:

    [extensions]
    hgext.convert=
    
  3. Create some temporary working directories (I had several repositories to migrate so I created directories for the SVN and Git versions, to keep them separate):

    $ mkdir svn
    $ mkdir git
    
  4. Make an empty local SVN repository:

    $ svnadmin create svn/project
    
  5. Clone the existing Git repository:

    $ git clone server/path/project.git git/project
    
  6. Let Mercurial do its thing:

    $ hg convert --dest-type svn git/project svn/project
    
  7. Now the SVN repository should contain the full commit history, but not with original timestamps. If this is not an issue, skip over the next part to step 11.

  8. With a little work, the date and time of each commit can be changed. Since my repositories are fairly small, it was feasible for me to do it manually. First, create a pre-revprop-change hook in the SVN repository with the following contents, to allow the necessary property to be modified:

    #!/bin/bash
    exit 0;
    

    This script has to be made executable:

    $ chmod +x svn/project/hooks/pre-revprop-change
    
  9. Mercurial created a working copy of the SVN repository, named project-wc, so switch to it and edit the commit times:

    $ cd project-wc
    $ svn propedit svn:date --revprop -r 1
    

    Enter the correct date and time (pay attention to timezones!) and save. You should get a message saying "Set new value for property svn:date on revision 1".
    Now rinse and repeat for every other revision.

  10. Optionally check the commit history to make sure everything looks OK:

    $ svn log -r 1:HEAD
    

    Then go back up one level:

    $ cd ..
    
  11. Dump the repository:

    $ svnadmin dump svn/project > project.dump
    
  12. And load the dump on your Subversion server. Done!

This process would probably also work directly between remote repositories, but I found it easier to work with local ones. Fixing the commit times was a lot of work, but overall the process was much more straightforward than any other method I found.

Printing chars and their ASCII-code in C

Try this:

char c = 'a'; // or whatever your character is
printf("%c %d", c, c);

The %c is the format string for a single character, and %d for a digit/integer. By casting the char to an integer, you'll get the ascii value.

Android: ListView elements with multiple clickable buttons

I Know it's late but this may help, this is an example how I write custom adapter class for different click actions

 public class CustomAdapter extends BaseAdapter {

    TextView title;
  Button button1,button2;

    public long getItemId(int position) {
        return position;
    }

    public int getCount() {
        return mAlBasicItemsnav.size();  // size of your list array
    }

    public Object getItem(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = getLayoutInflater().inflate(R.layout.listnavsub_layout, null, false); // use sublayout which you want to inflate in your each list item
        }

        title = (TextView) convertView.findViewById(R.id.textViewnav); // see you have to find id by using convertView.findViewById 
        title.setText(mAlBasicItemsnav.get(position));
      button1=(Button) convertView.findViewById(R.id.button1);
      button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //your click action 

           // if you have different click action at different positions then
            if(position==0)
              {
                       //click action of 1st list item on button click
        }
           if(position==1)
              {
                       //click action of 2st list item on button click
        }
    });

 // similarly for button 2

   button2=(Button) convertView.findViewById(R.id.button2);
      button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //your click action 

    });



        return convertView;
    }
}

How to create a TextArea in Android

Defining an Android Mulitline EditText Field is done via the inputType=”textMultiline”. Unfortunately the text looks strangely aligned. To solve that also use the gravity=”left|top” attribute.

<EditText
   android:id="@+id/editText1"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:ems="10"
   android:gravity="left|top"
   android:inputType="textMultiLine" >

   <requestFocus />

check this vogella blog

How do you share code between projects/solutions in Visual Studio?

You can wild-card inline using the following technique (which is the way in which @Andomar's solution is saved in the .csproj)

<Compile Include="..\MySisterProject\**\*.cs">
  <Link>_Inlined\MySisterProject\%(RecursiveDir)%(Filename)%(Extension)</Link>
</Compile>

Put in:

    <Visible>false</Visible>

If you want to hide the files and/or prevent the wild-card include being expanded if you add or remove an item from a 'virtual existing item' folder like MySisterProject above.

How to find value using key in javascript dictionary

Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.

If you make Dict into an object, this will work:

var dict = {};
var addPair = function (myKey, myValue) {
    dict[myKey] = myValue;
};
var giveValue = function (myKey) {
    return dict[myKey];
};

The myKey variable is already a string, so you don't need more quotes.

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

I got

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

"if not exist" command in batch file

When testing for directories remember that every directory contains two special files.

One is called '.' and the other '..'

. is the directory's own name while .. is the name of it's parent directory.

To avoid trailing backslash problems just test to see if the directory knows it's own name.

eg:

if not exist %temp%\buffer\. mkdir %temp%\buffer

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

jquery will provide you with this and more ...

if($("#something").val()){ //do stuff}

It took me a couple of days to pick it up, but it provides you with you with so much more functionality. An example below.

jQuery(document).ready(function() {
    /* finds closest element with class divright/left and 
    makes all checkboxs inside that div class the same as selectAll...
    */
        $("#selectAll").click(function() {
        $(this).closest('.divright').find(':checkbox').attr('checked', this.checked);
    });
});

oracle sql: update if exists else insert

Please refer to this question if you want to use UPSERT/MERGE command in Oracle. Otherwise, just resolve your issue on the client side by doing a count(1) first and then deciding whether to insert or update.

How can I show and hide elements based on selected option with jQuery?

To show the div while selecting one value and hide while selecting another value from dropdown box: -

 $('#yourselectorid').bind('change', function(event) {

           var i= $('#yourselectorid').val();

            if(i=="sometext") // equal to a selection option
             {
                 $('#divid').show();
             }
           elseif(i=="othertext")
             {
               $('#divid').hide(); // hide the first one
               $('#divid2').show(); // show the other one

              }
});

In OS X Lion, LANG is not set to UTF-8, how to fix it?

This is a headbreaker for a long time. I see now it's OSX.. i change it system-wide and it works perfect

When i add this the LANG in Centos6 and Fedora is also my preferred LANG. You can also "uncheck" export or set locale in terminal settings (OSX) /etc/profile

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

How to use orderby with 2 fields in linq?

VB.NET

 MyList.OrderBy(Function(f) f.StartDate).ThenByDescending(Function(f) f.EndDate)

OR

  From l In MyList Order By l.StartDate Ascending, l.EndDate Descending

What is the difference between :focus and :active?

Focus can only be given by keyboard input, but an Element can be activated by both, a mouse or a keyboard.

If one would use :focus on a link, the style rule would only apply with pressing a botton on the keyboard.

How do I get a list of files in a directory in C++?

Solving this will require a platform specific solution. Look for opendir() on unix/linux or FindFirstFile() on Windows. Or, there are many libraries that will handle the platform specific part for you.

Pure CSS checkbox image replacement

Using javascript seems to be unnecessary if you choose CSS3.

By using :before selector, you can do this in two lines of CSS. (no script involved).

Another advantage of this approach is that it does not rely on <label> tag and works even it is missing.

Note: in browsers without CSS3 support, checkboxes will look normal. (backward compatible).

input[type=checkbox]:before { content:""; display:inline-block; width:12px; height:12px; background:red; }
input[type=checkbox]:checked:before { background:green; }?

You can see a demo here: http://jsfiddle.net/hqZt6/1/

and this one with images:

http://jsfiddle.net/hqZt6/6/

plotting different colors in matplotlib

for color in ['r', 'b', 'g', 'k', 'm']:
    plot(x, y, color=color)

Python Pylab scatter plot error bars (the error on each point is unique)

This is almost like the other answer but you don't need a scatter plot at all, you can simply specify a scatter-plot-like format (fmt-parameter) for errorbar:

import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
e = [0.5, 1., 1.5, 2.]
plt.errorbar(x, y, yerr=e, fmt='o')
plt.show()

Result:

enter image description here

A list of the avaiable fmt parameters can be found for example in the plot documentation:

character   description
'-'     solid line style
'--'    dashed line style
'-.'    dash-dot line style
':'     dotted line style
'.'     point marker
','     pixel marker
'o'     circle marker
'v'     triangle_down marker
'^'     triangle_up marker
'<'     triangle_left marker
'>'     triangle_right marker
'1'     tri_down marker
'2'     tri_up marker
'3'     tri_left marker
'4'     tri_right marker
's'     square marker
'p'     pentagon marker
'*'     star marker
'h'     hexagon1 marker
'H'     hexagon2 marker
'+'     plus marker
'x'     x marker
'D'     diamond marker
'd'     thin_diamond marker
'|'     vline marker
'_'     hline marker

Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Widget.ActionBar.Title'

This is an old post, but if anyone comes up with this problem, i post what solved my problem:

I was trying to add the Action Bar Sherlock to my proyect when i get the error:

Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Holo.ActionBar'.

I turns out that the action bar sherlock proyect and my proyect had differents minSdkVersion and targetSdkVersion. Changing that parameters to match in both proyect solved my problem.

<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="17"/>

Spring Bean Scopes

From the spring specs, there are five types of bean scopes supported :

1. singleton(default*)

Scopes a single bean definition to a single object instance per Spring IoC container.

2. prototype

Scopes a single bean definition to any number of object instances.

3. request

Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

4. session

Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

5. global session

Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

*default means when no scope is explicitly provided in the <bean /> tag. read more about them here: http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch04s04.html

git status shows fatal: bad object HEAD

Your repository is broken. But you can probably fix it AND keep your edits:

  1. Back up first: cp your_repository your_repositry_bak
  2. Clone the broken repository (still works): git clone your_repository your_repository_clone
  3. Replace the broken .git folder with the one from the clone: rm -rf your_repository/.git && cp your_repository_clone/.git your_repository/ -r
  4. Delete clone & backup (if everything is fine): rm -r your_repository_*

java.net.UnknownHostException: Invalid hostname for server: local

This is not specific to the question, but this question showed up when I was Googling for the mentioned UnknownHostException, and the fix is not found anywhere else so I thought I'd add an answer here.

The exception that was continuously received was:

java.net.UnknownHostException:  google.com
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at java.net.Socket.<init>(Socket.java:434)
    at java.net.Socket.<init>(Socket.java:211)
    ... 

No matter how I tried to connect to any valid host, printing it in the terminal would not help either. Everything was right.

The Solution

Not calling trim() for the host string which contained whitespace. In writing a proxy server the host was obtained from HTTP headers with the use of split(":") by semicolons for the HOST header. This left whitespace, and causes the UnknownHostException as a host with whitespace is not a valid host. Doing a host = host.trim() on the String host solved the ambiguous issue.

Using custom std::set comparator

You can use a function comparator without wrapping it like so:

bool comparator(const MyType &lhs, const MyType &rhs)
{
    return [...];
}

std::set<MyType, bool(*)(const MyType&, const MyType&)> mySet(&comparator);

which is irritating to type out every time you need a set of that type, and can cause issues if you don't create all sets with the same comparator.

Changing ImageView source

myImgView.setImageResource(R.drawable.monkey);

is used for setting image in the current image view, but if want to delete this image then you can use this code like:

((ImageView) v.findViewById(R.id.ImageView1)).setImageResource(0);

now this will delete the image from your image view, because it has set the resources value to zero.

Split and join C# string

You can split and join the string, but why not use substrings? Then you only end up with one split instead of splitting the string into 5 parts and re-joining it. The end result is the same, but the substring is probably a bit faster.

string lcStart = "Some Very Large String Here";
int lnSpace = lcStart.IndexOf(' ');

if (lnSpace > -1)
{
    string lcFirst = lcStart.Substring(0, lnSpace);
    string lcRest = lcStart.Substring(lnSpace + 1);
}

Carriage Return\Line feed in Java

Encapsulate your writer to provide char replacement, like this:

public class WindowsFileWriter extends Writer {

    private Writer writer;

    public WindowsFileWriter(File file) throws IOException {
        try {
            writer = new OutputStreamWriter(new FileOutputStream(file), "ISO-8859-15");
        } catch (UnsupportedEncodingException e) {
            writer = new FileWriter(logfile);
        }
    }

    @Override
    public void write(char[] cbuf, int off, int len) throws IOException {
        writer.write(new String(cbuf, off, len).replace("\n", "\r\n"));
    }

    @Override
    public void flush() throws IOException {
        writer.flush();
    }

    @Override
    public void close() throws IOException {
        writer.close();
    }

}

Convert a list to a dictionary in Python

You can do it pretty fast without creating extra arrays, so this will work even for very large arrays:

dict(izip(*([iter(a)]*2)))

If you have a generator a, even better:

dict(izip(*([a]*2)))

Here's the rundown:

iter(h)    #create an iterator from the array, no copies here
[]*2       #creates an array with two copies of the same iterator, the trick
izip(*())  #consumes the two iterators creating a tuple
dict()     #puts the tuples into key,value of the dictionary

Using Python's os.path, how do I go up one directory?

For a paranoid like me, I'd prefer this one

TEMPLATE_DIRS = (
    __file__.rsplit('/', 2)[0] + '/templates',
)

Calculating time difference in Milliseconds

Since Java 1.5, you can get a more precise time value with System.nanoTime(), which obviously returns nanoseconds instead.

There is probably some caching going on in the instances when you get an immediate result.

How can I check if a user is logged-in in php?

Any page you want to perform session-checks on needs to start with:

session_start();

From there, you check your session array for a variable indicating they are logged in:

if (!$_SESSION["loggedIn"]) redirect_to_login();

Logging them in is nothing more than setting that value:

$_SESSION["loggedIn"] = true;

How to send email in ASP.NET C#

Check this out .... it works

http://www.aspnettutorials.com/tutorials/email/email-aspnet2-csharp/

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            MailMessage message = new MailMessage(txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);
            SmtpClient emailClient = new SmtpClient(txtSMTPServer.Text);
            emailClient.Send(message);
            litStatus.Text = "Message Sent";
        }
        catch (Exception ex)
        {
            litStatus.Text=ex.ToString();
        }
    }
}

Difference between Dictionary and Hashtable

Simply, Dictionary<TKey,TValue> is a generic type, allowing:

  • static typing (and compile-time verification)
  • use without boxing

If you are .NET 2.0 or above, you should prefer Dictionary<TKey,TValue> (and the other generic collections)

A subtle but important difference is that Hashtable supports multiple reader threads with a single writer thread, while Dictionary offers no thread safety. If you need thread safety with a generic dictionary, you must implement your own synchronization or (in .NET 4.0) use ConcurrentDictionary<TKey, TValue>.

how to change onclick event with jquery?

(2019) I used $('#'+id).removeAttr().off('click').on('click', function(){...});

I tried $('#'+id).off().on(...), but it wouldn't work to reset the onClick attribute every time it was called to be reset.

I use .on('click',function(){...}); to stay away from having to quote block all my javascript functions.

The O.P. could now use:

$(this).removeAttr('onclick').off('click').on('click', function(){ displayCalendar(document.prjectFrm[ia + 'dtSubDate'],'yyyy-mm-dd', this); });

Where this came through for me is when my div was set with the onClick attribute set statically:

<div onclick = '...'>

Otherwise, if I only had a dynamically attached a listener to it, I would have used the $('#'+id).off().on('click', function(){...});.

Without the off('click') my onClick listeners were being appended not replaced.

Open popup and refresh parent page on close popup

You can reach main page with parent command (parent is the window) after the step you can make everything...

    function funcx() {
        var result = confirm('bla bla bla.!');
        if(result)
            //parent.location.assign("http://localhost:58250/Ekocc/" + document.getElementById('hdnLink').value + "");
            parent.location.assign("http://blabla.com/" + document.getElementById('hdnLink').value + "");
    } 

pod install -bash: pod: command not found

Installing CocoaPods on OS X 10.11

These instructions were tested on all betas and the final release of El Capitan.

Custom GEM_HOME

This is the solution when you are receiving above error

$ mkdir -p $HOME/Software/ruby
$ export GEM_HOME=$HOME/Software/ruby
$ gem install cocoapods
[...]
1 gem installed
$ export PATH=$PATH:$HOME/Software/ruby/bin
$ pod --version
0.38.2

NuGet auto package restore does not work with MSBuild

MSBuild 15 has a /t:restore option that does this. it comes with Visual Studio 2017.

If you want to use this, you also have to use the new PackageReference, which means replacing the packages.config file with elements like this (do this in *.csproj):

<ItemGroup>
  <!-- ... -->
  <PackageReference Include="Contoso.Utility.UsefulStuff" Version="3.6.0" />
  <!-- ... -->
</ItemGroup>

There is an automated migration to this format if you right click on 'References' (it might not show up if you just opened visual studio, rebuild or open up the 'Manage NuGet packages for solution' window and it will start appearing).

Apple Cover-flow effect using jQuery or other library?

http://www.jacksasylum.eu/ContentFlow/

  • is the best I ever found. a true 'CoverFlow', highly configurable, cross-browser, very smooth action, has relections and supports scroll wheel + keyboard control. - has to be what your looking for!

Differences between socket.io and websockets

Its advantages are that it simplifies the usage of WebSockets as you described in #2, and probably more importantly it provides fail-overs to other protocols in the event that WebSockets are not supported on the browser or server. I would avoid using WebSockets directly unless you are very familiar with what environments they don't work and you are capable of working around those limitations.

This is a good read on both WebSockets and Socket.IO.

http://davidwalsh.name/websocket

How to hide 'Back' button on navigation bar on iPhone?

Objective-C:
self.navigationItem.hidesBackButton = YES;

Swift:
navigationItem.hidesBackButton = true

Stopping Docker containers by image name - Ubuntu

Adding on top of @VonC superb answer, here is a ZSH function that you can add into your .zshrc file:

dockstop() {
  docker rm $(docker stop $(docker ps -a -q --filter ancestor="$1" --format="{{.ID}}"))
}

Then in your command line, simply do dockstop myImageName and it will stop and remove all containers that were started from an image called myImageName.

Python socket connection timeout

You just need to use the socket settimeout() method before attempting the connect(), please note that after connecting you must settimeout(None) to set the socket into blocking mode, such is required for the makefile . Here is the code I am using:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect(address)
sock.settimeout(None)
fileobj = sock.makefile('rb', 0)

Script parameters in Bash

I needed to make sure that my scripts are entirely portable between various machines, shells and even cygwin versions. Further, my colleagues who were the ones I had to write the scripts for, are programmers, so I ended up using this:

for ((i=1;i<=$#;i++)); 
do

    if [ ${!i} = "-s" ] 
    then ((i++)) 
        var1=${!i};

    elif [ ${!i} = "-log" ];
    then ((i++)) 
        logFile=${!i};  

    elif [ ${!i} = "-x" ];
    then ((i++)) 
        var2=${!i};    

    elif [ ${!i} = "-p" ]; 
    then ((i++)) 
        var3=${!i};

    elif [ ${!i} = "-b" ];
    then ((i++)) 
        var4=${!i};

    elif [ ${!i} = "-l" ];
    then ((i++)) 
        var5=${!i}; 

    elif [ ${!i} = "-a" ];
    then ((i++)) 
        var6=${!i};
    fi

done;

Rationale: I included a launcher.sh script as well, since the whole operation had several steps which were quasi independent on each other (I'm saying "quasi", because even though each script could be run on its own, they were usually all run together), and in two days I found out, that about half of my colleagues, being programmers and all, were too good to be using the launcher file, follow the "usage", or read the HELP which was displayed every time they did something wrong and they were making a mess of the whole thing, running scripts with arguments in the wrong order and complaining that the scripts didn't work properly. Being the choleric I am I decided to overhaul all my scripts to make sure that they are colleague-proof. The code segment above was the first thing.

Single quotes vs. double quotes in Python

In Perl you want to use single quotes when you have a string which doesn't need to interpolate variables or escaped characters like \n, \t, \r, etc.

PHP makes the same distinction as Perl: content in single quotes will not be interpreted (not even \n will be converted), as opposed to double quotes which can contain variables to have their value printed out.

Python does not, I'm afraid. Technically seen, there is no $ token (or the like) to separate a name/text from a variable in Python. Both features make Python more readable, less confusing, after all. Single and double quotes can be used interchangeably in Python.

XSL substring and indexOf

It's not clear exactly what you want to do with the index of a substring [update: it is clearer now - thanks] but you may be able to use the function substring-after or substring-before:

substring-before('My name is Fred', 'Fred')

returns 'My name is '.

If you need more detailed control, the substring() function can take two or three arguments: string, starting-index, length. Omit length to get the whole rest of the string.

There is no index-of() function for strings in XPath (only for sequences, in XPath 2.0). You can use string-length(substring-before($string, $substring))+1 if you specifically need the position.

There is also contains($string, $substring). These are all documented here. In XPath 2.0 you can use regular expression matching.

(XSLT mostly uses XPath for selecting nodes and processing values, so this is actually more of an XPath question. I tagged it thus.)

Animate scroll to ID on page load

try with following code. make elements with class name page-scroll and keep id name to href of corresponding links

$('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: ($($anchor.attr('href')).offset().top - 50)
        }, 1250, 'easeInOutExpo');
        event.preventDefault();
    });

Convert unix time to readable date in pandas dataframe

If you try using:

df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],***unit='s'***))

and receive an error :

"pandas.tslib.OutOfBoundsDatetime: cannot convert input with unit 's'"

This means the DATE_FIELD is not specified in seconds.

In my case, it was milli seconds - EPOCH time.

The conversion worked using below:

df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],unit='ms')) 

How to declare variable and use it in the same Oracle SQL script?

In Toad I use this works:

declare 
    num number;
begin 
    ---- use 'select into' works 
    --select 123 into num from dual;

    ---- also can use :=
    num := 123;
    dbms_output.Put_line(num);
end;

Then the value will be print to DBMS Output Window.

Reference to here and here2.

Driver executable must be set by the webdriver.ie.driver system property

  1. You will need InternetExplorer driver executable on your system. So download it from the hinted source (http://www.seleniumhq.org/download/) unpack it and place somewhere you can find it. In my example, I will assume you will place it to C:\Selenium\iexploredriver.exe

  2. Then you have to set it up in the system. Here is the Java code pasted from my Selenium project:

    File file = new File("C:/Selenium/iexploredriver.exe");
    System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
    WebDriver driver = new InternetExplorerDriver();
    

Basically, you have to set this property before you initialize driver

ssl.SSLError: tlsv1 alert protocol version

I got this problem too. In macos, here is the solution:

  • Step 1: brew restall python. now you got python3.7 instead of the old python

  • Step 2: build the new env base on python3.7. my path is /usr/local/Cellar/python/3.7.2/bin/python3.7

now, you'll not being disturbed by this problem.

Get File Path (ends with folder)

Use the Application.FileDialog object

Sub SelectFolder()
    Dim diaFolder As FileDialog
    Dim selected As Boolean

    ' Open the file dialog
    Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
    diaFolder.AllowMultiSelect = False
    selected = diaFolder.Show

    If selected Then
        MsgBox diaFolder.SelectedItems(1)
    End If

    Set diaFolder = Nothing
End Sub

Singular matrix issue with Numpy

By definition, by multiplying a 1D vector by its transpose, you've created a singular matrix.

Each row is a linear combination of the first row.

Notice that the second row is just 8x the first row.

Likewise, the third row is 50x the first row.

There's only one independent row in your matrix.

No numeric types to aggregate - change in groupby() behaviour?

I got this error generating a data frame consisting of timestamps and data:

df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp))

Adding the suggested solution works for me:

df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp), dtype=float))

Thanks Chang She!

Example:

                     data
2005-01-01 00:10:00  7.53
2005-01-01 00:20:00  7.54
2005-01-01 00:30:00  7.62
2005-01-01 00:40:00  7.68
2005-01-01 00:50:00  7.81
2005-01-01 01:00:00  7.95
2005-01-01 01:10:00  7.96
2005-01-01 01:20:00  7.95
2005-01-01 01:30:00  7.98
2005-01-01 01:40:00  8.06
2005-01-01 01:50:00  8.04
2005-01-01 02:00:00  8.06
2005-01-01 02:10:00  8.12
2005-01-01 02:20:00  8.12
2005-01-01 02:30:00  8.25
2005-01-01 02:40:00  8.27
2005-01-01 02:50:00  8.17
2005-01-01 03:00:00  8.21
2005-01-01 03:10:00  8.29
2005-01-01 03:20:00  8.31
2005-01-01 03:30:00  8.25
2005-01-01 03:40:00  8.19
2005-01-01 03:50:00  8.17
2005-01-01 04:00:00  8.18
                     data
2005-01-01 00:00:00  7.636000
2005-01-01 01:00:00  7.990000
2005-01-01 02:00:00  8.165000
2005-01-01 03:00:00  8.236667
2005-01-01 04:00:00  8.180000

How to drop a table if it exists?

A better visual and easy way, if you are using Visual Studio, just open from menu bar,

View -> SQL Server Object Explorer

it should open like shown here

enter image description here

Select and Right Click the Table you wish to delete, then delete. Such a screen should be displayed. Click Update Database to confirm.

enter image description here

This method is very safe as it gives you the feedback and will warn of any relations of the deleted table with other tables.

How to make sure docker's time syncs with that of the host?

docker-compose usage:

Add /etc/localtime:/etc/localtime:ro to the volumes attribute:

version: '3'

services:
  a-service:
      image: service-name
      container_name: container-name
      volumes:
        - /etc/localtime:/etc/localtime:ro

Print the contents of a DIV

In Opera, try:

    print_win.document.write('</body></html>');
    print_win.document.close(); // This bit is important
    print_win.print();
    print_win.close();

How do I concatenate or merge arrays in Swift?

To complete the list of possible alternatives, reduce could be used to implement the behavior of flatten:

var a = ["a", "b", "c"] 
var b = ["d", "e", "f"]

let res = [a, b].reduce([],combine:+)

The best alternative (performance/memory-wise) among the ones presented is simply flatten, that just wrap the original arrays lazily without creating a new array structure.

But notice that flatten does not return a LazyCollection, so that lazy behavior will not be propagated to the next operation along the chain (map, flatMap, filter, etc...).

If lazyness makes sense in your particular case, just remember to prepend or append a .lazy to flatten(), for example, modifying Tomasz sample this way:

let c = [a, b].lazy.flatten()

Step out of current function with GDB

You can use the finish command.

finish: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated as fin.

(See 5.2 Continuing and Stepping.)

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

In the default settings, VS Code uses the following fonts (14 pt) in descending order:

  • Monaco
  • Menlo
  • Consolas
  • "Droid Sans Mono"
  • "Inconsolata"
  • "Courier New"
  • monospace (fallback)

How to verify: VS Code runs in a browser. In the first version, you could hit F12 to open the Developer Tools. Inspecting the DOM, you can find a containing several s that make up that line of code. Inspecting one of those spans, you can see that font-family is just the list above.

relevant areas

What do <o:p> elements do anyway?

Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.

The relevant paragraph:

Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.

This makes lots of sense.

For your specific question.. the o in the <o:p> means "Office namespace" so anything following the o: in a tag means "I'm part of Office namespace" - in case of <o:p> it just means paragraph, the equivalent of the ordinary <p> tag.

I assume that every HTML tag has its Office "equivalent" and they have more.

How to programmatically add controls to a form in VB.NET

Yes.

Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim MyTextbox as New Textbox
    With MyTextbox
       .Size = New Size(100,20)
       .Location = New Point(20,20)
    End With
    AddHandler MyTextbox.TextChanged, AddressOf MyTextbox_Changed
    Me.Controls.Add(MyTextbox)

'Without a help environment for an intelli sense substitution
'the address name and the methods name
'cannot be wrote in exchange for each other.
'Until an equality operation is prior for an exchange i have to work
'on an as is base substituted.

End Sub

Friend Sub MyTextbox_Changed(sender as Object, e as EventArgs)
   'Write code here.
End Sub

Using NOT operator in IF conditions

try like this

if (!(a | b)) {
    //blahblah
}

It's same with

if (a | b) {}
else {
    // blahblah
}