Programs & Examples On #Mindate

Bootstrap datetimepicker is not a function

Below is the right code. Include JS files in following manner:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(function() {_x000D_
    $('#datetimepicker6').datetimepicker();_x000D_
    $('#datetimepicker7').datetimepicker({_x000D_
      useCurrent: false //Important! See issue #1075_x000D_
    });_x000D_
    $("#datetimepicker6").on("dp.change", function(e) {_x000D_
      $('#datetimepicker7').data("DateTimePicker").minDate(e.date);_x000D_
    });_x000D_
    $("#datetimepicker7").on("dp.change", function(e) {_x000D_
      $('#datetimepicker6').data("DateTimePicker").maxDate(e.date);_x000D_
    });_x000D_
  });_x000D_
});
_x000D_
<html>_x000D_
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>_x000D_
_x000D_
<body>_x000D_
_x000D_
_x000D_
_x000D_
  <div class="container">_x000D_
    <div class='col-md-5'>_x000D_
      <div class="form-group">_x000D_
        <div class='input-group date' id='datetimepicker6'>_x000D_
          <input type='text' class="form-control" />_x000D_
          <span class="input-group-addon">_x000D_
                        <span class="glyphicon glyphicon-calendar"></span>_x000D_
          </span>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class='col-md-5'>_x000D_
      <div class="form-group">_x000D_
        <div class='input-group date' id='datetimepicker7'>_x000D_
          <input type='text' class="form-control" />_x000D_
          <span class="input-group-addon">_x000D_
                        <span class="glyphicon glyphicon-calendar"></span>_x000D_
          </span>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Validate date in dd/mm/yyyy format using JQuery Validate

This works fine for me.

$(document).ready(function () {
       $('#btn_move').click( function(){
           var dateformat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
           var Val_date=$('#txt_date').val();
               if(Val_date.match(dateformat)){
              var seperator1 = Val_date.split('/');
              var seperator2 = Val_date.split('-');

              if (seperator1.length>1)
              {
                  var splitdate = Val_date.split('/');
              }
              else if (seperator2.length>1)
              {
                  var splitdate = Val_date.split('-');
              }
              var dd = parseInt(splitdate[0]);
              var mm  = parseInt(splitdate[1]);
              var yy = parseInt(splitdate[2]);
              var ListofDays = [31,28,31,30,31,30,31,31,30,31,30,31];
              if (mm==1 || mm>2)
              {
                  if (dd>ListofDays[mm-1])
                  {
                      alert('Invalid date format!');
                      return false;
                  }
              }
              if (mm==2)
              {
                  var lyear = false;
                  if ( (!(yy % 4) && yy % 100) || !(yy % 400))
                  {
                      lyear = true;
                  }
                  if ((lyear==false) && (dd>=29))
                  {
                      alert('Invalid date format!');
                      return false;
                  }
                  if ((lyear==true) && (dd>29))
                  {
                      alert('Invalid date format!');
                      return false;
                  }
              }
          }
          else
          {
              alert("Invalid date format!");

              return false;
          }
       });
   });

Angular bootstrap datepicker date format does not format ng-model value

You can make use of $parsers as shown below,this solved it for me.

window.module.directive('myDate', function(dateFilter) {
  return {
    restrict: 'EAC',
    require: '?ngModel',
    link: function(scope, element, attrs, ngModel) {
      ngModel.$parsers.push(function(viewValue) {
        return dateFilter(viewValue,'yyyy-MM-dd');
      });
    }
  };
});

HTML:

<p class="input-group datepicker" >
  <input
     type="text"
     class="form-control"
     name="name"
     datepicker-popup="yyyy-MM-dd"
     date-type="string"
     show-weeks="false"
     ng-model="data[$parent.editable.name]" 
     is-open="$parent.opened"
     min-date="minDate"
     close-text="Close"
     ng-required="{{editable.mandatory}}"
     show-button-bar="false"
     close-on-date-selection="false"
     my-date />
  <span class="input-group-btn">
    <button type="button" class="btn btn-default" ng-click="openDatePicker($event)">
      <i class="glyphicon glyphicon-calendar"></i>
    </button>
  </span>
</p>

Disable future dates after today in Jquery Ui Datepicker

datepicker doesnot have a maxDate as an option.I used this endDate option.It worked well.

> $('.demo-calendar-default').datepicker({
>                 autoHide: true,
>                 zIndex: 2048,
>                 format: 'dd/mm/yyyy',
>                 endDate: new Date()
>             });

jQuery: enabling/disabling datepicker

I am also having This Error!

Then i change this

$("#from").datepicker('disable');

to This

$("#from").datepicker("disable");

mistake : single and double quotes..

Now its Work fine for me..

Changing minDate and maxDate on the fly using jQuery DatePicker

You have a couple of options...

1) You need to call the destroy() method not remove() so...

$('#date').datepicker('destroy');

Then call your method to recreate the datepicker object.

2) You can update the property of the existing object via

$('#date').datepicker('option', 'minDate', new Date(startDate));
$('#date').datepicker('option', 'maxDate', new Date(endDate));

or...

$('#date').datepicker('option', { minDate: new Date(startDate),
                                  maxDate: new Date(endDate) });

disable past dates on datepicker

Below solution worked for me. I hope, this will help you also.

$(document).ready(function() {
    $("#datepicker").datepicker({ startDate:'+0d' });
});

How to set minDate to current date in jQuery UI Datepicker?

You can use the minDate property, like this:

$("input.DateFrom").datepicker({
    changeMonth: true, 
    changeYear: true, 
    dateFormat: 'yy-mm-dd',
    minDate: 0, // 0 days offset = today
    maxDate: 'today',
    onSelect: function(dateText) {
        $sD = new Date(dateText);
        $("input#DateTo").datepicker('option', 'minDate', min);
    }
});

You can also specify a date, like this:

minDate: new Date(), // = today

TypeError: $.browser is undefined

just put the $.browser code in your js

var matched, browser;

jQuery.uaMatch = function( ua ) {
    ua = ua.toLowerCase();

    var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
        /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
        /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
        /(msie) ([\w.]+)/.exec( ua ) ||
        ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
        [];

    return {
        browser: match[ 1 ] || "",
        version: match[ 2 ] || "0"
    };
};

matched = jQuery.uaMatch( navigator.userAgent );
browser = {};

if ( matched.browser ) {
    browser[ matched.browser ] = true;
    browser.version = matched.version;
}

// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
    browser.webkit = true;
} else if ( browser.webkit ) {
    browser.safari = true;
}

jQuery.browser = browser;

jQuery UI: Datepicker set year range dropdown to 100 years

I did this:

var dateToday = new Date();
var yrRange = dateToday.getFullYear() + ":" + (dateToday.getFullYear() + 50);
and then
yearRange : yrRange

where 50 is the range from current year.

How to restrict the selectable date ranges in Bootstrap Datepicker?

The example above can be simplify a bit. Additionally you can put date manually from keyboard instead of selecting it via datepicker only. When clearing the value you need to handle also 'on clearDate' action to remove startDate/endDate boundary:

JS file:

$(".from_date").datepicker({
    format: 'yyyy-mm-dd',
    autoclose: true,
}).on('changeDate', function (selected) {
    var startDate = new Date(selected.date.valueOf());
    $('.to_date').datepicker('setStartDate', startDate);
}).on('clearDate', function (selected) {
    $('.to_date').datepicker('setStartDate', null);
});

$(".to_date").datepicker({
    format: 'yyyy-mm-dd',
    autoclose: true,
}).on('changeDate', function (selected) {
    var endDate = new Date(selected.date.valueOf());
    $('.from_date').datepicker('setEndDate', endDate);
}).on('clearDate', function (selected) {
    $('.from_date').datepicker('setEndDate', null);
});

HTML:

<input class="from_date" placeholder="Select start date" type="text" name="from_date">
<input class="to_date" placeholder="Select end date" type="text" name="to_date">

setting min date in jquery datepicker

Hiya working demo: http://jsfiddle.net/femy8/

Now the calendar will only go to minimum of 1999-10-25.

Click on the image i.e. small icon next to text box for calendar to appear. You can try selecting up until 1999 but the minimum date for selection is 25th of oct 1999. which is what you want.

This will help, have a nice one! :) cheers!

Jquery Code

$(".mypicker").datepicker({
    changeYear: true,
    dateFormat: 'yy-mm-dd',
    showButtonPanel: true,
    changeMonth: true,
    changeYear: true,
    showOn: "button",
        buttonImage: "images/calendar.gif",
        buttonImageOnly: true,
        minDate: new Date('1999/10/25'),
        maxDate: '+30Y',
        inline: true
});


?

jQuery Date Picker - disable past dates

$( "#date" ).datetimepicker({startDate:new Date()}).datetimepicker('update', new Date());

new Date() : function get the todays date previous date are locked. 100% working

How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker

Use the dateFormat option

 $(function(){
        $("#to").datepicker({ dateFormat: 'yy-mm-dd' });
        $("#from").datepicker({ dateFormat: 'yy-mm-dd' }).bind("change",function(){
            var minValue = $(this).val();
            minValue = $.datepicker.parseDate("yy-mm-dd", minValue);
            minValue.setDate(minValue.getDate()+1);
            $("#to").datepicker( "option", "minDate", minValue );
        })
    });

Demo at http://jsfiddle.net/gaby/WArtA/

How do I format date in jQuery datetimepicker?

For example, I get date/time in format Spanish.

$('#timePicker').datetimepicker({
    defaultDate: new Date(),
    format:'DD/MM/YYYY HH:mm'
});

getDate with Jquery Datepicker

This line looks questionable:

page_output.innerHTML = str_output;

You can use .innerHTML within jQuery, or you can use it without, but you have to address the selector semantically one way or the other:

$('#page_output').innerHTML /* for jQuery */
document.getElementByID('page_output').innerHTML /* for standard JS */

or better yet

$('#page_output').html(str_output);

jQuery datepicker to prevent past date

var givenStartDate = $('#startDate').val();
        alert('START DATE'+givenStartDate);
        var givenEndDate = $('#endDate').val();
        alert('END DATE'+givenEndDate);
        var date = new Date();
        var month = date.getMonth()+1;
        var day = date.getDate();
        var currentDate = date.getFullYear() + '-' +
            (month<10 ? '0' : '') + month + '-' +
            (day<10 ? '0' : '') + day;
        if(givenStartDate < currentDate || givenEndDate < currentDate)
         { 
        $("#updateButton").attr("disabled","disabled"); 
         }
         if(givenStartDate < currentDate && givenEndDate > currentDate)
            {
            $("#updateButton").attr("enabled","enabled");
            }
         if(givenStartDate > currentDate || givenEndDate > currentDate) { 
        $("#updateButton").attr("enabled","enabled"); 
         }

Try this. If any mistake, please correct me :) Thanks all.

changing minDate option in JQuery DatePicker not working

Month start from 0. 0 = January, 1 = February, 2 = March, ..., 11 = December.

Xcopy Command excluding files and folders

It is same as above answers, but is simple in steps

c:\SRC\folder1

c:\SRC\folder2

c:\SRC\folder3

c:\SRC\folder4

to copy all above folders to c:\DST\ except folder1 and folder2.

Step1: create a file c:\list.txt with below content, one folder name per one line

folder1\

folder2\

Step2: Go to command pompt and run as below xcopy c:\SRC*.* c:\DST*.* /EXCLUDE:c:\list.txt

START_STICKY and START_NOT_STICKY

Both codes are only relevant when the phone runs out of memory and kills the service before it finishes executing. START_STICKY tells the OS to recreate the service after it has enough memory and call onStartCommand() again with a null intent. START_NOT_STICKY tells the OS to not bother recreating the service again. There is also a third code START_REDELIVER_INTENT that tells the OS to recreate the service and redeliver the same intent to onStartCommand().

This article by Dianne Hackborn explained the background of this a lot better than the official documentation.

Source: http://android-developers.blogspot.com.au/2010/02/service-api-changes-starting-with.html

The key part here is a new result code returned by the function, telling the system what it should do with the service if its process is killed while it is running:

START_STICKY is basically the same as the previous behavior, where the service is left "started" and will later be restarted by the system. The only difference from previous versions of the platform is that it if it gets restarted because its process is killed, onStartCommand() will be called on the next instance of the service with a null Intent instead of not being called at all. Services that use this mode should always check for this case and deal with it appropriately.

START_NOT_STICKY says that, after returning from onStartCreated(), if the process is killed with no remaining start commands to deliver, then the service will be stopped instead of restarted. This makes a lot more sense for services that are intended to only run while executing commands sent to them. For example, a service may be started every 15 minutes from an alarm to poll some network state. If it gets killed while doing that work, it would be best to just let it be stopped and get started the next time the alarm fires.

START_REDELIVER_INTENT is like START_NOT_STICKY, except if the service's process is killed before it calls stopSelf() for a given intent, that intent will be re-delivered to it until it completes (unless after some number of more tries it still can't complete, at which point the system gives up). This is useful for services that are receiving commands of work to do, and want to make sure they do eventually complete the work for each command sent.

How to remove items from a list while iterating?

Your best approach for such an example would be a list comprehension

somelist = [tup for tup in somelist if determine(tup)]

In cases where you're doing something more complex than calling a determine function, I prefer constructing a new list and simply appending to it as I go. For example

newlist = []
for tup in somelist:
    # lots of code here, possibly setting things up for calling determine
    if determine(tup):
        newlist.append(tup)
somelist = newlist

Copying the list using remove might make your code look a little cleaner, as described in one of the answers below. You should definitely not do this for extremely large lists, since this involves first copying the entire list, and also performing an O(n) remove operation for each element being removed, making this an O(n^2) algorithm.

for tup in somelist[:]:
    # lots of code here, possibly setting things up for calling determine
    if determine(tup):
        newlist.append(tup)

Background image jumps when address bar hides iOS/Android/Mobile Chrome

Simple answer if your background allows, why not set background-size: to something just covering device width with media queries and use alongside the :after position: fixed; hack here.

IE: background-size: 901px; for any screens <900px? Not perfect or responsive but worked a charm for me on mobile <480px as i'm using an abstract BG.

How to get the current date and time

tl;dr

Instant.now()

java.time

The java.util.Date class has been outmoded by the new java.time package (Tutorial) in Java 8 and later. The old java.util.Date/.Calendar classes are notoriously troublesome, confusing, and flawed. Avoid them.

ZonedDateTime

Get the current moment in java.time.

ZonedDateTime now = ZonedDateTime.now();

A ZonedDateTime encapsulates:

  • Date.
  • Time-of-day, with a fraction of a second to nanosecond resolution.
  • Time zone.

If no time zone is specified, your JVM’s current default time zone is assigned silently. Better to specify your desired/expected time zone than rely implicitly on default.

ZoneId z = ZoneId.of( "Pacific/Auckland" );
ZonedDateTime zdt = ZonedDateTime.now( z );

UTC

Generally better to get in the habit of doing your back-end work (business logic, database, storage, data exchange) all in UTC time zone. The code above relies implicitly on the JVM’s current default time zone.

The Instant class represents a moment in the timeline in UTC with a resolution of nanoseconds.

Instant instant = Instant.now();

The Instant class is a basic building-block class in java.time and may be used often in your code.

When you need more flexibility in formatting, transform into an OffsetDateTime. Specify a ZoneOffset object. For UTC use the handy constant for UTC.

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );

Time Zone

You easily adjust to another time zone for presentation to the user. Use a proper time zone name, never the 3-4 letter codes such as EST or IST.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime nowMontreal = instant.atZone( z );

Generate a String representation of that date-time value, localized.

String output = DateTimeFormatter
    .ofLocalizedDate( FormatStyle.FULL )
    .withLocale( Locale.CANADA_FRENCH )
    .format ( nowMontreal );

Instant

Or, to stay in UTC, use Instant. An Instant object represents a moment on the timeline, to nanosecond resolution, always in UTC. This provides the building block for a zoned date-time, along with a time zone assignment. You can think of it conceptually this way:

ZonedDateTime = Instant + ZoneId

You can extract an Instant from a ZonedDateTime.

Instant instantNow = zdt.toInstant();

You can start with an Instant. No need to specify a time zone here, as Instant is always in UTC.

Instant now = Instant.now();

Can I pass variable to select statement as column name in SQL Server

You can't use variable names to bind columns or other system objects, you need dynamic sql

DECLARE @value varchar(10)  
SET @value = 'intStep'  
DECLARE @sqlText nvarchar(1000); 

SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)

'IF' in 'SELECT' statement - choose output value based on column values

You can try this also

 SELECT id , IF(type='p', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount FROM table

SQLite string contains other string query

While LIKE is suitable for this case, a more general purpose solution is to use instr, which doesn't require characters in the search string to be escaped. Note: instr is available starting from Sqlite 3.7.15.

SELECT *
  FROM TABLE  
 WHERE instr(column, 'cats') > 0;

Also, keep in mind that LIKE is case-insensitive, whereas instr is case-sensitive.

matplotlib.pyplot will not forget previous plots - how can I flush/refresh?

I discovered that this behaviour only occurs after running a particular script, similar to the one in the question. I have no idea why it occurs.

It works (refreshes the graphs) if I put

plt.clf()
plt.cla()
plt.close()

after every plt.show()

Add a duration to a moment (moment.js)

I am working on an application in which we track live route. Passenger wants to show current position of driver and the expected arrival time to reach at his/her location. So I need to add some duration into current time.

So I found the below mentioned way to do the same. We can add any duration(hour,minutes and seconds) in our current time by moment:

var travelTime = moment().add(642, 'seconds').format('hh:mm A');// it will add 642 seconds in the current time and will give time in 03:35 PM format

var travelTime = moment().add(11, 'minutes').format('hh:mm A');// it will add 11 mins in the current time and will give time in 03:35 PM format; can use m or minutes 

var travelTime = moment().add(2, 'hours').format('hh:mm A');// it will add 2 hours in the current time and will give time in 03:35 PM format

It fulfills my requirement. May be it can help you.

Creating a SOAP call using PHP with an XML body

First off, you have to specify you wish to use Document Literal style:

$client = new SoapClient(NULL, array(
    'location' => 'https://example.com/path/to/service',
    'uri' => 'http://example.com/wsdl',
    'trace' => 1,
    'use' => SOAP_LITERAL)
);

Then, you need to transform your data into a SoapVar; I've written a simple transform function:

function soapify(array $data)
{
        foreach ($data as &$value) {
                if (is_array($value)) {
                        $value = soapify($value);
                }
        }

        return new SoapVar($data, SOAP_ENC_OBJECT);
}

Then, you apply this transform function onto your data:

$data = soapify(array(
    'Acquirer' => array(
        'Id' => 'MyId',
        'UserId' => 'MyUserId',
        'Password' => 'MyPassword',
    ),
));

Finally, you call the service passing the Data parameter:

$method = 'Echo';

$result = $client->$method(new SoapParam($data, 'Data'));

Why is __dirname not defined in node REPL?

Though its not the solution to this problem I would like to add it as it may help others.

You should have two underscores before dirname, not one underscore (__dirname not _dirname).

NodeJS Docs

Windows: XAMPP vs WampServer vs EasyPHP vs alternative

I'm using EasyPHP in making my Thesis about Content Management System. So far, this tool is very good and easy to use.

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

You are not subscribing to any success callback in your $.post AJAX call. Meaning that the request is executed, but you do nothing with the results. If you want to do something useful with the results, try:

$.post('/Branch/Details/' + id, function(result) {
    // Do something with the result like for example inject it into
    // some placeholder and update the DOM.
    // This obviously assumes that your controller action returns
    // a partial view otherwise you will break your markup
});

On the other hand if you want to redirect, you absolutely do not need AJAX. You use AJAX only when you want to stay on the same page and update only a portion of it.

So if you only wanted to redirect the browser:

function foo(id) {
    window.location.href = '/Branch/Details/' + id;
}

As a side note: You should never be hardcoding urls like this. You should always be using url helpers when dealing with urls in an ASP.NET MVC application. So:

function foo(id) {
    var url = '@Url.Action("Details", "Branch", new { id = "__id__" })';
    window.location.href = url.replace('__id__', id);
}

Easy way to dismiss keyboard?

A better approach is to have something "steal" first responder status.

Since UIApplication is a subclass of UIResponder, you could try:

[[UIApplication sharedApplication] becomeFirstResponder]
[[UIApplication sharedApplication] resignFirstResponder]

Failing that, create a new UITextField with a zero sized frame, add it to a view somewhere and do something similar (become followed by resign).

Oracle Error ORA-06512

ORA-06512 is part of the error stack. It gives us the line number where the exception occurred, but not the cause of the exception. That is usually indicated in the rest of the stack (which you have still not posted).

In a comment you said

"still, the error comes when pNum is not between 12 and 14; when pNum is between 12 and 14 it does not fail"

Well, your code does this:

IF ((pNum < 12) OR (pNum > 14)) THEN     
    RAISE vSOME_EX;

That is, it raises an exception when pNum is not between 12 and 14. So does the rest of the error stack include this line?

ORA-06510: PL/SQL: unhandled user-defined exception

If so, all you need to do is add an exception block to handle the error. Perhaps:

PROCEDURE PX(pNum INT,pIdM INT,pCv VARCHAR2,pSup FLOAT)
AS
    vSOME_EX EXCEPTION;

BEGIN 
    IF ((pNum < 12) OR (pNum > 14)) THEN     
        RAISE vSOME_EX;
    ELSE  
        EXECUTE IMMEDIATE  'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('||pCv||', '||pSup||', '||pIdM||')';
    END IF;
exception
    when vsome_ex then
         raise_application_error(-20000
                                 , 'This is not a valid table:  M'||pNum||'GR');

END PX;

The documentation covers handling PL/SQL exceptions in depth.

Check if a row exists, otherwise insert

This is something I just recently had to do:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[cjso_UpdateCustomerLogin]
    (
      @CustomerID AS INT,
      @UserName AS VARCHAR(25),
      @Password AS BINARY(16)
    )
AS 
    BEGIN
        IF ISNULL((SELECT CustomerID FROM tblOnline_CustomerAccount WHERE CustomerID = @CustomerID), 0) = 0
        BEGIN
            INSERT INTO [tblOnline_CustomerAccount] (
                [CustomerID],
                [UserName],
                [Password],
                [LastLogin]
            ) VALUES ( 
                /* CustomerID - int */ @CustomerID,
                /* UserName - varchar(25) */ @UserName,
                /* Password - binary(16) */ @Password,
                /* LastLogin - datetime */ NULL ) 
        END
        ELSE
        BEGIN
            UPDATE  [tblOnline_CustomerAccount]
            SET     UserName = @UserName,
                    Password = @Password
            WHERE   CustomerID = @CustomerID    
        END

    END

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

  1. First of all check latest Chrome version (This is your browser Chrome version) link

  2. Download same version of Chrome Web Driver from this link

Do not download latest Chrome Web Driver if it does not match your Chrome Browser version.

Note: When I write this message, latest Chrome Browser version is 84 but latest Chrome Driver version is 85. I am using Chrome Driver version 84 so that Chrome Driver and Chrome Browser versions are the same.

open resource with relative path in Java

Use this:

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

What is the cleanest way to get the progress of JQuery ajax request?

Follow the steps to display Progress of Ajax Request:

  1. Create a Spinner using Html & CSS or use Bootstrap Spinner.
  2. Display the Spinner when the end-user is requesting for the AJAX Data for infinite loop or for threshold limit time.
  3. So, after a SUCCESS / ERROR result of AJAX Request, remove the Spinner which is currently displayed and show your results.

To make it easy I recommend you using JS Classes for dynamically Displaying & Hiding the spinner for this purpose.

I Hope this helps!

VBA Macro to compare all cells of two Excel files

Do NOT loop through all cells!! There is a lot of overhead in communications between worksheets and VBA, for both reading and writing. Looping through all cells will be agonizingly slow. I'm talking hours.

Instead, load an entire sheet at once into a Variant array. In Excel 2003, this takes about 2 seconds (and 250 MB of RAM). Then you can loop through it in no time at all.

In Excel 2007 and later, sheets are about 1000 times larger (1048576 rows × 16384 columns = 17 billion cells, compared to 65536 rows × 256 columns = 17 million in Excel 2003). You will run into an "Out of memory" error if you try to load the whole sheet into a Variant; on my machine I can only load 32 million cells at once. So you have to limit yourself to the range you know has actual data in it, or load the sheet bit by bit, e.g. 30 columns at a time.

Option Explicit

Sub test()

    Dim varSheetA As Variant
    Dim varSheetB As Variant
    Dim strRangeToCheck As String
    Dim iRow As Long
    Dim iCol As Long

    strRangeToCheck = "A1:IV65536"
    ' If you know the data will only be in a smaller range, reduce the size of the ranges above.
    Debug.Print Now
    varSheetA = Worksheets("Sheet1").Range(strRangeToCheck)
    varSheetB = Worksheets("Sheet2").Range(strRangeToCheck) ' or whatever your other sheet is.
    Debug.Print Now

    For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
        For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
            If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
                ' Cells are identical.
                ' Do nothing.
            Else
                ' Cells are different.
                ' Code goes here for whatever it is you want to do.
            End If
        Next iCol
    Next iRow

End Sub

To compare to a sheet in a different workbook, open that workbook and get the sheet as follows:

Set wbkA = Workbooks.Open(filename:="C:\MyBook.xls")
Set varSheetA = wbkA.Worksheets("Sheet1") ' or whatever sheet you need

Select a date from date picker using Selenium webdriver

WebDriver driver;

public void launch(){

    driver = new FirefoxDriver();
    driver.get("http://www.cleartrip.com/");
    driver.manage().window().maximize();
    System.out.println("The browser launched successfully");
    }
public void clickdate(String inputDate){
    WebElement ele =driver.findElement(By.id("DepartDate"));
    ele.click();
    String month = driver.findElement(By.xpath("//div[@class='monthBlock first']/div[1]//span[1]")).getText();
    String year = driver.findElement(By.xpath("//div[@class='monthBlock first']/div[1]//span[2]")).getText();
    System.out.println("Application month : "+month + " Year :"+year);
    int monthNum = getMonthNum(month);
    System.out.println("Enum Num : "+monthNum);
    String[] parts = inputDate.split("/");
    int noOfHits = ((Integer.parseInt(parts[2])-Integer.parseInt(year))*12)+(Integer.parseInt(parts[1])-monthNum);
    System.out.println("No OF Hits "+noOfHits);
    for(int i=0; i< noOfHits;i++){
    driver.findElement(By.className("nextMonth ")).click();
    }
    List<WebElement> cals=driver.findElements(By.xpath("//div[@class='monthBlock first']//tr"));
    System.out.println(cals.size());
    for( WebElement daterow : cals){
    List<WebElement> datenums = daterow.findElements(By.xpath("//td"));
    /*iterating the "td" list*/
    for(WebElement date : datenums ){
    /* Checking The our input Date(if it match go inside and click*/
    if(date.getText().equalsIgnoreCase(parts[0])){
    date.click();
    break;
                          }
                     }
                 }
}

public  int getMonthNum(String month){
    for (Month mName : Month.values()) {
    if(mName.name().equalsIgnoreCase(month))
    return mName.value;
    }
    return -1;
    }

public enum Month{
    January(1), February(2), March(3), April(4), May(5), June(6) , July(7), August(8), September(9), October(10), November(11),December(12);
    private int value;

    private Month(int value) {
    this.value = value;
    }

    }


public static void main(String[] args)  {
    // TODO Auto-generated method stub
    Cleartrip cl=new Cleartrip();
    cl.launch();
    cl.clickdate("24/11/2015");
    }
}

how to access master page control from content page

I have a helper method for this in my System.Web.UI.Page class

protected T FindControlFromMaster<T>(string name) where T : Control
{
     MasterPage master = this.Master;
     while (master != null)
     {
         T control = master.FindControl(name) as T;
         if (control != null)
             return control;

         master = master.Master;
     }
     return null;
}

then you can access using below code.

Label lblStatus = FindControlFromMaster<Label>("lblStatus");
if(lblStatus!=null) 
    lblStatus.Text = "something";

Python not working in the command line of git bash

In addition to @Vitaliy Terziev answer

try touch .bash_profile and then add alias into the file.

How do I get the localhost name in PowerShell?

Long form:

get-content env:computername

Short form:

gc env:computername

What is the best regular expression to check if a string is a valid URL?

Here is a regex I made which extracts the different parts from an URL:

^((?:https?|ftp):\/\/?)?([^:/\s.]+\.[^:/\s]|localhost)(:\d+)?((?:\/\w+)*\/)?([\w\-.]+[^#?\s]+)?([^#]+)?(#[\w-]+)?$

((?:https?|ftp):\/\/?)?(group 1): extracts the protocol
([^:/\s.]+\.[^:/\s]|localhost)(group 2): extracts the hostname
(:\d+)?(group 3): extracts the port number
((?:\/\w+)*\/)?([\w\-.]+[^#?\s]+)?(groups 4 & 5): extracts the path part
([^#]+)?(group 6): extracts the query part
(#[\w-]+)?(group 7): extracts the hash part

For every part of the regex listed above, you can remove the ending ? to force it (or add one to make it facultative). You can also remove the ^ at the beginning and $ at the end of the regex so it won't need to match the whole string.

See it on regex101.

Note: this regex is not 100% safe and may accept some strings which are not necessarily valid URLs but it does indeed validate some criterias. Its main goal was to extract the different parts of an URL not to validate it.

NSNotificationCenter addObserver in Swift

NSNotificationCenter add observer syntax in Swift 4.0 for iOS 11

  NotificationCenter.default.addObserver(self, selector: #selector(keyboardShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

This is for keyboardWillShow notification name type. Other type can be selected from the available option

the Selector is of type @objc func which handle how the keyboard will show ( this is your user function )

How do I select a random value from an enumeration?

Personally, I'm a fan of extension methods, so I would use something like this (while not really an extension, it looks similar):

public enum Options {
    Zero,
    One,
    Two,
    Three,
    Four,
    Five
}

public static class RandomEnum {
    private static Random _Random = new Random(Environment.TickCount);

    public static T Of<T>() {
        if (!typeof(T).IsEnum)
            throw new InvalidOperationException("Must use Enum type");

        Array enumValues = Enum.GetValues(typeof(T));
        return (T)enumValues.GetValue(_Random.Next(enumValues.Length));
    }
}

[TestClass]
public class RandomTests {
    [TestMethod]
    public void TestMethod1() {
        Options option;
        for (int i = 0; i < 10; ++i) {
            option = RandomEnum.Of<Options>();
            Console.WriteLine(option);
        }
    }

}

Pythonically add header to a csv file

This worked for me.

header = ['row1', 'row2', 'row3']
some_list = [1, 2, 3]
with open('test.csv', 'wt', newline ='') as file:
    writer = csv.writer(file, delimiter=',')
    writer.writerow(i for i in header)
    for j in some_list:
        writer.writerow(j)

Appending to an existing string

You can use << to append to a string in-place.

s = "foo"
old_id = s.object_id
s << "bar"
s                      #=> "foobar"
s.object_id == old_id  #=> true

Convert JS object to JSON string

use JSON.stringify(param1, param2, param3);

What is: -

param1 --> value to convert to JSON

param2 --> function to stringify in your own way. Alternatively, it serves as a white list for which objects need to be included in the final JSON.

param3 --> A Number data type which indicates number of whitespaces to add. Max allowed are 10.

Pass a reference to DOM object with ng-click

While you do the following, technically speaking:

<button ng-click="doSomething($event)"></button>
// In controller:
$scope.doSomething = function($event) {
  //reference to the button that triggered the function:
  $event.target
};

This is probably something you don't want to do as AngularJS philosophy is to focus on model manipulation and let AngularJS do the rendering (based on hints from the declarative UI). Manipulating DOM elements and attributes from a controller is a big no-no in AngularJS world.

You might check this answer for more info: https://stackoverflow.com/a/12431211/1418796

Filter data.frame rows by a logical condition

Sometimes the column you want to filter may appear in a different position than column index 2 or have a variable name.

In this case, you can simply refer the column name you want to filter as:

columnNameToFilter = "cell_type"
expr[expr[[columnNameToFilter]] == "hesc", ]

Razor MVC Populating Javascript array with Model Array

JSON syntax is pretty much the JavaScript syntax for coding your object. Therefore, in terms of conciseness and speed, your own answer is the best bet.

I use this approach when populating dropdown lists in my KnockoutJS model. E.g.

var desktopGrpViewModel = {
    availableComputeOfferings: ko.observableArray(@Html.Raw(JsonConvert.SerializeObject(ViewBag.ComputeOfferings))),
    desktopGrpComputeOfferingSelected: ko.observable(),
};
ko.applyBindings(desktopGrpViewModel);

...

<select name="ComputeOffering" class="form-control valid" id="ComputeOffering" data-val="true" 
data-bind="options: availableComputeOffering,
           optionsText: 'Name',
           optionsValue: 'Id',
           value: desktopGrpComputeOfferingSelect,
           optionsCaption: 'Choose...'">
</select>

Note that I'm using Json.NET NuGet package for serialization and the ViewBag to pass data.

phpMyAdmin allow remote users

Try this

Replace

<Directory /usr/share/phpMyAdmin/>
    <IfModule mod_authz_core.c>
        # Apache 2.4
        <RequireAny>
            Require ip 127.0.0.1
            Require ip ::1
        </RequireAny>
    </IfModule>
    <IfModule !mod_authz_core.c>
        # Apache 2.2
        Order Deny,Allow
        Deny from All
        Allow from 127.0.0.1
        Allow from ::1
    </IfModule>
</Directory>

With this:

<Directory "/usr/share/phpMyAdmin/">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride all
        Order Allow,Deny 
    Allow from all
</Directory>

Add the following line for ease of access:

Alias /phpmyadmin /usr/share/phpMyAdmin

Get viewport/window height in ReactJS

@speckledcarp 's answer is great, but can be tedious if you need this logic in multiple components. You can refactor it as an HOC (higher order component) to make this logic easier to reuse.

withWindowDimensions.jsx

import React, { Component } from "react";

export default function withWindowDimensions(WrappedComponent) {
    return class extends Component {
        state = { width: 0, height: 0 };

        componentDidMount() {
            this.updateWindowDimensions();
            window.addEventListener("resize", this.updateWindowDimensions);
        }

        componentWillUnmount() {
            window.removeEventListener("resize", this.updateWindowDimensions);
        }

        updateWindowDimensions = () => {
            this.setState({ width: window.innerWidth, height: window.innerHeight });
        };

        render() {
            return (
                <WrappedComponent
                    {...this.props}
                    windowWidth={this.state.width}
                    windowHeight={this.state.height}
                    isMobileSized={this.state.width < 700}
                />
            );
        }
    };
}

Then in your main component:

import withWindowDimensions from './withWindowDimensions.jsx';

class MyComponent extends Component {
  render(){
    if(this.props.isMobileSized) return <p>It's short</p>;
    else return <p>It's not short</p>;
}

export default withWindowDimensions(MyComponent);

You can also "stack" HOCs if you have another you need to use, e.g. withRouter(withWindowDimensions(MyComponent))

Edit: I would go with a React hook nowadays (example above here), as they solve some of the advanced issues with HOCs and classes

Why are exclamation marks used in Ruby methods?

From themomorohoax.com:

A bang can used in the below ways, in order of my personal preference.

1) An active record method raises an error if the method does not do what it says it will.

2) An active record method saves the record or a method saves an object (e.g. strip!)

3) A method does something “extra”, like posts to someplace, or does some action.

The point is: only use a bang when you’ve really thought about whether it’s necessary, to save other developers the annoyance of having to check why you are using a bang.

The bang provides two cues to other developers.

1) that it’s not necessary to save the object after calling the method.

2) when you call the method, the db is going to be changed.

http://www.themomorohoax.com/2009/02/11/when-to-use-a-bang-exclamation-point-after-rails-methods

CSS Auto hide elements after 5 seconds

YES!

But you can't do it in the way you may immediately think, because you cant animate or create a transition around the properties you'd otherwise rely on (e.g. display, or changing dimensions and setting to overflow:hidden) in order to correctly hide the element and prevent it from taking up visible space.

Therefore, create an animation for the elements in question, and simply toggle visibility:hidden; after 5 seconds, whilst also setting height and width to zero to prevent the element from still occupying space in the DOM flow.

FIDDLE

CSS

html, body {
    height:100%;
    width:100%;
    margin:0;
    padding:0;
}
#hideMe {
    -moz-animation: cssAnimation 0s ease-in 5s forwards;
    /* Firefox */
    -webkit-animation: cssAnimation 0s ease-in 5s forwards;
    /* Safari and Chrome */
    -o-animation: cssAnimation 0s ease-in 5s forwards;
    /* Opera */
    animation: cssAnimation 0s ease-in 5s forwards;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
}
@keyframes cssAnimation {
    to {
        width:0;
        height:0;
        overflow:hidden;
    }
}
@-webkit-keyframes cssAnimation {
    to {
        width:0;
        height:0;
        visibility:hidden;
    }
}

HTML

<div id='hideMe'>Wait for it...</div>

Convert String (UTF-16) to UTF-8 in C#

A string in C# is always UTF-16, there is no way to "convert" it. The encoding is irrelevant as long as you manipulate the string in memory, it only matters if you write the string to a stream (file, memory stream, network stream...).

If you want to write the string to a XML file, just specify the encoding when you create the XmlWriter

Promise.all().then() resolve?

Today NodeJS supports new async/await syntax. This is an easy syntax and makes the life much easier

async function process(promises) { // must be an async function
    let x = await Promise.all(promises);  // now x will be an array
    x = x.map( tmp => tmp * 10);              // proccessing the data.
}

const promises = [
   new Promise(resolve => setTimeout(resolve, 0, 1)),
   new Promise(resolve => setTimeout(resolve, 0, 2))
];

process(promises)

Learn more:

MySQL & Java - Get id of the last inserted value (JDBC)

Wouldn't you just change:

numero = stmt.executeUpdate(query);

to:

numero = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);

Take a look at the documentation for the JDBC Statement interface.

Update: Apparently there is a lot of confusion about this answer, but my guess is that the people that are confused are not reading it in the context of the question that was asked. If you take the code that the OP provided in his question and replace the single line (line 6) that I am suggesting, everything will work. The numero variable is completely irrelevant and its value is never read after it is set.

R legend placement in a plot

Building on @P-Lapointe solution, but making it extremely easy, you could use the maximum values from your data using max() and then you re-use those maximum values to set the legend xy coordinates. To make sure you don't get beyond the borders, you set up ylim slightly over the maximum values.

a=c(rnorm(1000))
b=c(rnorm(1000))
par(mfrow=c(1,2))
plot(a,ylim=c(0,max(a)+1))
legend(x=max(a)+0.5,legend="a",pch=1)
plot(a,b,ylim=c(0,max(b)+1),pch=2)
legend(x=max(b)-1.5,y=max(b)+1,legend="b",pch=2)

enter image description here

Building with Lombok's @Slf4j and Intellij: Cannot find symbol log

I've just installed the latest idea verion 2108.1 and found this issue, after installed lombok plugin and restart the Idea resolve it.

Angular 2 filter/search list

You have to manually filter result based on change of input each time by keeping listener over input event. While doing manually filtering make sure you should maintain two copy of variable, one would be original collection copy & second would be filteredCollection copy. The advantage for going this way could save your couple of unnecessary filtering on change detection cycle. You may see a more code, but this would be more performance friendly.

Markup - HTML Template

<md-input #myInput placeholder="Item name..." [(ngModel)]="name" (input)="filterItem(myInput.value)"></md-input>

<div *ngFor="let item of filteredItems">
   {{item.name}}
</div>

Code

assignCopy(){
   this.filteredItems = Object.assign([], this.items);
}
filterItem(value){
   if(!value){
       this.assignCopy();
   } // when nothing has typed
   this.filteredItems = Object.assign([], this.items).filter(
      item => item.name.toLowerCase().indexOf(value.toLowerCase()) > -1
   )
}
this.assignCopy();//when you fetch collection from server.

Updating property value in properties file without deleting other values

Properties prop = new Properties();
prop.load(...); // FileInputStream 
prop.setProperty("key", "value");
prop.store(...); // FileOutputStream 

How to count items in JSON data

import json

json_data = json.dumps({
  "result":[
    {
      "run":[
        {
          "action":"stop"
        },
        {
          "action":"start"
        },
        {
          "action":"start"
        }
      ],
      "find": "true"
    }
  ]
})

item_dict = json.loads(json_data)
print len(item_dict['result'][0]['run'])

Convert it in dict.

create table in postgreSQL

Replace bigint(20) not null auto_increment by bigserial not null and datetime by timestamp

What is mutex and semaphore in Java ? What is the main difference?

You compare the incomparable, technically there is no difference between a Semaphore and mutex it doesn't make sense. Mutex is just a significant name like any name in your application logic, it means that you initialize a semaphore at "1", it's used generally to protect a resource or a protected variable to ensure the mutual exclusion.

How can I change the default width of a Twitter Bootstrap modal box?

Below is the code for set the modal pop-up width and left position from the screen through javascript.

$('#openModalPopupId').css({ "width": "80%", "left": "30%"});

Binding arrow keys in JS/jQuery

Are you sure jQuery.HotKeys doesn't support the arrow keys? I've messed around with their demo before and observed left, right, up, and down working when I tested it in IE7, Firefox 3.5.2, and Google Chrome 2.0.172...

EDIT: It appears jquery.hotkeys has been relocated to Github: https://github.com/jeresig/jquery.hotkeys

redirect while passing arguments

You could pass the messages as explicit URL parameter (appropriately encoded), or store the messages into session (cookie) variable before redirecting and then get the variable before rendering the template. For example:

from flask import session, url_for

def do_baz():
    messages = json.dumps({"main":"Condition failed on page baz"})
    session['messages'] = messages
    return redirect(url_for('.do_foo', messages=messages))

@app.route('/foo')
def do_foo():
    messages = request.args['messages']  # counterpart for url_for()
    messages = session['messages']       # counterpart for session
    return render_template("foo.html", messages=json.loads(messages))

(encoding the session variable might not be necessary, flask may be handling it for you, but can't recall the details)

Or you could probably just use Flask Message Flashing if you just need to show simple messages.

How to show/hide if variable is null

In this case, myvar should be a boolean value. If this variable is true, it will show the div, if it's false.. It will hide.

Check this out.

Changing text of UIButton programmatically swift

Just a clarification for those new to Swift and iOS programming. Below line of code:

button.setTitle("myTitle", forState: UIControlState.Normal)

only applies to IBOutlets, not IBActions.

So, if your app is using a button as a function to execute some code, say playing music, and you want to change the title from Play to Pause based on a toggle variable, you need to also create an IBOutlet for that button.

If you try to use button.setTitle against an IBAction you will get an error. Its obvious once you know it, but for the noobs (we all were) this is a helpful tip.

How to control border height?

A border will always be at the full length of the containing box (the height of the element plus its padding), it can't be controlled except for adjusting the height of the element to which it applies. If all you need is a vertical divider, you could use:

<div id="left">
  content
</div>
<span class="divider"></span>
<div id="right">
  content
</div>

With css:

span {
 display: inline-block;
 width: 0;
 height: 1em;
 border-left: 1px solid #ccc;
 border-right: 1px solid #ccc;
}

Demo at JS Fiddle, adjust the height of the span.container to adjust the border 'height'.

Or, to use pseudo-elements (::before or ::after), given the following HTML:

<div id="left">content</div>
<div id="right">content</div>

The following CSS adds a pseudo-element before any div element that's the adjacent sibling of another div element:

div {
    display: inline-block;
    position: relative;
}

div + div {
    padding-left: 0.3em;
}

div + div::before {
    content: '';
    border-left: 2px solid #000;
    position: absolute;
    height: 50%;
    left: 0;
    top: 25%;
}

JS Fiddle demo.

Difference between Iterator and Listiterator?

Iterator is super class of ListIterator.

Here are the differences between them:

  1. With iterator you can move only forward, but with ListIterator you can move backword also while reading the elements.
  2. With ListIterator you can obtain the index at any point while traversing, which is not possible with iterators.
  3. With iterator you can check only for next element available or not, but in listiterator you can check previous and next elements.
  4. With listiterator you can add new element at any point of time, while traversing. Not possible with iterator.
  5. With listiterator you can modify an element while traversing, which is not possible with iterator.

Iterator look and feel:

 public interface Iterator<E> {
    boolean hasNext();
    E next();
    void remove(); //optional-->use only once with next(), 
                         dont use it when u use for:each
    }

ListIterator look and feel:

public interface ListIterator<E> extends Iterator<E> {
    boolean hasNext();
    E next();
    boolean hasPrevious();
    E previous();
    int nextIndex();
    int previousIndex();
    void remove(); //optional
    void set(E e); //optional
    void add(E e); //optional
}

Bootstrap push div content to new line

If your your list is dynamically generated with unknown number and your target is to always have last div in a new line set last div class to "col-xl-12" and remove other classes so it will always take a full row.

This is a copy of your code corrected so that last div always occupy a full row (I although removed unnecessary classes).

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="grid">_x000D_
  <div class="row">_x000D_
    <div class="col-sm-3">Under me should be a DIV</div>_x000D_
    <div class="col-md-6 col-sm-5">Under me should be a DIV</div>_x000D_
    <div class="col-xl-12">I am the last DIV and I always take a full row for my self!!</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

PHP and MySQL Select a Single Value

Try this

$value = mysql_result($result, 0);

Can I use library that used android support with Androidx projects.

API 29.+ usage AndroidX libraries. If you are using API 29.+, then you cannot remove these. If you want to remove AndroidX, then you need to remove the entire 29.+ API from your SDK:

SDK Settings

This will work fine.

C# Copy a file to another location with a different name

One method is:

File.Copy(oldFilePathWithFileName, newFilePathWithFileName);

Or you can use the FileInfo.CopyTo() method too something like this:

FileInfo file = new FileInfo(oldFilePathWithFileName);
file.CopyTo(newFilePathWithFileName);

Example:

File.Copy(@"c:\a.txt", @"c:\b.txt");

or

FileInfo file = new FileInfo(@"c:\a.txt");
file.CopyTo(@"c:\b.txt");

How do I make a request using HTTP basic authentication with PHP curl?

For those who don't want to use curl:

//url
$url = 'some_url'; 

//Credentials
$client_id  = "";
$client_pass= ""; 

//HTTP options
$opts = array('http' =>
    array(
        'method'    => 'POST',
        'header'    => array ('Content-type: application/json', 'Authorization: Basic '.base64_encode("$client_id:$client_pass")),
        'content' => "some_content"
    )
);

//Do request
$context = stream_context_create($opts);
$json = file_get_contents($url, false, $context);

$result = json_decode($json, true);
if(json_last_error() != JSON_ERROR_NONE){
    return null;
}

print_r($result);

What does the CSS rule "clear: both" do?

When you want one element placed at the bottom other element you use this code in CSS. It is used for floats.

If you float content you can float left or right... so in a common layout you might have a left nav, a content div and a footer.

To ensure the footer stays below both of these floats (if you have floated left and right) then you put the footer as clear: both.

This way it will stay below both floats.

(If you are only clearing left then you only really need to clear: left;.)

Go through this tutorial:

Asynchronously wait for Task<T> to complete with timeout

A generic version of @Kevan's answer above, using Reactive Extensions.

public static Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout, IScheduler scheduler)
{
    return task.ToObservable().Timeout(timeout, scheduler).ToTask();
}

With optional Scheduler:

public static Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout, Scheduler scheduler = null)
{
    return scheduler is null 
       ? task.ToObservable().Timeout(timeout).ToTask() 
       : task.ToObservable().Timeout(timeout, scheduler).ToTask();
}

BTW: When a Timeout happens, a timeout exception will be thrown

How to run python script on terminal (ubuntu)?

Set the PATH as below:


In the csh shell - type setenv PATH "$PATH:/usr/local/bin/python" and press Enter.

In the bash shell (Linux) - type export PATH="$PATH:/usr/local/bin/python" and press Enter.

In the sh or ksh shell - type PATH="$PATH:/usr/local/bin/python" and press Enter.

Note - /usr/local/bin/python is the path of the Python directory


now run as below:

-bash-4.2$ python test.py

Hello, Python!

$(window).width() not the same as media query

Here is an alternative to the methods mentioned earlier that rely on changing something via CSS and reading it via Javascript. This method does not need window.matchMedia or Modernizr. It also needs no extra HTML element. It works by using a HTML pseudo-element to 'store' breakpoint information:

body:after {
  visibility: hidden;
  height: 0;
  font-size: 0;
}

@media (min-width: 20em) {
  body:after {
    content: "mobile";
  }
}

@media (min-width: 48em) {
  body:after {
    content: "tablet";
  }
}

@media (min-width: 64em) {
  body:after {
    content: "desktop";
  }
}

I used body as an example, you can use any HTML element for this. You can add any string or number you want into the content of the pseudo-element. Doesn't have to be 'mobile' and so on.

Now we can read this information from Javascript in the following way:

var breakpoint = window.getComputedStyle(document.querySelector('body'), ':after').getPropertyValue('content').replace(/"/g,'');

if (breakpoint === 'mobile') {
    doSomething();
}

This way we are always sure that the breakpoint information is correct, since it is coming directly from CSS and we don't have to hassle with getting the right screen-width via Javascript.

Expression must have class type

It's a pointer, so instead try:

a->f();

Basically the operator . (used to access an object's fields and methods) is used on objects and references, so:

A a;
a.f();
A& ref = a;
ref.f();

If you have a pointer type, you have to dereference it first to obtain a reference:

A* ptr = new A();
(*ptr).f();
ptr->f();

The a->b notation is usually just a shorthand for (*a).b.

A note on smart pointers

The operator-> can be overloaded, which is notably used by smart pointers. When you're using smart pointers, then you also use -> to refer to the pointed object:

auto ptr = make_unique<A>();
ptr->f();

SQL Error: ORA-00933: SQL command not properly ended

Semicolon ; on the end of command had caused the same error on me.

cmd.CommandText = "INSERT INTO U_USERS_TABLE (USERNAME, PASSWORD, FIRSTNAME, LASTNAME) VALUES ("
                + "'" + txtUsername.Text + "',"
                + "'" + txtPassword.Text + "',"
                + "'" + txtFirstname.Text + "',"
                + "'" + txtLastname.Text + "');"; <== Semicolon in "" is the cause.
                                                      Removing it will be fine.

Hope it helps.

How can I prevent the textarea from stretching beyond his parent DIV element? (google-chrome issue only)

textarea {
width: 700px;  
height: 100px;
resize: none; }

assign your required width and height for the textarea and then use. resize: none ; css property which will disable the textarea's stretchable property.

#pragma mark in Swift?

You can use // MARK:


There has also been discussion that liberal use of class extensions might be a better practice anyway. Since extensions can implement protocols, you can e.g. put all of your table view delegate methods in an extension and group your code at a more semantic level than #pragma mark is capable of.

Git: How to remove file from index without deleting files from any repository

I do not think a Git commit can record an intention like “stop tracking this file, but do not delete it”.

Enacting such an intention will require intervention outside Git in any repositories that merge (or rebase onto) a commit that deletes the file.


Save a Copy, Apply Deletion, Restore

Probably the easiest thing to do is to tell your downstream users to save a copy of the file, pull your deletion, then restore the file. If they are pulling via rebase and are ‘carrying’ modifications to the file, they will get conflicts. To resolve such conflicts, use git rm foo.conf && git rebase --continue (if the conflicting commit has changes besides those to the removed file) or git rebase --skip (if the conflicting commit has only changed to the removed file).

Restore File as Untracked After Pulling a Commit That Deletes It

If they have already pulled your deletion commit, they can still recover the previous version of the file with git show:

git show @{1}:foo.conf >foo.conf

Or with git checkout (per comment by William Pursell; but remember to re-remove it from the index!):

git checkout @{1} -- foo.conf && git rm --cached foo.conf

If they have taken other actions since pulling your deletion (or they are pulling with rebase into a detached HEAD), they may need something other than @{1}. They could use git log -g to find the commit just before they pulled your deletion.


In a comment, you mention that the file you want to “untrack, but keep” is some kind of configuration file that is required for running the software (directly out of a repository).

Keep File as a ‘Default’ and Manually/Automatically Activate It

If it is not completely unacceptable to continue to maintain the configuration file's content in the repository, you might be able to rename the tracked file from (e.g.) foo.conf to foo.conf.default and then instruct your users to cp foo.conf.default foo.conf after applying the rename commit. Or, if the users already use some existing part of the repository (e.g. a script or some other program configured by content in the repository (e.g. Makefile or similar)) to launch/deploy your software, you could incorporate a defaulting mechanism into the launch/deploy process:

test -f foo.conf || test -f foo.conf.default &&
    cp foo.conf.default foo.conf

With such a defaulting mechanism in place, users should be able to pull a commit that renames foo.conf to foo.conf.default without having to do any extra work. Also, you avoid having to manually copy a configuration file if you make additional installations/repositories in the future.

Rewriting History Requires Manual Intervention Anyway…

If it is unacceptable to maintain the content in the repository then you will likely want to completely eradicate it from history with something like git filter-branch --index-filter …. This amounts to rewriting history, which will require manual intervention for each branch/repository (see “Recovering From Upstream Rebase” section in the git rebase manpage). The special treatment required for your configuration file would be just another step that one must perform while recovering from the rewrite:

  1. Save a copy of the configuration file.
  2. Recover from the rewrite.
  3. Restore the configuration file.

Ignore It to Prevent Recurrence

Whatever method you use, you will probably want to include the configuration filename in a .gitignore file in the repository so that no one can inadvertently git add foo.conf again (it is possible, but requires -f/--force). If you have more than one configuration file, you might consider ‘moving’ them all into a single directory and ignoring the whole thing (by ‘moving’ I mean changing where the program expects to find its configuration files, and getting the users (or the launch/deploy mechanism) to copy/move the files to to their new location; you obviously would not want to git mv a file into a directory that you will be ignoring).

What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?

  1. Using homebrew install nvm:

    brew update
    brew install nvm
    source $(brew --prefix nvm)/nvm.sh
    

    Add the last command to the .profile, .bashrc or .zshrc file to not run it again on every terminal start. So for example to add it to the .profile run:

    echo "source $(brew --prefix nvm)/nvm.sh" >> ~/.profile
    

    If you have trouble with installing nvm using brew you can install it manually (see here)

  2. Using nvm install node or iojs (you can install any version you want):

    nvm install 0.10
    # or
    nvm install iojs-1.2.0
    
  3. npm is shipping with node (or iojs), so it will be available after installing node (or iojs). You may want to upgrade it to the latest version:

    $ npm install -g npm@latest
    

    UPD Previous version was npm update -g npm. Thanks to @Metallica for pointing to the correct way (look at the comment bellow).

  4. Using npm install ionic:

    npm install -g ionic
    
  5. What about ngCordova: you can install it using npm or bower. I don't know what variant is more fit for you, it depends on the package manager you want to use for the client side. So I'll describe them both:

    1. Using npm: Go to your project folder and install ng-cordova in it:

      npm install --save ng-cordova
      
    2. Using bower: Install bower:

       npm install -g bower
      

      And then go to your project folder and install ngCordova in it:

       bower install --save ngCordova
      

PS

  1. Some commands may require superuser privilege
  2. Short variant of npm install some_module is npm i some_module

SQL to Query text in access with an apostrophe in it

How about more simply: Select * from tblStudents where [name] = replace(YourName,"'","''")

When to use dynamic vs. static libraries

Others have adequately explained what a static library is, but I'd like to point out some of the caveats of using static libraries, at least on Windows:

  • Singletons: If something needs to be global/static and unique, be very careful about putting it in a static library. If multiple DLLs are linked against that static library they will each get their own copy of the singleton. However, if your application is a single EXE with no custom DLLs, this may not be a problem.

  • Unreferenced code removal: When you link against a static library, only the parts of the static library that are referenced by your DLL/EXE will get linked into your DLL/EXE.

    For example, if mylib.lib contains a.obj and b.obj and your DLL/EXE only references functions or variables from a.obj, the entirety of b.obj will get discarded by the linker. If b.obj contains global/static objects, their constructors and destructors will not get executed. If those constructors/destructors have side effects, you may be disappointed by their absence.

    Likewise, if the static library contains special entrypoints you may need to take care that they are actually included. An example of this in embedded programming (okay, not Windows) would be an interrupt handler that is marked as being at a specific address. You also need to mark the interrupt handler as an entrypoint to make sure it doesn't get discarded.

    Another consequence of this is that a static library may contain object files that are completely unusable due to unresolved references, but it won't cause a linker error until you reference a function or variable from those object files. This may happen long after the library is written.

  • Debug symbols: You may want a separate PDB for each static library, or you may want the debug symbols to be placed in the object files so that they get rolled into the PDB for the DLL/EXE. The Visual C++ documentation explains the necessary options.

  • RTTI: You may end up with multiple type_info objects for the same class if you link a single static library into multiple DLLs. If your program assumes that type_info is "singleton" data and uses &typeid() or type_info::before(), you may get undesirable and surprising results.

How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4

Here I'm basically wrapping a button in a link. The advantage is that you can post to different action methods in the same form.

<a href="Controller/ActionMethod">
    <input type="button" value="Click Me" />
</a>

Adding parameters:

<a href="Controller/ActionMethod?userName=ted">
    <input type="button" value="Click Me" />
</a>

Adding parameters from a non-enumerated Model:

<a href="Controller/[email protected]">
    <input type="button" value="Click Me" />
</a>

You can do the same for an enumerated Model too. You would just have to reference a single entity first. Happy Coding!

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

String myText = "   Hello     World   ";
myText = myText.trim().replace(/ +(?= )/g,'');


// Output: "Hello World"

Why don't self-closing script elements work?

Unlike XML and XHTML, HTML has no knowledge of the self-closing syntax. Browsers that interpret XHTML as HTML don't know that the / character indicates that the tag should be self-closing; instead they interpret it like an empty attribute and the parser still thinks the tag is 'open'.

Just as <script defer> is treated as <script defer="defer">, <script /> is treated as <script /="/">.

Can you control how an SVG's stroke-width is drawn?

Here is a work around for inner bordered rect using symbol and use.

Example: https://jsbin.com/yopemiwame/edit?html,output

SVG:

<svg>
  <symbol id="inner-border-rect">
    <rect class="inner-border" width="100%" height="100%" style="fill:rgb(0,255,255);stroke-width:10;stroke:rgb(0,0,0)">
  </symbol>
  ...
  <use xlink:href="#inner-border-rect" x="?" y="?" width="?" height="?">
</svg>

Note: Make sure to replace the ? in use with real values.

Background: The reason why this works is because symbol establishes a new viewport by replacing symbol with svg and creating an element in the shadow DOM. This svg of the shadow DOM is then linked into your current SVG element. Note that svgs can be nested and every svg creates a new viewport, which clips everything that overlaps, including the overlapping border. For a much more detailed overview of whats going on read this fantastic article by Sara Soueidan.

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

You can add the index directly to your entry config and using a file-loader to load it

module.exports = {

  entry: [
    __dirname + "/index.html",
    .. other js files here
  ],

  module: {
    rules: [
      {
        test: /\.html/, 
        loader: 'file-loader?name=[name].[ext]', 
      },
      .. other loaders
    ]
  }

}

PHP: How to handle <![CDATA[ with SimpleXMLElement?

This is working perfect for me.

$content = simplexml_load_string(
    $raw_xml
    , null
    , LIBXML_NOCDATA
);

Xcode/Simulator: How to run older iOS version?

I was searching for how to do this on a much newer version of xcode than the original question and while the answers here got me where I needed to go, they aren't quite accurate for location anymore. Xcode 11.3.1, you need to go into Preferences -> Components, then select the desired Simulators. You can also select tvOS and watchOS similators from the same window.

Components preference window from Xcode 11.3.1

Using Keras & Tensorflow with AMD GPU

This is an old question, but since I spent the last few weeks trying to figure it out on my own:

  1. OpenCL support for Theano is hit and miss. They added a libgpuarray back-end which appears to still be buggy (i.e., the process runs on the GPU but the answer is wrong--like 8% accuracy on MNIST for a DL model that gets ~95+% accuracy on CPU or nVidia CUDA). Also because ~50-80% of the performance boost on the nVidia stack comes from the CUDNN libraries now, OpenCL will just be left in the dust. (SEE BELOW!) :)
  2. ROCM appears to be very cool, but the documentation (and even a clear declaration of what ROCM is/what it does) is hard to understand. They're doing their best, but they're 4+ years behind. It does NOT NOT NOT work on an RX550 (as of this writing). So don't waste your time (this is where 1 of the weeks went :) ). At first, it appears ROCM is a new addition to the driver set (replacing AMDGPU-Pro, or augmenting it), but it is in fact a kernel module and set of libraries that essentially replace AMDGPU-Pro. (Think of this as the equivalent of Nvidia-381 driver + CUDA some libraries kind of). https://rocm.github.io/dl.html (Honestly I still haven't tested the performance or tried to get it to work with more recent Mesa drivers yet. I will do that sometime.
  3. Add MiOpen to ROCM, and that is essentially CUDNN. They also have some pretty clear guides for migrating. But better yet.
  4. They created "HIP" which is an automagical translator from CUDA/CUDNN to MiOpen. It seems to work pretty well since they lined the API's up directly to be translatable. There are concepts that aren't perfect maps, but in general it looks good.

Now, finally, after 3-4 weeks of trying to figure out OpenCL, etc, I found this tutorial to help you get started quickly. It is a step-by-step for getting hipCaffe up and running. Unlike nVidia though, please ensure you have supported hardware!!!! https://rocm.github.io/hardware.html. Think you can get it working without their supported hardware? Good luck. You've been warned. Once you have ROCM up and running (AND RUN THE VERIFICATION TESTS), here is the hipCaffe tutorial--if you got ROCM up you'll be doing an MNIST validation test within 10 minutes--sweet! https://rocm.github.io/ROCmHipCaffeQuickstart.html

In Python How can I declare a Dynamic Array

Here's a great method I recently found on a different stack overflow post regarding multi-dimensional arrays, but the answer works beautifully for single dimensional arrays as well:

# Create an 8 x 5 matrix of 0's:
w, h = 8, 5;
MyMatrix = [ [0 for x in range( w )] for y in range( h ) ]  

# Create an array of objects:
MyList = [ {} for x in range( n ) ]

I love this because you can specify the contents and size dynamically, in one line!

One more for the road:

# Dynamic content initialization:
MyFunkyArray = [ x * a + b for x in range ( n ) ]

How to get the name of the current Windows user in JavaScript

JavaScript runs in the context of the current HTML document, so it won't be able to determine anything about a current user unless it's in the current page or you do AJAX calls to a server-side script to get more information.

JavaScript will not be able to determine your Windows user name.

How to get xdebug var_dump to show full object/array

Or you can use an alternative:

https://github.com/kint-php/kint

It works with zero set up and has much more features than Xdebug's var_dump anyway. To bypass the nested limit on the fly with Kint, just use

 +d( $variable ); // append `+` to the dump call

How to return Json object from MVC controller to view

You could use AJAX to call this controller action. For example if you are using jQuery you might use the $.ajax() method:

<script type="text/javascript">
    $.ajax({
        url: '@Url.Action("NameOfYourAction")',
        type: 'GET',
        cache: false,
        success: function(result) {
            // you could use the result.values dictionary here
        }
    });
</script>

What are the differences between .so and .dylib on osx?

The Mach-O object file format used by Mac OS X for executables and libraries distinguishes between shared libraries and dynamically loaded modules. Use otool -hv some_file to see the filetype of some_file.

Mach-O shared libraries have the file type MH_DYLIB and carry the extension .dylib. They can be linked against with the usual static linker flags, e.g. -lfoo for libfoo.dylib. They can be created by passing the -dynamiclib flag to the compiler. (-fPIC is the default and needn't be specified.)

Loadable modules are called "bundles" in Mach-O speak. They have the file type MH_BUNDLE. They can carry any extension; the extension .bundle is recommended by Apple, but most ported software uses .so for the sake of compatibility. Typically, you'll use bundles for plug-ins that extend an application; in such situations, the bundle will link against the application binary to gain access to the application’s exported API. They can be created by passing the -bundle flag to the compiler.

Both dylibs and bundles can be dynamically loaded using the dl APIs (e.g. dlopen, dlclose). It is not possible to link against bundles as if they were shared libraries. However, it is possible that a bundle is linked against real shared libraries; those will be loaded automatically when the bundle is loaded.

Historically, the differences were more significant. In Mac OS X 10.0, there was no way to dynamically load libraries. A set of dyld APIs (e.g. NSCreateObjectFileImageFromFile, NSLinkModule) were introduced with 10.1 to load and unload bundles, but they didn't work for dylibs. A dlopen compatibility library that worked with bundles was added in 10.3; in 10.4, dlopen was rewritten to be a native part of dyld and added support for loading (but not unloading) dylibs. Finally, 10.5 added support for using dlclose with dylibs and deprecated the dyld APIs.

On ELF systems like Linux, both use the same file format; any piece of shared code can be used as a library and for dynamic loading.

Finally, be aware that in Mac OS X, "bundle" can also refer to directories with a standardized structure that holds executable code and the resources used by that code. There is some conceptual overlap (particularly with "loadable bundles" like plugins, which generally contain executable code in the form of a Mach-O bundle), but they shouldn't be confused with Mach-O bundles discussed above.

Additional references:

How to change the datetime format in pandas

Below code changes to 'datetime' type and also formats in the given format string. Works well!

df['DOB']=pd.to_datetime(df['DOB'].dt.strftime('%m/%d/%Y'))

Center the nav in Twitter Bootstrap

I prefer this :

<nav class="navbar">
  <div class="hidden-xs hidden-sm" style="position: absolute;left: 50%;margin-left:-56px;width:112px" id="centered-div">
    <!-- this element is on the center of the nav, visible only on -md and -lg -->
    <a></a>
  </div>

  <div class="container-fluid">
    <!-- ...things with your navbar... -->
      <div class="visible-xs visible-sm">
        <!-- this element will be hidden on -md and -lg -->
      </div>
    <!-- ...things with your navbar... -->
  </div>
</nav>

The element is perfectly centered, and will be hidden on some screen sizes (there was no place left on -xs and -sm for me for example). I get the idea from Twitter's actual navbar

Reading settings from app.config or web.config in .NET

As I found the best approach to access application settings variables in a systematic way by making a wrapper class over System.Configuration as below

public class BaseConfiguration
{
    protected static object GetAppSetting(Type expectedType, string key)
    {
        string value = ConfigurationManager.AppSettings.Get(key);
        try
        {
            if (expectedType == typeof(int))
                return int.Parse(value);
            if (expectedType == typeof(string))
                return value;

            throw new Exception("Type not supported.");
        }
        catch (Exception ex)
        {
            throw new Exception(string.Format("Config key:{0} was expected to be of type {1} but was not.",
                key, expectedType), ex);
        }
    }
}

Now we can access needed settings variables by hard coded names using another class as below:

public class ConfigurationSettings:BaseConfiguration
{
    #region App setting

    public static string ApplicationName
    {
        get { return (string)GetAppSetting(typeof(string), "ApplicationName"); }
    }

    public static string MailBccAddress
    {
        get { return (string)GetAppSetting(typeof(string), "MailBccAddress"); }
    }

    public static string DefaultConnection
    {
        get { return (string)GetAppSetting(typeof(string), "DefaultConnection"); }
    }

    #endregion App setting

    #region global setting


    #endregion global setting
}

How to add a new schema to sql server 2008?

In SQL Server 2016 SSMS expand 'DATABASNAME' > expand 'SECURITY' > expand 'SCHEMA' ; right click 'SCHEMAS' from the popup left click 'NEW SCHEMAS...' add the name on the window that opens and add an owner i.e dbo click 'OK' button

Error Code: 2013. Lost connection to MySQL server during query

I ran into this while running a stored proc- which was creating lots of rows into a table in the database. I could see the error come right after the time crossed the 30 sec boundary.

I tried all the suggestions in the other answers. I am sure some of it helped , however- what really made it work for me was switching to SequelPro from Workbench.

I am guessing it was some client side connection that I could not spot in Workbench. Maybe this will help someone else as well ?

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

This occurred when trying to connect to the WCF Service via. the IP e.g. https://111.11.111.1:port/MyService.svc while using a certificate tied to a name e.g. mysite.com.

Switching to the https://mysite.com:port/MyService.svc resolved it.

var.replace is not a function

Did you call your function properly? Ie. is the thing you pass as as a parameter really a string?

Otherwise, I don't see a problem with your code - the example below works as expected

function trim(str) {
    return str.replace(/^\s+|\s+$/g,'');
}


trim('    hello   ');  // --> 'hello'

However, if you call your functoin with something non-string, you will indeed get the error above:

trim({});  // --> TypeError: str.replace is not a function

Angularjs $http.get().then and binding to a list

Actually you get promise on $http.get.

Try to use followed flow:

<li ng-repeat="document in documents" ng-class="IsFiltered(document.Filtered)">
    <span><input type="checkbox" name="docChecked" id="doc_{{document.Id}}" ng-model="document.Filtered" /></span>
    <span>{{document.Name}}</span>
</li>

Where documents is your array.

$scope.documents = [];

$http.get('/Documents/DocumentsList/' + caseId).then(function(result) {
    result.data.forEach(function(val, i) { 
        $scope.documents.push(/* put data here*/);
    });
}, function(error) {
    alert(error.message);
});                       

How to develop Desktop Apps using HTML/CSS/JavaScript?

Awesomium makes it easy to use HTML UI in your C++ or .NET app

Update

My previous answer is now outdated. These days you would be crazy not to look into using Electron for this. Many popular desktop apps have been developed on top of it.

How to Customize a Progress Bar In Android

For using custom drawable:

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360"
android:drawable="@drawable/my_drawable"
android:pivotX="50%"
android:pivotY="50%" />

(add under res/drawable progress.xml). my_drawable may be xml, png

Then in your layout use

<ProgressBar
        android:id="@+id/progressBar"
        android:indeterminateDrawable="@drawable/progress_circle"
...
/>

C++ - Assigning null to a std::string

Literal 0 is of type int and you can't assign int to std::string. Use mValue.clear() or assign an empty string mValue="".

graphing an equation with matplotlib

Your guess is right: the code is trying to evaluate x**3+2*x-4 immediately. Unfortunately you can't really prevent it from doing so. The good news is that in Python, functions are first-class objects, by which I mean that you can treat them like any other variable. So to fix your function, we could do:

import numpy as np  
import matplotlib.pyplot as plt  

def graph(formula, x_range):  
    x = np.array(x_range)  
    y = formula(x)  # <- note now we're calling the function 'formula' with x
    plt.plot(x, y)  
    plt.show()  

def my_formula(x):
    return x**3+2*x-4

graph(my_formula, range(-10, 11))

If you wanted to do it all in one line, you could use what's called a lambda function, which is just a short function without a name where you don't use def or return:

graph(lambda x: x**3+2*x-4, range(-10, 11))

And instead of range, you can look at np.arange (which allows for non-integer increments), and np.linspace, which allows you to specify the start, stop, and the number of points to use.

How many significant digits do floats and doubles have in java?

A 32-bit float has about 7 digits of precision and a 64-bit double has about 16 digits of precision

Long answer:

Floating-point numbers have three components:

  1. A sign bit, to determine if the number is positive or negative.
  2. An exponent, to determine the magnitude of the number.
  3. A fraction, which determines how far between two exponent values the number is. This is sometimes called “the significand, mantissa, or coefficient”

Essentially, this works out to sign * 2^exponent * (1 + fraction). The “size” of the number, it’s exponent, is irrelevant to us, because it only scales the value of the fraction portion. Knowing that log10(n) gives the number of digits of n,† we can determine the precision of a floating point number with log10(largest_possible_fraction). Because each bit in a float stores 2 possibilities, a binary number of n bits can store a number up to 2n - 1 (a total of 2n values where one of the values is zero). This gets a bit hairier, because it turns out that floating point numbers are stored with one less bit of fraction than they can use, because zeroes are represented specially and all non-zero numbers have at least one non-zero binary bit.‡

Combining this, the digits of precision for a floating point number is log10(2n), where n is the number of bits of the floating point number’s fraction. A 32-bit float has 24 bits of fraction for ˜7.22 decimal digits of precision, and a 64-bit double has 53 bits of fraction for ˜15.95 decimal digits of precision.

For more on floating point accuracy, you might want to read about the concept of a machine epsilon.


† For n = 1 at least — for other numbers your formula will look more like ?log10(|n|)? + 1.

‡ “This rule is variously called the leading bit convention, the implicit bit convention, or the hidden bit convention.” (Wikipedia)

How can I kill a process by name instead of PID?

ps aux | grep processname | cut -d' ' -f7 | xargs kill -9 $

Breaking a list into multiple columns in Latex

I've had multenum for "Multi-column enumerated lists" recommended to me, but I've never actually used it myself, yet.

Edit: The syntax doesn't exactly look like you could easily copy+paste lists into the LaTeX code. So, it may not be the best solution for your use case!

Using crontab to execute script every minute and another every 24 hours

This is the format of /etc/crontab:

# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

I recommend copy & pasting that into the top of your crontab file so that you always have the reference handy. RedHat systems are setup that way by default.

To run something every minute:

* * * * * username /var/www/html/a.php

To run something at midnight of every day:

0 0 * * * username /var/www/html/reset.php

You can either include /usr/bin/php in the command to run, or you can make the php scripts directly executable:

chmod +x file.php

Start your php file with a shebang so that your shell knows which interpreter to use:

#!/usr/bin/php
<?php
// your code here

How to create an HTML button that acts like a link?

Type window.location and press enter in your browser console. Then you can get the clear idea what location contains

   hash: ""
   host: "stackoverflow.com"
   hostname: "stackoverflow.com"
   href: "https://stackoverflow.com/questions/2906582/how-to-create-an-html-button- 
   that-acts-like-a-link"
   origin: "https://stackoverflow.com"
   pathname: "/questions/2906582/how-to-create-an-html-button-that-acts-like-a-link"
   port: ""
   protocol: "https:"

You can set any value from here.

So For redirect another page you can set href value with your link.

   window.location.href = your link

In Your Case-

   <button onclick="window.location.href='www.google.com'">Google</button>

Is Visual Studio Community a 30 day trial?

Another answer, when you have a machine where you do not have an internet connection and cannot log in, is here - https://dimitri.janczak.net/2019/07/13/trial-period-reset-of-visual-studio-community-edition/.

The files are on github - https://github.com/1Dimitri/VSCELicense/releases/tag/1.0.

From the readme file:

Original Module Usage

  1. Download/clone this repository

  2. Run PowerShell.exe as an Administrator

  3. Import module:

    Import-Module -Name X:\PATH\TO\VSCELicense
    
    

Usage :

Get Visual Studio Community Edition license expiration date
Get-VSCELicenseExpirationDate -Version VS2019
Set license expiration date to current date + 10 days
Set-VSCELicenseExpirationDate -Version VS2019 -AddDays 10

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

$out.='<option value="'.$key.'">'.$value["name"];

me funciono con esta

"<a  href='javascript:void(0)' onclick='cargar_datos_cliente(\"$row->DSC_EST\")' class='button micro asignar margin-none'>Editar</a>";

navbar color in Twitter Bootstrap

If you are using the LESS or SASS Version of the Bootstrap. The most efficient way is to change the variable name, in the LESS or SASS file.

$navbar-default-color:              #FFFFFF !default;
$navbar-default-bg:                 #36669d !default;
$navbar-default-border:             $navbar-default-bg !default;

This by far the most easiest and the most efficient way to change the Bootstraps Navbar. You need not write overrides, and the code remains clean.

no match for ‘operator<<’ in ‘std::operator

There's only one error:

cout.cpp:26:29: error: no match for ‘operator<<’ in ‘std::operator<< [with _Traits = std::char_traits]((* & std::cout), ((const char*)"my structure ")) << m’

This means that the compiler couldn't find a matching overload for operator<<. The rest of the output is the compiler listing operator<< overloads that didn't match. The third line actually says this:

cout.cpp:26:29: note: candidates are:

add created_at and updated_at fields to mongoose schemas

I actually do this in the back

If all goes well with the updating:

 // All ifs passed successfully. Moving on the Model.save
    Model.lastUpdated = Date.now(); // <------ Now!
    Model.save(function (err, result) {
      if (err) {
        return res.status(500).json({
          title: 'An error occured',
          error: err
        });
      }
      res.status(200).json({
        message: 'Model Updated',
        obj: result
      });
    });

This Activity already has an action bar supplied by the window decor

Or Simply change the @Style/AppTheme

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">

This works for me!

How to get data out of a Node.js http get request

from learnyounode:

var http = require('http')  

http.get(options, function (response) {  
  response.setEncoding('utf8')  
  response.on('data', console.log)  
  response.on('error', console.error)  
})

'options' is the host/path variable

How can I get the username of the logged-in user in Django?

'request.user' has the logged in user.
'request.user.username' will return username of logged in user.

Syntax behind sorted(key=lambda: ...)

The variable left of the : is a parameter name. The use of variable on the right is making use of the parameter.

Means almost exactly the same as:

def some_method(variable):
  return variable[0]

Oracle PL/SQL - Raise User-Defined Exception With Custom SQLERRM

I usually lose track of all of my -20001-type error codes, so I try to consolidate all my application errors into a nice package like such:

SET SERVEROUTPUT ON

CREATE OR REPLACE PACKAGE errors AS
  invalid_foo_err EXCEPTION;
  invalid_foo_num NUMBER := -20123;
  invalid_foo_msg VARCHAR2(32767) := 'Invalid Foo!';
  PRAGMA EXCEPTION_INIT(invalid_foo_err, -20123);  -- can't use var >:O

  illegal_bar_err EXCEPTION;
  illegal_bar_num NUMBER := -20156;
  illegal_bar_msg VARCHAR2(32767) := 'Illegal Bar!';
  PRAGMA EXCEPTION_INIT(illegal_bar_err, -20156);  -- can't use var >:O

  PROCEDURE raise_err(p_err NUMBER, p_msg VARCHAR2 DEFAULT NULL);
END;
/

CREATE OR REPLACE PACKAGE BODY errors AS
  unknown_err EXCEPTION;
  unknown_num NUMBER := -20001;
  unknown_msg VARCHAR2(32767) := 'Unknown Error Specified!';

  PROCEDURE raise_err(p_err NUMBER, p_msg VARCHAR2 DEFAULT NULL) AS
    v_msg VARCHAR2(32767);
  BEGIN
    IF p_err = unknown_num THEN
      v_msg := unknown_msg;
    ELSIF p_err = invalid_foo_num THEN
      v_msg := invalid_foo_msg;
    ELSIF p_err = illegal_bar_num THEN
      v_msg := illegal_bar_msg;
    ELSE
      raise_err(unknown_num, 'USR' || p_err || ': ' || p_msg);
    END IF;

    IF p_msg IS NOT NULL THEN
      v_msg := v_msg || ' - '||p_msg;
    END IF;

    RAISE_APPLICATION_ERROR(p_err, v_msg);
  END;
END;
/

Then call errors.raise_err(errors.invalid_foo_num, 'optional extra text') to use it, like such:

BEGIN
  BEGIN
    errors.raise_err(errors.invalid_foo_num, 'Insufficient Foo-age!');
  EXCEPTION
    WHEN errors.invalid_foo_err THEN
      dbms_output.put_line(SQLERRM);
  END;

  BEGIN
    errors.raise_err(errors.illegal_bar_num, 'Insufficient Bar-age!');
  EXCEPTION
    WHEN errors.illegal_bar_err THEN
      dbms_output.put_line(SQLERRM);
  END;

  BEGIN
    errors.raise_err(-10000, 'This Doesn''t Exist!!');
  EXCEPTION
    WHEN OTHERS THEN
      dbms_output.put_line(SQLERRM);
  END;
END;
/

produces this output:

ORA-20123: Invalid Foo! - Insufficient Foo-age!
ORA-20156: Illegal Bar! - Insufficient Bar-age!
ORA-20001: Unknown Error Specified! - USR-10000: This Doesn't Exist!!

Find the location of a character in string

You can use gregexpr

 gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired")


[[1]]
[1]  4 24
attr(,"match.length")
[1] 1 1
attr(,"useBytes")
[1] TRUE

or perhaps str_locate_all from package stringr which is a wrapper for gregexpr stringi::stri_locate_all (as of stringr version 1.0)

library(stringr)
str_locate_all(pattern ='2', "the2quickbrownfoxeswere2tired")

[[1]]
     start end
[1,]     4   4
[2,]    24  24

note that you could simply use stringi

library(stringi)
stri_locate_all(pattern = '2', "the2quickbrownfoxeswere2tired", fixed = TRUE)

Another option in base R would be something like

lapply(strsplit(x, ''), function(x) which(x == '2'))

should work (given a character vector x)

C++ compile time error: expected identifier before numeric constant

You cannot do this:

vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);

in a class outside of a method.

You can initialize the data members at the point of declaration, but not with () brackets:

class Foo {
    vector<string> name = vector<string>(5);
    vector<int> val{vector<int>(5,0)};
};

Before C++11, you need to declare them first, then initialize them e.g in a contructor

class Foo {
    vector<string> name;
    vector<int> val;
 public:
  Foo() : name(5), val(5,0) {}
};

Local variable referenced before assignment?

When Python parses the body of a function definition and encounters an assignment such as

feed = ...

Python interprets feed as a local variable by default. If you do not wish for it to be a local variable, you must put

global feed

in the function definition. The global statement does not have to be at the beginning of the function definition, but that is where it is usually placed. Wherever it is placed, the global declaration makes feed a global variable everywhere in the function.

Without the global statement, since feed is taken to be a local variable, when Python executes

feed = feed + 1,

Python evaluates the right-hand side first and tries to look up the value of feed. The first time through it finds feed is undefined. Hence the error.

The shortest way to patch up the code is to add global feed to the beginning of onLoadFinished. The nicer way is to use a class:

class Page(object):
    def __init__(self):
        self.feed = 0
    def onLoadFinished(self, result):
        ...
        self.feed += 1

The problem with having functions which mutate global variables is that it makes it harder to grok your code. Functions are no longer isolated units. Their interaction extends to everything that affects or is affected by the global variable. Thus it makes larger programs harder to understand.

By avoiding mutating globals, in the long run your code will be easier to understand, test and maintain.

Access PHP variable in JavaScript

I'm not sure how necessary this is, and it adds a call to getElementById, but if you're really keen on getting inline JavaScript out of your code, you can pass it as an HTML attribute, namely:

<span class="metadata" id="metadata-size-of-widget" title="<?php echo json_encode($size_of_widget) ?>"></span>

And then in your JavaScript:

var size_of_widget = document.getElementById("metadata-size-of-widget").title;

How to select data of a table from another database in SQL Server?

I've used this before to setup a query against another server and db via linked server:

EXEC sp_addlinkedserver @server='PWA_ProjectServer', @srvproduct='',
@provider='SQLOLEDB', @datasrc='SERVERNAME\PWA_ProjectServer'

per the comment above:

select * from [server].[database].[schema].[table]

e.g.

select top 6 * from [PWA_ProjectServer].[PWA_ProjectServer_Reporting].[dbo].[MSP_AdminStatus]

Forking vs. Branching in GitHub

You cannot always make a branch or pull an existing branch and push back to it, because you are not registered as a collaborator for that specific project.

Forking is nothing more than a clone on the GitHub server side:

  • without the possibility to directly push back
  • with fork queue feature added to manage the merge request

You keep a fork in sync with the original project by:

  • adding the original project as a remote
  • fetching regularly from that original project
  • rebase your current development on top of the branch of interest you got updated from that fetch.

The rebase allows you to make sure your changes are straightforward (no merge conflict to handle), making your pulling request that more easy when you want the maintainer of the original project to include your patches in his project.

The goal is really to allow collaboration even though direct participation is not always possible.


The fact that you clone on the GitHub side means you have now two "central" repository ("central" as "visible from several collaborators).
If you can add them directly as collaborator for one project, you don't need to manage another one with a fork.

fork on GitHub

The merge experience would be about the same, but with an extra level of indirection (push first on the fork, then ask for a pull, with the risk of evolutions on the original repo making your fast-forward merges not fast-forward anymore).
That means the correct workflow is to git pull --rebase upstream (rebase your work on top of new commits from upstream), and then git push --force origin, in order to rewrite the history in such a way your own commits are always on top of the commits from the original (upstream) repo.

See also:

How to read first N lines of a file?

What I do is to call the N lines using pandas. I think the performance is not the best, but for example if N=1000:

import pandas as pd
yourfile = pd.read_csv('path/to/your/file.csv',nrows=1000)

How to make a great R reproducible example

You can do this using reprex.

As mt1022 noted, "... good package for producing minimal, reproducible example is "reprex" from tidyverse".

According to Tidyverse:

The goal of "reprex" is to package your problematic code in such a way that other people can run it and feel your pain.

An example is given on tidyverse web site.

library(reprex)
y <- 1:4
mean(y)
reprex() 

I think this is the simplest way to create a reproducible example.

JUnit tests pass in Eclipse but fail in Maven Surefire

I had this problem today testing a method that converted an object that contained a Map to a JSON string. I assume Eclipse and the Maven surefire plugin were using different JREs which had different implementations of HashMap ordering or something, which caused the tests run through Eclipse to pass and the tests run through surefire to fail (assertEquals failed). The easiest solution was to use an implementation of Map that had reliable ordering.

What is 0x10 in decimal?

0x means the number is hexadecimal, or base 16.

0x10 is 16.

laravel collection to array

Use all() method - it's designed to return items of Collection:

/**
 * Get all of the items in the collection.
 *
 * @return array
 */
public function all()
{
    return $this->items;
}

How do you unit test private methods?

Declare them internal, and then use the InternalsVisibleToAttribute to allow your unit test assembly to see them.

What is the closest thing Windows has to fork()?

The following document provides some information on porting code from UNIX to Win32: https://msdn.microsoft.com/en-us/library/y23kc048.aspx

Among other things, it indicates that the process model is quite different between the two systems and recommends consideration of CreateProcess and CreateThread where fork()-like behavior is required.

How to ignore certain files in Git

First create a .gitignore file where we have to store the names of files and directories to be ignored. To ignore a directory;

name_of_directory/

To ignore a file;

name_of_file

We don't need to provide the complete path of the file or directory to be ignored, we just have to provide its name.

If you want to ignore all files with same extention;

*.pyc  #will ignore all files with pyc extention

WPF Check box: Check changed handling

As a checkbox click = a checkbox change the following will also work:

<CheckBox Click="CheckBox_Click" />
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
    // ... do some stuff
}

It has the additional advantage of working when IsThreeState="True" whereas just handling Checked and Unchecked does not.

Mailto: Body formatting

Forget it; this might work with Outlook or maybe even GMail but you won't be able to get this working properly supporting most other E-mail clients out there (and there's a shitton of 'em).

You're better of using a simple PHP script (check out PHPMailer) or use a hosted solution (Google "email form hosted", "free email form hosting" or something similar)

By the way, you are looking for the term "Percent-encoding" (also called url-encoding and Javascript uses encodeUri/encodeUriComponent (make sure you understand the differences!)). You will need to encode a whole lot more than just newlines.

Difference between static and shared libraries?

Simplified:

  • Static linking: one large executable
  • Dynamic linking: a small executable plus one or more library files (.dll files on Windows, .so on Linux, or .dylib on macOS)

SVG: text inside rect

This is not possible. If you want to display text inside a rect element you should put them both in a group with the text element coming after the rect element ( so it appears on top ).

_x000D_
_x000D_
<svg xmlns="http://www.w3.org/2000/svg">_x000D_
  <g>_x000D_
    <rect x="0" y="0" width="100" height="100" fill="red"></rect>_x000D_
    <text x="0" y="50" font-family="Verdana" font-size="35" fill="blue">Hello</text>_x000D_
  </g>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

What is the difference between Swing and AWT?

Swing vs AWT. Basically AWT came first and is a set of heavyweight UI components (meaning they are wrappers for operating system objects) whereas Swing built on top of AWT with a richer set of lightweight components.

Any serious Java UI work is done in Swing not AWT, which was primarily used for applets.

How to configure postgresql for the first time?

If you're running macOS like I am, you may not have the postgres user.

When trying to run sudo -u postgres psql I was getting the error sudo: unknown user: postgres

Luckily there are executables that postgres provides.

createuser -D /var/postgres/var-10-local --superuser --username=nick
createdb --owner=nick

Then I was able to access psql without issues.

psql
psql (10.2)
Type "help" for help.

nick=#

If you're creating a new postgres instance from scratch, here are the steps I took. I used a non-default port so I could run two instances.

mkdir /var/postgres/var-10-local
pg_ctl init -D /var/postgres/var-10-local

Then I edited /var/postgres/var-10-local/postgresql.conf with my preferred port, 5433.

/Applications/Postgres.app/Contents/Versions/10/bin/postgres -D /Users/nick/Library/Application\ Support/Postgres/var-10-local -p 5433

createuser -D /var/postgres/var-10-local --superuser --username=nick --port=5433
createdb --owner=nick --port=5433

Done!

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

Iterating through populated rows

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

This code will:

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

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


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

    Dim rowRange As Range
    Dim colRange As Range

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

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

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

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

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

What does the [Flags] Enum Attribute mean in C#?

Combining answers https://stackoverflow.com/a/8462/1037948 (declaration via bit-shifting) and https://stackoverflow.com/a/9117/1037948 (using combinations in declaration) you can bit-shift previous values rather than using numbers. Not necessarily recommending it, but just pointing out you can.

Rather than:

[Flags]
public enum Options : byte
{
    None    = 0,
    One     = 1 << 0,   // 1
    Two     = 1 << 1,   // 2
    Three   = 1 << 2,   // 4
    Four    = 1 << 3,   // 8

    // combinations
    OneAndTwo = One | Two,
    OneTwoAndThree = One | Two | Three,
}

You can declare

[Flags]
public enum Options : byte
{
    None    = 0,
    One     = 1 << 0,       // 1
    // now that value 1 is available, start shifting from there
    Two     = One << 1,     // 2
    Three   = Two << 1,     // 4
    Four    = Three << 1,   // 8

    // same combinations
    OneAndTwo = One | Two,
    OneTwoAndThree = One | Two | Three,
}

Confirming with LinqPad:

foreach(var e in Enum.GetValues(typeof(Options))) {
    string.Format("{0} = {1}", e.ToString(), (byte)e).Dump();
}

Results in:

None = 0
One = 1
Two = 2
OneAndTwo = 3
Three = 4
OneTwoAndThree = 7
Four = 8

Select All checkboxes using jQuery

Here is a simple way to do this :

Html :

<input type="checkbox" id="selectall" class="css-checkbox " name="selectall"/>Selectall<br>
<input type="checkbox" class="checkboxall" value="checkbox1"/>checkbox1<br>
<input type="checkbox" class="checkboxall" value="checkbox2"/>checkbox2<br>
<input type="checkbox" class="checkboxall" value="checkbox3"/>checkbox3<br>

jquery :

$(document).ready(function(){
$("#selectall").click(function(){
        if(this.checked){
            $('.checkboxall').each(function(){
                $(".checkboxall").prop('checked', true);
            })
        }else{
            $('.checkboxall').each(function(){
                $(".checkboxall").prop('checked', false);
            })
        }
    });
});

Bootstrap 4 img-circle class not working

It's now called rounded-circle as explained here in the BS4 docs

<img src="img/gallery2.JPG" class="rounded-circle">

Demo

What is the difference between old style and new style classes in Python?

Here's a very practical, true/false difference. The only difference between the two versions of the following code is that in the second version Person inherits from object. Other than that, the two versions are identical, but with different results:

  1. Old-style classes

    class Person():
        _names_cache = {}
        def __init__(self,name):
            self.name = name
        def __new__(cls,name):
            return cls._names_cache.setdefault(name,object.__new__(cls,name))
    
    ahmed1 = Person("Ahmed")
    ahmed2 = Person("Ahmed")
    print ahmed1 is ahmed2
    print ahmed1
    print ahmed2
    
    
    >>> False
    <__main__.Person instance at 0xb74acf8c>
    <__main__.Person instance at 0xb74ac6cc>
    >>>
    
    
  2. New-style classes

    class Person(object):
        _names_cache = {}
        def __init__(self,name):
            self.name = name
        def __new__(cls,name):
            return cls._names_cache.setdefault(name,object.__new__(cls,name))
    
    ahmed1 = Person("Ahmed")
    ahmed2 = Person("Ahmed")
    print ahmed2 is ahmed1
    print ahmed1
    print ahmed2
    
    >>> True
    <__main__.Person object at 0xb74ac66c>
    <__main__.Person object at 0xb74ac66c>
    >>>
    

Logging best practices

I don't often develop in asp.net, however when it comes to loggers I think a lot of best practices are universal. Here are some of my random thoughts on logging that I have learned over the years:

Frameworks

  • Use a logger abstraction framework - like slf4j (or roll your own), so that you decouple the logger implementation from your API. I have seen a number of logger frameworks come and go and you are better off being able to adopt a new one without much hassle.
  • Try to find a framework that supports a variety of output formats.
  • Try to find a framework that supports plugins / custom filters.
  • Use a framework that can be configured by external files, so that your customers / consumers can tweak the log output easily so that it can be read by commerical log management applications with ease.
  • Be sure not to go overboard on custom logging levels, otherwise you may not be able to move to different logging frameworks.

Logger Output

  • Try to avoid XML/RSS style logs for logging that could encounter catastrophic failures. This is important because if the power switch is shut off without your logger writing the closing </xxx> tag, your log is broken.
  • Log threads. Otherwise, it can be very difficult to track the flow of your program.
  • If you have to internationalize your logs, you may want to have a developer only log in English (or your language of choice).
  • Sometimes having the option to insert logging statements into SQL queries can be a lifesaver in debugging situations. Such as:
    -- Invoking Class: com.foocorp.foopackage.FooClass:9021
    SELECT * FROM foo;
  • You want class-level logging. You normally don't want static instances of loggers as well - it is not worth the micro-optimization.
  • Marking and categorizing logged exceptions is sometimes useful because not all exceptions are created equal. So knowing a subset of important exceptions a head of time is helpful, if you have a log monitor that needs to send notifications upon critical states.
  • Duplication filters will save your eyesight and hard disk. Do you really want to see the same logging statement repeated 10^10000000 times? Wouldn't it be better just to get a message like: This is my logging statement - Repeated 100 times

Also see this question of mine.

A more useful statusline in vim?

I currently use this statusbar settings:

set laststatus=2
set statusline=\ %f%m%r%h%w\ %=%({%{&ff}\|%{(&fenc==\"\"?&enc:&fenc).((exists(\"+bomb\")\ &&\ &bomb)?\",B\":\"\")}%k\|%Y}%)\ %([%l,%v][%p%%]\ %)

My complete .vimrc file: http://gabriev82.altervista.org/projects/vim-configuration/

Python lookup hostname from IP with 1 second timeout

What you're trying to accomplish is called Reverse DNS lookup.

socket.gethostbyaddr("IP") 
# => (hostname, alias-list, IP)

http://docs.python.org/library/socket.html?highlight=gethostbyaddr#socket.gethostbyaddr

However, for the timeout part I have read about people running into problems with this. I would check out PyDNS or this solution for more advanced treatment.

How to handle iframe in Selenium WebDriver using java

You have to get back out of the Iframe with the following code:

driver.switchTo().frame(driver.findElement(By.id("frameId")));
//do your stuff
driver.switchTo().defaultContent();

hope that helps

Mask output of `The following objects are masked from....:` after calling attach() function

You use attach without detach - every time you do it new call to attach masks objects attached before (they contain the same names). Either use detach or do not use attach at all. Nice discussion and tips are here.

Does WhatsApp offer an open API?

1) It looks possible. This info on Github describes how to create a java program to send a message using the whatsapp encryption protocol from WhisperSystems.

2) No. See the whatsapp security white paper.

3) See #1.

ORA-00972 identifier is too long alias column name

I'm using Argos reporting system as a front end and Oracle in back. I just encountered this error and it was caused by a string with a double quote at the start and a single quote at the end. Replacing the double quote with a single solved the issue.

Where do I find old versions of Android NDK?

If you search Google for the version you want, you should be able to find a download link. For example, Android NDK r5b is available at http://androgeek.info/?p=296

On another note, it might be a good idea to look at why your code doesn't compile against the latest version and fix it.

How do you get/set media volume (not ringtone volume) in Android?

AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
int maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float percent = 0.7f;
int seventyVolume = (int) (maxVolume*percent);
audio.setStreamVolume(AudioManager.STREAM_MUSIC, seventyVolume, 0);

Copy Data from a table in one Database to another separate database

Try this

INSERT INTO dbo.DB1.TempTable
    (COLUMNS)
    SELECT COLUMNS_IN_SAME_ORDER FROM dbo.DB2.TempTable

This will only fail if an item in dbo.DB2.TempTable is in already in dbo.DB1.TempTable.

trim left characters in sql server?

For 'Hello' at the start of the string:

SELECT STUFF('Hello World', 1, 6, '')

This will work for 'Hello' anywhere in the string:

SELECT REPLACE('Hello World', 'Hello ', '')

best way to create object

Or you can use a data file to put many person objects in to a list or array. You do need to use the System.IO for this. And you need a data file which contains all the information about the objects.

A method for it would look something like this:

static void ReadFile()
{
    using(StreamWriter writer = new StreamWriter(@"Data.csv"))
    {
        string line = null;
        line = reader.ReadLine();
        while(null!= (line = reader.ReadLine())
                {
                    string[] values = line.Split(',');
                    string name = values[0];
                    int age = int.Parse(values[1]);
                }
        Person person = new Person(name, age);
    }
}

How to display PDF file in HTML?

1. Browser-native HTML inline embedding:

<embed
    src="http://infolab.stanford.edu/pub/papers/google.pdf#toolbar=0&navpanes=0&scrollbar=0"
    type="application/pdf"
    frameBorder="0"
    scrolling="auto"
    height="100%"
    width="100%"
></embed>
<iframe
    src="http://infolab.stanford.edu/pub/papers/google.pdf#toolbar=0&navpanes=0&scrollbar=0"
    frameBorder="0"
    scrolling="auto"
    height="100%"
    width="100%"
></iframe>

Pro:

  • No PDF file size limitations (even hundreds of MB)
  • It’s the fastest solution

Cons:

  • It doesn’t work on mobile browsers

2. Google Docs Viewer:

<iframe
    src="https://drive.google.com/viewerng/viewer?embedded=true&url=http://infolab.stanford.edu/pub/papers/google.pdf#toolbar=0&scrollbar=0"
    frameBorder="0"
    scrolling="auto"
    height="100%"
    width="100%"
></iframe>

Pro:

  • Works on desktop and mobile browser

Cons:

  • 25MB file limit
  • Requires additional time to download viewer

3. Other solutions to embed PDF:


IMPORTANT NOTE:

Please check the X-Frame-Options HTTP response header. It should be SAMEORIGIN.

X-Frame-Options SAMEORIGIN;

What's the best way to get the last element of an array without deleting it?

Note: For (PHP 7 >= 7.3.0) we can use array_key_last — Gets the last key of an array

array_key_last ( array $array ) : mixed

Ref: http://php.net/manual/en/function.array-key-last.php

Error in file(file, "rt") : cannot open the connection

I came across a solution based on a few answers popped in the thread. (windows 10)

setwd("D:/path to folder where the files are")
directory <- getwd()
myfile<- "a_file_in_the_folder.txt"
filepath=paste0(directory,"/",myfile[1],sep="")
table <- read.table(table, sep = "\t", header=T, row.names = 1, dec=",")

Maintaining Session through Angular.js

You can also try to make service based on window.sessionStorage or window.localStorage to keep state information between page reloads. I use it in the web app which is partially made in AngularJS and page URL is changed in "the old way" for some parts of workflow. Web storage is supported even by IE8. Here is angular-webstorage for convenience.

'git status' shows changed files, but 'git diff' doesn't

I've just run in a similar issue. git diff file showed nothing because I added file to the Git index with some part of its name in uppercase: GeoJSONContainer.js.

Afterwards, I've renamed it to GeoJsonContainer.js and changes stopped being tracked. git diff GeoJsonContainer.js was showing nothing. I had to remove the file from the index with a force flag, and add the file again:

git rm -f GeoJSONContainer.js
git add GeoJSONContainer.js

CGContextDrawImage draws image upside down when passed UIImage.CGImage

I use this Swift 5, pure Core Graphics extension that correctly handles non-zero origins in image rects:

extension CGContext {

    /// Draw `image` flipped vertically, positioned and scaled inside `rect`.
    public func drawFlipped(_ image: CGImage, in rect: CGRect) {
        self.saveGState()
        self.translateBy(x: 0, y: rect.origin.y + rect.height)
        self.scaleBy(x: 1.0, y: -1.0)
        self.draw(image, in: CGRect(origin: CGPoint(x: rect.origin.x, y: 0), size: rect.size))
        self.restoreGState()
    }
}

You can use it exactly like CGContext's regular draw(: in:) method:

ctx.drawFlipped(myImage, in: myRect)

Get the ID of a drawable in ImageView

I answered something like this in another question already, but will change it just a little for this one.

Unfortunately, there is no getImageResource() or getDrawableId(). But, I created a simple workaround by using the ImageView tags.

In onCreate():

imageView0 = (ImageView) findViewById(R.id.imageView0);
imageView1 = (ImageView) findViewById(R.id.imageView1);
imageView2 = (ImageView) findViewById(R.id.imageView2);

imageView0.setTag(R.drawable.apple);
imageView1.setTag(R.drawable.banana);
imageView2.setTag(R.drawable.cereal);

Then, if you like, you can create a simple function to get the drawable id:

private int getDrawableId(ImageView iv) {
    return (Integer) iv.getTag();
}

Too easy.

Docker and securing passwords

Something simply like this will work I guess if it is bash shell.

read -sp "db_password:" password | docker run -itd --name <container_name> --build-arg mysql_db_password=$db_password alpine /bin/bash

Simply read it silently and pass as argument in Docker image. You need to accept the variable as ARG in Dockerfile.

Dynamic variable names in Bash

I want to be able to create a variable name containing the first argument of the command

script.sh file:

#!/usr/bin/env bash
function grep_search() {
  eval $1=$(ls | tail -1)
}

Test:

$ source script.sh
$ grep_search open_box
$ echo $open_box
script.sh

As per help eval:

Execute arguments as a shell command.


You may also use Bash ${!var} indirect expansion, as already mentioned, however it doesn't support retrieving of array indices.


For further read or examples, check BashFAQ/006 about Indirection.

We are not aware of any trick that can duplicate that functionality in POSIX or Bourne shells without eval, which can be difficult to do securely. So, consider this a use at your own risk hack.

However, you should re-consider using indirection as per the following notes.

Normally, in bash scripting, you won't need indirect references at all. Generally, people look at this for a solution when they don't understand or know about Bash Arrays or haven't fully considered other Bash features such as functions.

Putting variable names or any other bash syntax inside parameters is frequently done incorrectly and in inappropriate situations to solve problems that have better solutions. It violates the separation between code and data, and as such puts you on a slippery slope toward bugs and security issues. Indirection can make your code less transparent and harder to follow.

How to assign name for a screen?

The easiest way use screen with name

screen -S 'name' 'application'
  • Ctrl+a, d = exit and leave application open

Return to screen:

screen -r 'name'

for example using lynx with screen

Create screen:

screen -S lynx lynx

Ctrl+a, d =exit

later you can return with:

screen -r lynx

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

As mentioned in other answers, you'll always get the QuotaExceededError in Safari Private Browser Mode on both iOS and OS X when localStorage.setItem (or sessionStorage.setItem) is called.

One solution is to do a try/catch or Modernizr check in each instance of using setItem.

However if you want a shim that simply globally stops this error being thrown, to prevent the rest of your JavaScript from breaking, you can use this:

https://gist.github.com/philfreo/68ea3cd980d72383c951

// Safari, in Private Browsing Mode, looks like it supports localStorage but all calls to setItem
// throw QuotaExceededError. We're going to detect this and just silently drop any calls to setItem
// to avoid the entire page breaking, without having to do a check at each usage of Storage.
if (typeof localStorage === 'object') {
    try {
        localStorage.setItem('localStorage', 1);
        localStorage.removeItem('localStorage');
    } catch (e) {
        Storage.prototype._setItem = Storage.prototype.setItem;
        Storage.prototype.setItem = function() {};
        alert('Your web browser does not support storing settings locally. In Safari, the most common cause of this is using "Private Browsing Mode". Some settings may not save or some features may not work properly for you.');
    }
}

Git merge errors

I had the same issue when switching from a dev branch to master branch. What I did was commit my changes and switch to the master branch. You might have uncommitted changes.

Postgres password authentication fails

pg_hba.conf entry define login methods by IP addresses. You need to show the relevant portion of pg_hba.conf in order to get proper help.

Change this line:

host    all             all             <my-ip-address>/32        md5

To reflect your local network settings. So, if your IP is 192.168.16.78 (class C) with a mask of 255.255.255.0, then put this:

host    all             all             192.168.16.0/24        md5

Make sure your WINDOWS MACHINE is in that network 192.168.16.0 and try again.

Select From all tables - MySQL

why you dont just dump the mysql database but with extension when you run without --single-transaction you will interrupt the connection to other clients:

mysqldump --host=hostname.de --port=0000 --user=username --password=password --single-transaction --skip-add-locks --skip-lock-tables --default-character-set=utf8 datenbankname > mysqlDBBackup.sql 

after that read out the file and search for what you want.... in Strings.....

Simple http post example in Objective-C?

This is what I recently used, and it worked fine for me:

NSString *post = @"key1=val1&key2=val2";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://www.nowhere.com/sendFormHere.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

Originally taken from http://deusty.blogspot.com/2006/11/sending-http-get-and-post-from-cocoa.html, but that blog does not seem to exist anymore.

How to use a FolderBrowserDialog from a WPF application

The advantage of passing an owner handle is that the FolderBrowserDialog will not be modal to that window. This prevents the user from interacting with your main application window while the dialog is active.

Transposing a 1D NumPy array

instead use arr[:,None] to create column vector

App.settings - the Angular way?

I figured out how to do this with InjectionTokens (see example below), and if your project was built using the Angular CLI you can use the environment files found in /environments for static application wide settings like an API endpoint, but depending on your project's requirements you will most likely end up using both since environment files are just object literals, while an injectable configuration using InjectionToken's can use the environment variables and since it's a class can have logic applied to configure it based on other factors in the application, such as initial http request data, subdomain, etc.

Injection Tokens Example

/app/app-config.module.ts

import { NgModule, InjectionToken } from '@angular/core';
import { environment } from '../environments/environment';

export let APP_CONFIG = new InjectionToken<AppConfig>('app.config');

export class AppConfig {
  apiEndpoint: string;
}

export const APP_DI_CONFIG: AppConfig = {
  apiEndpoint: environment.apiEndpoint
};

@NgModule({
  providers: [{
    provide: APP_CONFIG,
    useValue: APP_DI_CONFIG
  }]
})
export class AppConfigModule { }

/app/app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppConfigModule } from './app-config.module';

@NgModule({
  declarations: [
    // ...
  ],
  imports: [
    // ...
    AppConfigModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now you can just DI it into any component, service, etc:

/app/core/auth.service.ts

import { Injectable, Inject } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

import { APP_CONFIG, AppConfig } from '../app-config.module';
import { AuthHttp } from 'angular2-jwt';

@Injectable()
export class AuthService {

  constructor(
    private http: Http,
    private router: Router,
    private authHttp: AuthHttp,
    @Inject(APP_CONFIG) private config: AppConfig
  ) { }

  /**
   * Logs a user into the application.
   * @param payload
   */
  public login(payload: { username: string, password: string }) {
    return this.http
      .post(`${this.config.apiEndpoint}/login`, payload)
      .map((response: Response) => {
        const token = response.json().token;
        sessionStorage.setItem('token', token); // TODO: can this be done else where? interceptor
        return this.handleResponse(response); // TODO:  unset token shouldn't return the token to login
      })
      .catch(this.handleError);
  }

  // ...
}

You can then also type check the config using the exported AppConfig.

ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC

Building slightly off Ben's answer, I added attributes for the ID so I could use labels.

<%: Html.Label("isBlahYes", "Yes")%><%= Html.RadioButtonFor(model => model.blah, true, new { @id = "isBlahYes" })%>
<%: Html.Label("isBlahNo", "No")%><%= Html.RadioButtonFor(model => model.blah, false, new { @id = "isBlahNo" })%>

I hope this helps.

Set cookies for cross origin requests

For express, upgrade your express library to 4.17.1 which is the latest stable version. Then;

In CorsOption: Set origin to your localhost url or your frontend production url and credentials to true e.g

  const corsOptions = {
    origin: config.get("origin"),
    credentials: true,
  };

I set my origin dynamically using config npm module.

Then , in res.cookie:

For localhost: you do not need to set sameSite and secure option at all, you can set httpOnly to true for http cookie to prevent XSS attack and other useful options depending on your use case.

For production environment, you need to set sameSite to none for cross-origin request and secure to true. Remember sameSite works with express latest version only as at now and latest chrome version only set cookie over https, thus the need for secure option.

Here is how I made mine dynamic

 res
    .cookie("access_token", token, {
      httpOnly: true,
      sameSite: app.get("env") === "development" ? true : "none",
      secure: app.get("env") === "development" ? false : true,
    })

How to change Jquery UI Slider handle

You also should set border:none to that css class.

Sort a list of lists with a custom compare function

Since the OP was asking for using a custom compare function (and this is what led me to this question as well), I want to give a solid answer here:

Generally, you want to use the built-in sorted() function which takes a custom comparator as its parameter. We need to pay attention to the fact that in Python 3 the parameter name and semantics have changed.

How the custom comparator works

When providing a custom comparator, it should generally return an integer/float value that follows the following pattern (as with most other programming languages and frameworks):

  • return a negative value (< 0) when the left item should be sorted before the right item
  • return a positive value (> 0) when the left item should be sorted after the right item
  • return 0 when both the left and the right item have the same weight and should be ordered "equally" without precedence

In the particular case of the OP's question, the following custom compare function can be used:

def compare(item1, item2):
    return fitness(item1) - fitness(item2)

Using the minus operation is a nifty trick because it yields to positive values when the weight of left item1 is bigger than the weight of the right item2. Hence item1 will be sorted after item2.

If you want to reverse the sort order, simply reverse the subtraction: return fitness(item2) - fitness(item1)

Calling sorted() in Python 2

sorted(mylist, cmp=compare)

or:

sorted(mylist, cmp=lambda item1, item2: fitness(item1) - fitness(item2))

Calling sorted() in Python 3

from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(compare))

or:

from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(lambda item1, item2: fitness(item1) - fitness(item2)))

Trying to make bootstrap modal wider

If you need this solution for only few types of modals just use style="width:90%" attribute.

example:

div class="modal-dialog modal-lg" style="width:90%"

note: this will change only this particular modal

Writing unit tests in Python: How do I start?

As others already replied, it's late to write unit tests, but not too late. The question is whether your code is testable or not. Indeed, it's not easy to put existing code under test, there is even a book about this: Working Effectively with Legacy Code (see key points or precursor PDF).

Now writing the unit tests or not is your call. You just need to be aware that it could be a tedious task. You might tackle this to learn unit-testing or consider writing acceptance (end-to-end) tests first, and start writing unit tests when you'll change the code or add new feature to the project.

Is it possible to pass parameters programmatically in a Microsoft Access update query?

Many thanks for the information about using the QueryDefs collection! I have been wondering about this for a while.

I did it a different way, without using VBA, by using a table containing the query parameters.

E.g:

SELECT a_table.a_field 
FROM QueryParameters, a_table 
WHERE a_table.a_field BETWEEN QueryParameters.a_field_min 
AND QueryParameters.a_field_max

Where QueryParameters is a table with two fields, a_field_min and a_field_max

It can even be used with GROUP BY, if you include the query parameter fields in the GROUP BY clause, and the FIRST operator on the parameter fields in the HAVING clause.

Want to show/hide div based on dropdown box selection

The core problem is the js errors:

$('#purpose').on('change', function () {
    // if (this.value == '1'); { No semicolon and I used === instead of ==
    if (this.value === '1'){
        $("#business").show();
    } else {
        $("#business").hide();
    }
});
// }); remove

http://jsfiddle.net/Bushwazi/2kGzZ/3/

I had to clean up the html & js...I couldn't help myself.

HTML:

<select id='purpose'>
    <option value="0">Personal use</option>
    <option value="1">Business use</option>
    <option value="2">Passing on to a client</option>
</select>
<form id="business">
    <label for="business">Business Name</label>
    <input type='text' class='text' name='business' value size='20' />
</form>

CSS:

#business {
  display:none;
}

JS:

$('#purpose').on('change', function () {
    if(this.value === "1"){
        $("#business").show();
    } else {
        $("#business").hide();
    }
});

Div vertical scrollbar show

Always : If you always want vertical scrollbar, use overflow-y: scroll;

jsFiddle:

<div style="overflow-y: scroll;">
......
</div>

When needed: If you only want vertical scrollbar when needed, use overflow-y: auto; (You need to specify a height in this case)

jsFiddle:

<div style="overflow-y: auto; height:150px; ">
....
</div>

jQuery .find() on data from .ajax() call is returning "[object Object]" instead of div

Is #result in the response HTML? Try the following. jQuery will still return an empty object if it doesn't find anything.

alert(result.length);

How to check which version of Keras is installed?

Simple command to check keras version:

(py36) C:\WINDOWS\system32>python
Python 3.6.8 |Anaconda custom (64-bit) 

>>> import keras
Using TensorFlow backend.
>>> keras.__version__
'2.2.4'

How to find the size of an int[]?

when u pass any array to some function. u are just passing it's starting address, so for it to work u have to pass it size also for it to work properly. it's the same reason why we pass argc with argv[] in command line arguement.

Looking for a good Python Tree data structure

You can build a nice tree of dicts of dicts like this:

import collections

def Tree():
    return collections.defaultdict(Tree)

It might not be exactly what you want but it's quite useful! Values are saved only in the leaf nodes. Here is an example of how it works:

>>> t = Tree()
>>> t
defaultdict(<function tree at 0x2142f50>, {})
>>> t[1] = "value"
>>> t[2][2] = "another value"
>>> t
defaultdict(<function tree at 0x2142f50>, {1: 'value', 2: defaultdict(<function tree at 0x2142f50>, {2: 'another value'})}) 

For more information take a look at the gist.

How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

Another approach is to use @ExceptionHandler with @ControllerAdvice to centralize all your handlers in the same class, if not you must put the handler methods in every controller you want to manage an exception.

Your handler class:

@ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {

  @ExceptionHandler(MyBadRequestException.class)
  public ResponseEntity<MyError> handleException(MyBadRequestException e) {
    return ResponseEntity
        .badRequest()
        .body(new MyError(HttpStatus.BAD_REQUEST, e.getDescription()));
  }
}

Your custom exception:

public class MyBadRequestException extends RuntimeException {

  private String description;

  public MyBadRequestException(String description) {
    this.description = description;
  }

  public String getDescription() {
    return this.description;
  }
}

Now you can throw exceptions from any of your controllers, and you can define other handlers inside you advice class.

How to decode HTML entities using jQuery?

I think you're confusing the text and HTML methods. Look at this example, if you use an element's inner HTML as text, you'll get decoded HTML tags (second button). But if you use them as HTML, you'll get the HTML formatted view (first button).

<div id="myDiv">
    here is a <b>HTML</b> content.
</div>
<br />
<input value="Write as HTML" type="button" onclick="javascript:$('#resultDiv').html($('#myDiv').html());" />
&nbsp;&nbsp;
<input value="Write as Text" type="button" onclick="javascript:$('#resultDiv').text($('#myDiv').html());" />
<br /><br />
<div id="resultDiv">
    Results here !
</div>

First button writes : here is a HTML content.

Second button writes : here is a <B>HTML</B> content.

By the way, you can see a plug-in that I found in jQuery plugin - HTML decode and encode that encodes and decodes HTML strings.

How to get POSTed JSON in Flask?

Assuming that you have posted valid JSON,

@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
    content = request.json
    print content['uuid']
    # Return data as JSON
    return jsonify(content)

python modify item in list, save back in list

You need to use the enumerate function: python docs

for place, item in enumerate(list):
    if "foo" in item:
        item = replace_all(item, replaceDictionary)
        list[place] = item
        print item

Also, it's a bad idea to use the word list as a variable, due to it being a reserved word in python.

Since you had problems with enumerate, an alternative from the itertools library:

for place, item in itertools.zip(itertools.count(0), list):
    if "foo" in item:
        item = replace_all(item, replaceDictionary)
        list[place] = item
        print item

How do I print the full value of a long string in gdb?

set print elements 0

From the GDB manual:

set print elements number-of-elements
Set a limit on how many elements of an array GDB will print. If GDB is printing a large array, it stops printing after it has printed the number of elements set by the set print elements command. This limit also applies to the display of strings. When GDB starts, this limit is set to 200. Setting number-of-elements to zero means that the printing is unlimited.

Can't use SURF, SIFT in OpenCV

FYI, as of 3.0.0 SIFT and friends are in a contrib repo located at https://github.com/Itseez/opencv_contrib and are not included with opencv by default.

Convert String to Float in Swift

Below will give you an optional Float, stick a ! at the end if you know it to be a Float, or use if/let.

let wageConversion = Float(wage.text)

how to make a full screen div, and prevent size to be changed by content?

Or even just:

<div id="full-size">
  Your contents go here
</div>
html,body{ margin:0; padding:0; height:100%; width:100%; }
#full-size{
  height:100%;
  width:100%;
  overflow:hidden; /* or overflow:auto; if you want scrollbars */
}

(html, body can be set to like.. 95%-99% or some such to account for slight inconsistencies in margins, etc.)