Programs & Examples On #Ready

Calling a function when ng-repeat has finished

var module = angular.module('testApp', [])
    .directive('onFinishRender', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function () {
                    scope.$emit(attr.onFinishRender);
                });
            }
        }
    }
});

Notice that I didn't use .ready() but rather wrapped it in a $timeout. $timeout makes sure it's executed when the ng-repeated elements have REALLY finished rendering (because the $timeout will execute at the end of the current digest cycle -- and it will also call $apply internally, unlike setTimeout). So after the ng-repeat has finished, we use $emit to emit an event to outer scopes (sibling and parent scopes).

And then in your controller, you can catch it with $on:

$scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {
    //you also get the actual event object
    //do stuff, execute functions -- whatever...
});

With html that looks something like this:

<div ng-repeat="item in items" on-finish-render="ngRepeatFinished">
    <div>{{item.name}}}<div>
</div>

Show how many characters remaining in a HTML text box using JavaScript

Just register an Eventhandler on keydown events and check the length of the input field on that function and write it into a separate element.

See the demo.

var maxchar = 160;
var i = document.getElementById("textinput");
var c = document.getElementById("count");
c.innerHTML = maxchar;

i.addEventListener("keydown",count);

function count(e){
    var len =  i.value.length;
    if (len >= maxchar){
       e.preventDefault();
    } else{
       c.innerHTML = maxchar - len-1;   
    }
}
?

You should check the length on your server too, because Javascript might be disabled or the user wants to do something nasty on purpose.

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Placing setOnClickListener in onStart method solved the problem for me. Checkout "Android Lifecycle concept" for further clarification

TypeError: 'builtin_function_or_method' object is not subscriptable

Looks like you typed brackets instead of parenthesis by mistake.

Disable elastic scrolling in Safari

You could check if the scroll-offsets are in the bounds. If they go beyond, set them back.

var scrollX = 0;
var scrollY = 0;
var scrollMinX = 0;
var scrollMinY = 0;
var scrollMaxX = document.body.scrollWidth - window.innerWidth;
var scrollMaxY = document.body.scrollHeight - window.innerHeight;

// make sure that we work with the correct dimensions
window.addEventListener('resize', function () {
  scrollMaxX = document.body.scrollWidth - window.innerWidth;
  scrollMaxY = document.body.scrollHeight - window.innerHeight;
}, false);

// where the magic happens
window.addEventListener('scroll', function () {
  scrollX = window.scrollX;
  scrollY = window.scrollY;

  if (scrollX <= scrollMinX) scrollTo(scrollMinX, window.scrollY);
  if (scrollX >= scrollMaxX) scrollTo(scrollMaxX, window.scrollY);

  if (scrollY <= scrollMinY) scrollTo(window.scrollX, scrollMinY);
  if (scrollY >= scrollMaxY) scrollTo(window.scrollX, scrollMaxY);
}, false);

http://jsfiddle.net/yckart/3YnUM/

How do I collapse a table row in Bootstrap?

You just need to set the table cell padding to zero. Here's a jsfiddle (using Bootstrap 2.3.2) with your code slightly modified:

http://jsfiddle.net/marciowerner/fhjgn7b5/4/

The javascript is optional and only needed if you want to use a cell padding other than zero.

_x000D_
_x000D_
$('.collapse').on('show.bs.collapse', function() {_x000D_
  $(this).parent().removeClass("zeroPadding");_x000D_
});_x000D_
_x000D_
$('.collapse').on('hide.bs.collapse', function() {_x000D_
  $(this).parent().addClass("zeroPadding");_x000D_
});
_x000D_
.zeroPadding {_x000D_
  padding: 0 !important;_x000D_
}
_x000D_
<head>_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
  <script type="text/javascript" src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>_x000D_
  <link rel="stylesheet" type="text/css" href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <table class="table table-bordered table-striped">_x000D_
    <tr>_x000D_
      <td>_x000D_
        <button type="button" class="btn" data-toggle="collapse" data-target="#collapseme">Click to expand</button>_x000D_
      </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td class="zeroPadding">_x000D_
        <div class="collapse out" id="collapseme">Should be collapsed</div>_x000D_
      </td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</body>
_x000D_
_x000D_
_x000D_

What do \t and \b do?

\t is the tab character, and is doing exactly what you're anticipating based on the action of \b - it goes to the next tab stop, then gets decremented, and then goes to the next tab stop (which is in this case the same tab stop, because of the \b.

How do I access the HTTP request header fields via JavaScript?

I would imagine Google grabs some data server-side - remember, when a page loads into your browser that has Google Analytics code within it, your browser makes a request to Google's servers; Google can obtain data in that way as well as through the JavaScript embedded in the page.

Are vectors passed to functions by value or by reference in C++

void foo(vector<int> test)

vector would be passed by value in this.

You have more ways to pass vectors depending on the context:-

1) Pass by reference:- This will let function foo change your contents of the vector. More efficient than pass by value as copying of vector is avoided.

2) Pass by const-reference:- This is efficient as well as reliable when you don't want function to change the contents of the vector.

Setting timezone to UTC (0) in PHP

List of entire available timezones.

$time_zones = array (
  0 => 'Africa/Abidjan',
  1 => 'Africa/Accra',
  2 => 'Africa/Addis_Ababa',
  3 => 'Africa/Algiers',
  4 => 'Africa/Asmara',
  5 => 'Africa/Asmera',
  6 => 'Africa/Bamako',
  7 => 'Africa/Bangui',
  8 => 'Africa/Banjul',
  9 => 'Africa/Bissau',
  10 => 'Africa/Blantyre',
  11 => 'Africa/Brazzaville',
  12 => 'Africa/Bujumbura',
  13 => 'Africa/Cairo',
  14 => 'Africa/Casablanca',
  15 => 'Africa/Ceuta',
  16 => 'Africa/Conakry',
  17 => 'Africa/Dakar',
  18 => 'Africa/Dar_es_Salaam',
  19 => 'Africa/Djibouti',
  20 => 'Africa/Douala',
  21 => 'Africa/El_Aaiun',
  22 => 'Africa/Freetown',
  23 => 'Africa/Gaborone',
  24 => 'Africa/Harare',
  25 => 'Africa/Johannesburg',
  26 => 'Africa/Juba',
  27 => 'Africa/Kampala',
  28 => 'Africa/Khartoum',
  29 => 'Africa/Kigali',
  30 => 'Africa/Kinshasa',
  31 => 'Africa/Lagos',
  32 => 'Africa/Libreville',
  33 => 'Africa/Lome',
  34 => 'Africa/Luanda',
  35 => 'Africa/Lubumbashi',
  36 => 'Africa/Lusaka',
  37 => 'Africa/Malabo',
  38 => 'Africa/Maputo',
  39 => 'Africa/Maseru',
  40 => 'Africa/Mbabane',
  41 => 'Africa/Mogadishu',
  42 => 'Africa/Monrovia',
  43 => 'Africa/Nairobi',
  44 => 'Africa/Ndjamena',
  45 => 'Africa/Niamey',
  46 => 'Africa/Nouakchott',
  47 => 'Africa/Ouagadougou',
  48 => 'Africa/Porto-Novo',
  49 => 'Africa/Sao_Tome',
  50 => 'Africa/Timbuktu',
  51 => 'Africa/Tripoli',
  52 => 'Africa/Tunis',
  53 => 'Africa/Windhoek',
  54 => 'America/Adak',
  55 => 'America/Anchorage',
  56 => 'America/Anguilla',
  57 => 'America/Antigua',
  58 => 'America/Araguaina',
  59 => 'America/Argentina/Buenos_Aires',
  60 => 'America/Argentina/Catamarca',
  61 => 'America/Argentina/ComodRivadavia',
  62 => 'America/Argentina/Cordoba',
  63 => 'America/Argentina/Jujuy',
  64 => 'America/Argentina/La_Rioja',
  65 => 'America/Argentina/Mendoza',
  66 => 'America/Argentina/Rio_Gallegos',
  67 => 'America/Argentina/Salta',
  68 => 'America/Argentina/San_Juan',
  69 => 'America/Argentina/San_Luis',
  70 => 'America/Argentina/Tucuman',
  71 => 'America/Argentina/Ushuaia',
  72 => 'America/Aruba',
  73 => 'America/Asuncion',
  74 => 'America/Atikokan',
  75 => 'America/Atka',
  76 => 'America/Bahia',
  77 => 'America/Bahia_Banderas',
  78 => 'America/Barbados',
  79 => 'America/Belem',
  80 => 'America/Belize',
  81 => 'America/Blanc-Sablon',
  82 => 'America/Boa_Vista',
  83 => 'America/Bogota',
  84 => 'America/Boise',
  85 => 'America/Buenos_Aires',
  86 => 'America/Cambridge_Bay',
  87 => 'America/Campo_Grande',
  88 => 'America/Cancun',
  89 => 'America/Caracas',
  90 => 'America/Catamarca',
  91 => 'America/Cayenne',
  92 => 'America/Cayman',
  93 => 'America/Chicago',
  94 => 'America/Chihuahua',
  95 => 'America/Coral_Harbour',
  96 => 'America/Cordoba',
  97 => 'America/Costa_Rica',
  98 => 'America/Creston',
  99 => 'America/Cuiaba',
  100 => 'America/Curacao',
  101 => 'America/Danmarkshavn',
  102 => 'America/Dawson',
  103 => 'America/Dawson_Creek',
  104 => 'America/Denver',
  105 => 'America/Detroit',
  106 => 'America/Dominica',
  107 => 'America/Edmonton',
  108 => 'America/Eirunepe',
  109 => 'America/El_Salvador',
  110 => 'America/Ensenada',
  111 => 'America/Fort_Nelson',
  112 => 'America/Fort_Wayne',
  113 => 'America/Fortaleza',
  114 => 'America/Glace_Bay',
  115 => 'America/Godthab',
  116 => 'America/Goose_Bay',
  117 => 'America/Grand_Turk',
  118 => 'America/Grenada',
  119 => 'America/Guadeloupe',
  120 => 'America/Guatemala',
  121 => 'America/Guayaquil',
  122 => 'America/Guyana',
  123 => 'America/Halifax',
  124 => 'America/Havana',
  125 => 'America/Hermosillo',
  126 => 'America/Indiana/Indianapolis',
  127 => 'America/Indiana/Knox',
  128 => 'America/Indiana/Marengo',
  129 => 'America/Indiana/Petersburg',
  130 => 'America/Indiana/Tell_City',
  131 => 'America/Indiana/Vevay',
  132 => 'America/Indiana/Vincennes',
  133 => 'America/Indiana/Winamac',
  134 => 'America/Indianapolis',
  135 => 'America/Inuvik',
  136 => 'America/Iqaluit',
  137 => 'America/Jamaica',
  138 => 'America/Jujuy',
  139 => 'America/Juneau',
  140 => 'America/Kentucky/Louisville',
  141 => 'America/Kentucky/Monticello',
  142 => 'America/Knox_IN',
  143 => 'America/Kralendijk',
  144 => 'America/La_Paz',
  145 => 'America/Lima',
  146 => 'America/Los_Angeles',
  147 => 'America/Louisville',
  148 => 'America/Lower_Princes',
  149 => 'America/Maceio',
  150 => 'America/Managua',
  151 => 'America/Manaus',
  152 => 'America/Marigot',
  153 => 'America/Martinique',
  154 => 'America/Matamoros',
  155 => 'America/Mazatlan',
  156 => 'America/Mendoza',
  157 => 'America/Menominee',
  158 => 'America/Merida',
  159 => 'America/Metlakatla',
  160 => 'America/Mexico_City',
  161 => 'America/Miquelon',
  162 => 'America/Moncton',
  163 => 'America/Monterrey',
  164 => 'America/Montevideo',
  165 => 'America/Montreal',
  166 => 'America/Montserrat',
  167 => 'America/Nassau',
  168 => 'America/New_York',
  169 => 'America/Nipigon',
  170 => 'America/Nome',
  171 => 'America/Noronha',
  172 => 'America/North_Dakota/Beulah',
  173 => 'America/North_Dakota/Center',
  174 => 'America/North_Dakota/New_Salem',
  175 => 'America/Ojinaga',
  176 => 'America/Panama',
  177 => 'America/Pangnirtung',
  178 => 'America/Paramaribo',
  179 => 'America/Phoenix',
  180 => 'America/Port-au-Prince',
  181 => 'America/Port_of_Spain',
  182 => 'America/Porto_Acre',
  183 => 'America/Porto_Velho',
  184 => 'America/Puerto_Rico',
  185 => 'America/Rainy_River',
  186 => 'America/Rankin_Inlet',
  187 => 'America/Recife',
  188 => 'America/Regina',
  189 => 'America/Resolute',
  190 => 'America/Rio_Branco',
  191 => 'America/Rosario',
  192 => 'America/Santa_Isabel',
  193 => 'America/Santarem',
  194 => 'America/Santiago',
  195 => 'America/Santo_Domingo',
  196 => 'America/Sao_Paulo',
  197 => 'America/Scoresbysund',
  198 => 'America/Shiprock',
  199 => 'America/Sitka',
  200 => 'America/St_Barthelemy',
  201 => 'America/St_Johns',
  202 => 'America/St_Kitts',
  203 => 'America/St_Lucia',
  204 => 'America/St_Thomas',
  205 => 'America/St_Vincent',
  206 => 'America/Swift_Current',
  207 => 'America/Tegucigalpa',
  208 => 'America/Thule',
  209 => 'America/Thunder_Bay',
  210 => 'America/Tijuana',
  211 => 'America/Toronto',
  212 => 'America/Tortola',
  213 => 'America/Vancouver',
  214 => 'America/Virgin',
  215 => 'America/Whitehorse',
  216 => 'America/Winnipeg',
  217 => 'America/Yakutat',
  218 => 'America/Yellowknife',
  219 => 'Antarctica/Casey',
  220 => 'Antarctica/Davis',
  221 => 'Antarctica/DumontDUrville',
  222 => 'Antarctica/Macquarie',
  223 => 'Antarctica/Mawson',
  224 => 'Antarctica/McMurdo',
  225 => 'Antarctica/Palmer',
  226 => 'Antarctica/Rothera',
  227 => 'Antarctica/South_Pole',
  228 => 'Antarctica/Syowa',
  229 => 'Antarctica/Troll',
  230 => 'Antarctica/Vostok',
  231 => 'Arctic/Longyearbyen',
  232 => 'Asia/Aden',
  233 => 'Asia/Almaty',
  234 => 'Asia/Amman',
  235 => 'Asia/Anadyr',
  236 => 'Asia/Aqtau',
  237 => 'Asia/Aqtobe',
  238 => 'Asia/Ashgabat',
  239 => 'Asia/Ashkhabad',
  240 => 'Asia/Baghdad',
  241 => 'Asia/Bahrain',
  242 => 'Asia/Baku',
  243 => 'Asia/Bangkok',
  244 => 'Asia/Beirut',
  245 => 'Asia/Bishkek',
  246 => 'Asia/Brunei',
  247 => 'Asia/Calcutta',
  248 => 'Asia/Chita',
  249 => 'Asia/Choibalsan',
  250 => 'Asia/Chongqing',
  251 => 'Asia/Chungking',
  252 => 'Asia/Colombo',
  253 => 'Asia/Dacca',
  254 => 'Asia/Damascus',
  255 => 'Asia/Dhaka',
  256 => 'Asia/Dili',
  257 => 'Asia/Dubai',
  258 => 'Asia/Dushanbe',
  259 => 'Asia/Gaza',
  260 => 'Asia/Harbin',
  261 => 'Asia/Hebron',
  262 => 'Asia/Ho_Chi_Minh',
  263 => 'Asia/Hong_Kong',
  264 => 'Asia/Hovd',
  265 => 'Asia/Irkutsk',
  266 => 'Asia/Istanbul',
  267 => 'Asia/Jakarta',
  268 => 'Asia/Jayapura',
  269 => 'Asia/Jerusalem',
  270 => 'Asia/Kabul',
  271 => 'Asia/Kamchatka',
  272 => 'Asia/Karachi',
  273 => 'Asia/Kashgar',
  274 => 'Asia/Kathmandu',
  275 => 'Asia/Katmandu',
  276 => 'Asia/Khandyga',
  277 => 'Asia/Kolkata',
  278 => 'Asia/Krasnoyarsk',
  279 => 'Asia/Kuala_Lumpur',
  280 => 'Asia/Kuching',
  281 => 'Asia/Kuwait',
  282 => 'Asia/Macao',
  283 => 'Asia/Macau',
  284 => 'Asia/Magadan',
  285 => 'Asia/Makassar',
  286 => 'Asia/Manila',
  287 => 'Asia/Muscat',
  288 => 'Asia/Nicosia',
  289 => 'Asia/Novokuznetsk',
  290 => 'Asia/Novosibirsk',
  291 => 'Asia/Omsk',
  292 => 'Asia/Oral',
  293 => 'Asia/Phnom_Penh',
  294 => 'Asia/Pontianak',
  295 => 'Asia/Pyongyang',
  296 => 'Asia/Qatar',
  297 => 'Asia/Qyzylorda',
  298 => 'Asia/Rangoon',
  299 => 'Asia/Riyadh',
  300 => 'Asia/Saigon',
  301 => 'Asia/Sakhalin',
  302 => 'Asia/Samarkand',
  303 => 'Asia/Seoul',
  304 => 'Asia/Shanghai',
  305 => 'Asia/Singapore',
  306 => 'Asia/Srednekolymsk',
  307 => 'Asia/Taipei',
  308 => 'Asia/Tashkent',
  309 => 'Asia/Tbilisi',
  310 => 'Asia/Tehran',
  311 => 'Asia/Tel_Aviv',
  312 => 'Asia/Thimbu',
  313 => 'Asia/Thimphu',
  314 => 'Asia/Tokyo',
  315 => 'Asia/Ujung_Pandang',
  316 => 'Asia/Ulaanbaatar',
  317 => 'Asia/Ulan_Bator',
  318 => 'Asia/Urumqi',
  319 => 'Asia/Ust-Nera',
  320 => 'Asia/Vientiane',
  321 => 'Asia/Vladivostok',
  322 => 'Asia/Yakutsk',
  323 => 'Asia/Yekaterinburg',
  324 => 'Asia/Yerevan',
  325 => 'Atlantic/Azores',
  326 => 'Atlantic/Bermuda',
  327 => 'Atlantic/Canary',
  328 => 'Atlantic/Cape_Verde',
  329 => 'Atlantic/Faeroe',
  330 => 'Atlantic/Faroe',
  331 => 'Atlantic/Jan_Mayen',
  332 => 'Atlantic/Madeira',
  333 => 'Atlantic/Reykjavik',
  334 => 'Atlantic/South_Georgia',
  335 => 'Atlantic/St_Helena',
  336 => 'Atlantic/Stanley',
  337 => 'Australia/ACT',
  338 => 'Australia/Adelaide',
  339 => 'Australia/Brisbane',
  340 => 'Australia/Broken_Hill',
  341 => 'Australia/Canberra',
  342 => 'Australia/Currie',
  343 => 'Australia/Darwin',
  344 => 'Australia/Eucla',
  345 => 'Australia/Hobart',
  346 => 'Australia/LHI',
  347 => 'Australia/Lindeman',
  348 => 'Australia/Lord_Howe',
  349 => 'Australia/Melbourne',
  350 => 'Australia/North',
  351 => 'Australia/NSW',
  352 => 'Australia/Perth',
  353 => 'Australia/Queensland',
  354 => 'Australia/South',
  355 => 'Australia/Sydney',
  356 => 'Australia/Tasmania',
  357 => 'Australia/Victoria',
  358 => 'Australia/West',
  359 => 'Australia/Yancowinna',
  360 => 'Europe/Amsterdam',
  361 => 'Europe/Andorra',
  362 => 'Europe/Athens',
  363 => 'Europe/Belfast',
  364 => 'Europe/Belgrade',
  365 => 'Europe/Berlin',
  366 => 'Europe/Bratislava',
  367 => 'Europe/Brussels',
  368 => 'Europe/Bucharest',
  369 => 'Europe/Budapest',
  370 => 'Europe/Busingen',
  371 => 'Europe/Chisinau',
  372 => 'Europe/Copenhagen',
  373 => 'Europe/Dublin',
  374 => 'Europe/Gibraltar',
  375 => 'Europe/Guernsey',
  376 => 'Europe/Helsinki',
  377 => 'Europe/Isle_of_Man',
  378 => 'Europe/Istanbul',
  379 => 'Europe/Jersey',
  380 => 'Europe/Kaliningrad',
  381 => 'Europe/Kiev',
  382 => 'Europe/Lisbon',
  383 => 'Europe/Ljubljana',
  384 => 'Europe/London',
  385 => 'Europe/Luxembourg',
  386 => 'Europe/Madrid',
  387 => 'Europe/Malta',
  388 => 'Europe/Mariehamn',
  389 => 'Europe/Minsk',
  390 => 'Europe/Monaco',
  391 => 'Europe/Moscow',
  392 => 'Europe/Nicosia',
  393 => 'Europe/Oslo',
  394 => 'Europe/Paris',
  395 => 'Europe/Podgorica',
  396 => 'Europe/Prague',
  397 => 'Europe/Riga',
  398 => 'Europe/Rome',
  399 => 'Europe/Samara',
  400 => 'Europe/San_Marino',
  401 => 'Europe/Sarajevo',
  402 => 'Europe/Simferopol',
  403 => 'Europe/Skopje',
  404 => 'Europe/Sofia',
  405 => 'Europe/Stockholm',
  406 => 'Europe/Tallinn',
  407 => 'Europe/Tirane',
  408 => 'Europe/Tiraspol',
  409 => 'Europe/Uzhgorod',
  410 => 'Europe/Vaduz',
  411 => 'Europe/Vatican',
  412 => 'Europe/Vienna',
  413 => 'Europe/Vilnius',
  414 => 'Europe/Volgograd',
  415 => 'Europe/Warsaw',
  416 => 'Europe/Zagreb',
  417 => 'Europe/Zaporozhye',
  418 => 'Europe/Zurich',
  419 => 'Indian/Antananarivo',
  420 => 'Indian/Chagos',
  421 => 'Indian/Christmas',
  422 => 'Indian/Cocos',
  423 => 'Indian/Comoro',
  424 => 'Indian/Kerguelen',
  425 => 'Indian/Mahe',
  426 => 'Indian/Maldives',
  427 => 'Indian/Mauritius',
  428 => 'Indian/Mayotte',
  429 => 'Indian/Reunion',
  430 => 'Pacific/Apia',
  431 => 'Pacific/Auckland',
  432 => 'Pacific/Bougainville',
  433 => 'Pacific/Chatham',
  434 => 'Pacific/Chuuk',
  435 => 'Pacific/Easter',
  436 => 'Pacific/Efate',
  437 => 'Pacific/Enderbury',
  438 => 'Pacific/Fakaofo',
  439 => 'Pacific/Fiji',
  440 => 'Pacific/Funafuti',
  441 => 'Pacific/Galapagos',
  442 => 'Pacific/Gambier',
  443 => 'Pacific/Guadalcanal',
  444 => 'Pacific/Guam',
  445 => 'Pacific/Honolulu',
  446 => 'Pacific/Johnston',
  447 => 'Pacific/Kiritimati',
  448 => 'Pacific/Kosrae',
  449 => 'Pacific/Kwajalein',
  450 => 'Pacific/Majuro',
  451 => 'Pacific/Marquesas',
  452 => 'Pacific/Midway',
  453 => 'Pacific/Nauru',
  454 => 'Pacific/Niue',
  455 => 'Pacific/Norfolk',
  456 => 'Pacific/Noumea',
  457 => 'Pacific/Pago_Pago',
  458 => 'Pacific/Palau',
  459 => 'Pacific/Pitcairn',
  460 => 'Pacific/Pohnpei',
  461 => 'Pacific/Ponape',
  462 => 'Pacific/Port_Moresby',
  463 => 'Pacific/Rarotonga',
  464 => 'Pacific/Saipan',
  465 => 'Pacific/Samoa',
  466 => 'Pacific/Tahiti',
  467 => 'Pacific/Tarawa',
  468 => 'Pacific/Tongatapu',
  469 => 'Pacific/Truk',
  470 => 'Pacific/Wake',
  471 => 'Pacific/Wallis',
  472 => 'Pacific/Yap',
  473 => 'Brazil/Acre',
  474 => 'Brazil/DeNoronha',
  475 => 'Brazil/East',
  476 => 'Brazil/West',
  477 => 'Canada/Atlantic',
  478 => 'Canada/Central',
  479 => 'Canada/East-Saskatchewan',
  480 => 'Canada/Eastern',
  481 => 'Canada/Mountain',
  482 => 'Canada/Newfoundland',
  483 => 'Canada/Pacific',
  484 => 'Canada/Saskatchewan',
  485 => 'Canada/Yukon',
  486 => 'CET',
  487 => 'Chile/Continental',
  488 => 'Chile/EasterIsland',
  489 => 'CST6CDT',
  490 => 'Cuba',
  491 => 'EET',
  492 => 'Egypt',
  493 => 'Eire',
  494 => 'EST',
  495 => 'EST5EDT',
  496 => 'Etc/GMT',
  497 => 'Etc/GMT+0',
  498 => 'Etc/GMT+1',
  499 => 'Etc/GMT+10',
  500 => 'Etc/GMT+11',
  501 => 'Etc/GMT+12',
  502 => 'Etc/GMT+2',
  503 => 'Etc/GMT+3',
  504 => 'Etc/GMT+4',
  505 => 'Etc/GMT+5',
  506 => 'Etc/GMT+6',
  507 => 'Etc/GMT+7',
  508 => 'Etc/GMT+8',
  509 => 'Etc/GMT+9',
  510 => 'Etc/GMT-0',
  511 => 'Etc/GMT-1',
  512 => 'Etc/GMT-10',
  513 => 'Etc/GMT-11',
  514 => 'Etc/GMT-12',
  515 => 'Etc/GMT-13',
  516 => 'Etc/GMT-14',
  517 => 'Etc/GMT-2',
  518 => 'Etc/GMT-3',
  519 => 'Etc/GMT-4',
  520 => 'Etc/GMT-5',
  521 => 'Etc/GMT-6',
  522 => 'Etc/GMT-7',
  523 => 'Etc/GMT-8',
  524 => 'Etc/GMT-9',
  525 => 'Etc/GMT0',
  526 => 'Etc/Greenwich',
  527 => 'Etc/UCT',
  528 => 'Etc/Universal',
  529 => 'Etc/UTC',
  530 => 'Etc/Zulu',
  531 => 'Factory',
  532 => 'GB',
  533 => 'GB-Eire',
  534 => 'GMT',
  535 => 'GMT+0',
  536 => 'GMT-0',
  537 => 'GMT0',
  538 => 'Greenwich',
  539 => 'Hongkong',
  540 => 'HST',
  541 => 'Iceland',
  542 => 'Iran',
  543 => 'Israel',
  544 => 'Jamaica',
  545 => 'Japan',
  546 => 'Kwajalein',
  547 => 'Libya',
  548 => 'MET',
  549 => 'Mexico/BajaNorte',
  550 => 'Mexico/BajaSur',
  551 => 'Mexico/General',
  552 => 'MST',
  553 => 'MST7MDT',
  554 => 'Navajo',
  555 => 'NZ',
  556 => 'NZ-CHAT',
  557 => 'Poland',
  558 => 'Portugal',
  559 => 'PRC',
  560 => 'PST8PDT',
  561 => 'ROC',
  562 => 'ROK',
  563 => 'Singapore',
  564 => 'Turkey',
  565 => 'UCT',
  566 => 'Universal',
  567 => 'US/Alaska',
  568 => 'US/Aleutian',
  569 => 'US/Arizona',
  570 => 'US/Central',
  571 => 'US/East-Indiana',
  572 => 'US/Eastern',
  573 => 'US/Hawaii',
  574 => 'US/Indiana-Starke',
  575 => 'US/Michigan',
  576 => 'US/Mountain',
  577 => 'US/Pacific',
  578 => 'US/Pacific-New',
  579 => 'US/Samoa',
  580 => 'UTC',
  581 => 'W-SU',
  582 => 'WET',
  583 => 'Zulu',
)

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

The ENTRYPOINT specifies a command that will always be executed when the container starts.

The CMD specifies arguments that will be fed to the ENTRYPOINT.

If you want to make an image dedicated to a specific command you will use ENTRYPOINT ["/path/dedicated_command"]

Otherwise, if you want to make an image for general purpose, you can leave ENTRYPOINT unspecified and use CMD ["/path/dedicated_command"] as you will be able to override the setting by supplying arguments to docker run.

For example, if your Dockerfile is:

FROM debian:wheezy
ENTRYPOINT ["/bin/ping"]
CMD ["localhost"]

Running the image without any argument will ping the localhost:

$ docker run -it test
PING localhost (127.0.0.1): 48 data bytes
56 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.096 ms
56 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.088 ms
56 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.088 ms
^C--- localhost ping statistics ---
3 packets transmitted, 3 packets received, 0% packet loss
round-trip min/avg/max/stddev = 0.088/0.091/0.096/0.000 ms

Now, running the image with an argument will ping the argument:

$ docker run -it test google.com
PING google.com (173.194.45.70): 48 data bytes
56 bytes from 173.194.45.70: icmp_seq=0 ttl=55 time=32.583 ms
56 bytes from 173.194.45.70: icmp_seq=2 ttl=55 time=30.327 ms
56 bytes from 173.194.45.70: icmp_seq=4 ttl=55 time=46.379 ms
^C--- google.com ping statistics ---
5 packets transmitted, 3 packets received, 40% packet loss
round-trip min/avg/max/stddev = 30.327/36.430/46.379/7.095 ms

For comparison, if your Dockerfile is:

FROM debian:wheezy
CMD ["/bin/ping", "localhost"]

Running the image without any argument will ping the localhost:

$ docker run -it test
PING localhost (127.0.0.1): 48 data bytes
56 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.076 ms
56 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.087 ms
56 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.090 ms
^C--- localhost ping statistics ---
3 packets transmitted, 3 packets received, 0% packet loss
round-trip min/avg/max/stddev = 0.076/0.084/0.090/0.000 ms

But running the image with an argument will run the argument:

docker run -it test bash
root@e8bb7249b843:/#

See this article from Brian DeHamer for even more details: https://www.ctl.io/developers/blog/post/dockerfile-entrypoint-vs-cmd/

how concatenate two variables in batch script?

Enabling delayed variable expansion solves you problem, the script produces "hi":

setlocal EnableDelayedExpansion

set var1=A
set var2=B

set AB=hi

set newvar=!%var1%%var2%!

echo %newvar%

Selecting Multiple Values from a Dropdown List in Google Spreadsheet

If the answers must be constrained to Google Sheets, this answer works but it has limitations and is clumsy enough UX that it may be hard to get others to adopt. In trying to solve this problem I've found that, for many applications, Airtable solves this by allowing for multi-select columns and the UX is worlds better.

How does facebook, gmail send the real time notification?

According to a slideshow about Facebook's Messaging system, Facebook uses the comet technology to "push" message to web browsers. Facebook's comet server is built on the open sourced Erlang web server mochiweb.

In the picture below, the phrase "channel clusters" means "comet servers".

System overview

Many other big web sites build their own comet server, because there are differences between every company's need. But build your own comet server on a open source comet server is a good approach.

You can try icomet, a C1000K C++ comet server built with libevent. icomet also provides a JavaScript library, it is easy to use as simple as:

var comet = new iComet({
    sign_url: 'http://' + app_host + '/sign?obj=' + obj,
    sub_url: 'http://' + icomet_host + '/sub',
    callback: function(msg){
        // on server push
        alert(msg.content);
    }
});

icomet supports a wide range of Browsers and OSes, including Safari(iOS, Mac), IEs(Windows), Firefox, Chrome, etc.

Difference between a Structure and a Union

"union" and "struct" are constructs of the C language. Talking of an "OS level" difference between them is inappropriate, since it's the compiler that produces different code if you use one or another keyword.

add id to dynamically created <div>

Not sure if this is the best way, but it works.

if (cartDiv == null) {
    cartDiv = "<div id='unique_id'></div>"; // document.createElement('div');
    document.body.appendChild(cartDiv);
}

A button to start php script, how?

Having 2 files like you suggested would be the easiest solution.

For instance:

2 files solution:

index.html

(.. your html ..)
<form action="script.php" method="get">
  <input type="submit" value="Run me now!">
</form>
(...)

script.php

<?php
  echo "Hello world!"; // Your code here
?>

Single file solution:

index.php

<?php
  if (!empty($_GET['act'])) {
    echo "Hello world!"; //Your code here
  } else {
?>
(.. your html ..)
<form action="index.php" method="get">
  <input type="hidden" name="act" value="run">
  <input type="submit" value="Run me now!">
</form>
<?php
  }
?>

ls command: how can I get a recursive full-path listing, one line per file?

Here is a partial answer that shows the directory names.

ls -mR * | sed -n 's/://p'

Explanation:

ls -mR * lists the full directory names ending in a ':', then lists the files in that directory separately

sed -n 's/://p' finds lines that end in a colon, strip off the colon and print the line

By iterating over the list of directories, we should be able to find the directories as well. Still workin on it. It is a challenge to get the wildcards through xargs.

PHP Warning: Division by zero

Try using

$var = @($val1 / $val2);

Android Studio: Add jar as library?

I have read all the answers here and they all seem to cover old versions of Android Studio!

With a project created with Android Studio 2.2.3 I just needed to create a libs directory under app and place my jar there. I did that with my file manager, no need to click or edit anything in Android Studio.

Why it works? Open Build / Edit Libraries and Dependencies and you will see:

{include=[*.jar], dir=libs}

How do I do pagination in ASP.NET MVC?

Controller

 [HttpGet]
    public async Task<ActionResult> Index(int page =1)
    {
        if (page < 0 || page ==0 )
        {
            page = 1;
        }
        int pageSize = 5;
        int totalPage = 0;
        int totalRecord = 0;
        BusinessLayer bll = new BusinessLayer();
        MatchModel matchmodel = new MatchModel();
        matchmodel.GetMatchList = bll.GetMatchCore(page, pageSize, out totalRecord, out totalPage);
        ViewBag.dbCount = totalPage;
        return View(matchmodel);
    }

BusinessLogic

  public List<Match> GetMatchCore(int page, int pageSize, out int totalRecord, out int totalPage)
    {
        SignalRDataContext db = new SignalRDataContext();
        var query = new List<Match>();
        totalRecord = db.Matches.Count();
        totalPage = (totalRecord / pageSize) + ((totalRecord % pageSize) > 0 ? 1 : 0);
        query = db.Matches.OrderBy(a => a.QuestionID).Skip(((page - 1) * pageSize)).Take(pageSize).ToList();
        return query;
    }

View for displaying total page count

 if (ViewBag.dbCount != null)
    {
        for (int i = 1; i <= ViewBag.dbCount; i++)
        {
            <ul class="pagination">
                <li>@Html.ActionLink(@i.ToString(), "Index", "Grid", new { page = @i },null)</li> 
            </ul>
        }
    }

Convert a bitmap into a byte array

Save the Image to a MemoryStream and then grab the byte array.

http://msdn.microsoft.com/en-us/library/ms142148.aspx

  Byte[] data;

  using (var memoryStream = new MemoryStream())
  {
    image.Save(memoryStream, ImageFormat.Bmp);

    data = memoryStream.ToArray();
  }

using mailto to send email with an attachment

Nope, this is not possible at all. There is no provision for it in the mailto: protocol, and it would be a gaping security hole if it were possible.

The best idea to send a file, but have the client send the E-Mail that I can think of is:

  • Have the user choose a file
  • Upload the file to a server
  • Have the server return a random file name after upload
  • Build a mailto: link that contains the URL to the uploaded file in the message body

How do you remove a specific revision in the git history?

As noted before git-rebase(1) is your friend. Assuming the commits are in your master branch, you would do:

git rebase --onto master~3 master~2 master

Before:

1---2---3---4---5  master

After:

1---2---4'---5' master

From git-rebase(1):

A range of commits could also be removed with rebase. If we have the following situation:

E---F---G---H---I---J  topicA

then the command

git rebase --onto topicA~5 topicA~3 topicA

would result in the removal of commits F and G:

E---H'---I'---J'  topicA

This is useful if F and G were flawed in some way, or should not be part of topicA. Note that the argument to --onto and the parameter can be any valid commit-ish.

"Unable to find remote helper for 'https'" during git clone

found this in 2020 and solution solved the issue with OMZ https://stackoverflow.com/a/13018777/13222154

...
?  ~ cd $ZSH
?  .oh-my-zsh (master) ? git remote -v
origin  https://github.com/ohmyzsh/ohmyzsh.git (fetch)
origin  https://github.com/ohmyzsh/ohmyzsh.git (push)
?  .oh-my-zsh (master) ? date ; omz update
Wed Sep 30 16:16:31 CDT 2020
Updating Oh My Zsh
fatal: Unable to find remote helper for 'https'
There was an error updating. Try again later?
omz::update: restarting the zsh session...

...

    ln "$execdir/git-remote-http" "$execdir/$p" 2>/dev/null || \
    ln -s "git-remote-http" "$execdir/$p" 2>/dev/null || \
    cp "$execdir/git-remote-http" "$execdir/$p" || exit; \
done && \
./check_bindir "z$bindir" "z$execdir" "$bindir/git-add"
?  git-2.9.5 
?  git-2.9.5 
?  git-2.9.5 
?  git-2.9.5 omz update       
Updating Oh My Zsh
remote: Enumerating objects: 296, done.
remote: Counting objects: 100% (296/296), done.
remote: Compressing objects: 100% (115/115), done.
remote: Total 221 (delta 146), reused 179 (delta 105), pack-reused 0
Receiving objects: 100% (221/221), 42.89 KiB | 0 bytes/s, done.
Resolving deltas: 100% (146/146), completed with 52 local objects.
From https://github.com/ohmyzsh/ohmyzsh
 * branch            master     -> FETCH_HEAD
   7deda85..f776af2  master     -> origin/master
Created autostash: 273f6e9

How do I reference the input of an HTML <textarea> control in codebehind?

You need to use runat="server" like this:

<textarea id="TextArea1" cols="20" rows="2" runat="server"></textarea>

You can use the runat=server attribute with any standard HTML element, and later use it from codebehind.

Difference between Activity and FragmentActivity

A FragmentActivity is a subclass of Activity that was built for the Android Support Package.

The FragmentActivity class adds a couple new methods to ensure compatibility with older versions of Android, but other than that, there really isn't much of a difference between the two. Just make sure you change all calls to getLoaderManager() and getFragmentManager() to getSupportLoaderManager() and getSupportFragmentManager() respectively.

How Do I Replace/Change The Heading Text Inside <h3></h3>, Using jquery?

Give an id to h3 like this:

<h3 id="headertag">Featured Offers</h3>

and in the javascript function do this :

document.getElementById("headertag").innerHTML = "Public Offers";

What command shows all of the topics and offsets of partitions in Kafka?

We're using Kafka 2.11 and make use of this tool - kafka-consumer-groups.

$ rpm -qf /bin/kafka-consumer-groups
confluent-kafka-2.11-1.1.1-1.noarch

For example:

$ kafka-consumer-groups --describe --group logstash | grep -E "TOPIC|filebeat"
Note: This will not show information about old Zookeeper-based consumers.
TOPIC            PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID                                     HOST             CLIENT-ID
beats_filebeat   0          20003914484     20003914888     404             logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1   logstash-0
beats_filebeat   1          19992522286     19992522709     423             logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1   logstash-0
beats_filebeat   2          19990597254     19990597637     383             logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1   logstash-0
beats_filebeat   7          19991718707     19991719268     561             logstash-0-YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY /192.168.1.2   logstash-0
beats_filebeat   8          20015611981     20015612509     528             logstash-0-YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY /192.168.1.2   logstash-0
beats_filebeat   5          19990536340     19990541331     4991            logstash-0-ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ /192.168.1.3   logstash-0
beats_filebeat   6          19990728038     19990733086     5048            logstash-0-ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ /192.168.1.3   logstash-0
beats_filebeat   3          19994613945     19994616297     2352            logstash-0-AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA /192.168.1.4   logstash-0
beats_filebeat   4          19990681602     19990684038     2436            logstash-0-AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA /192.168.1.4   logstash-0

Random Tip

NOTE: We use an alias that overloads kafka-consumer-groups like so in our /etc/profile.d/kafka.sh:

alias kafka-consumer-groups="KAFKA_JVM_PERFORMANCE_OPTS=\"-Djava.security.auth.login.config=$HOME/.kafka_client_jaas.conf\"  kafka-consumer-groups --bootstrap-server ${KAFKA_HOSTS} --command-config /etc/kafka/security-enabler.properties"

How to add colored border on cardview?

I solved this by putting two CardViews in a RelativeLayout. One with background of the border color and the other one with the image. (or whatever you wish to use)

Note the margin added to top and start for the second CardView. In my case I decided to use a 2dp thick border.

            <android.support.v7.widget.CardView
            android:id="@+id/user_thumb_rounded_background"
            android:layout_width="36dp"
            android:layout_height="36dp"
            app:cardCornerRadius="18dp"
            android:layout_marginEnd="6dp">

            <ImageView
                android:id="@+id/user_thumb_background"
                android:background="@color/colorPrimaryDark"
                android:layout_width="36dp"
                android:layout_height="36dp" />

        </android.support.v7.widget.CardView>

        <android.support.v7.widget.CardView
            android:id="@+id/user_thumb_rounded"
            android:layout_width="32dp"
            android:layout_height="32dp"
            app:cardCornerRadius="16dp"
            android:layout_marginTop="2dp"
            android:layout_marginStart="2dp"
            android:layout_marginEnd="6dp">

        <ImageView
            android:id="@+id/user_thumb"
            android:src="@drawable/default_profile"
            android:layout_width="32dp"
            android:layout_height="32dp" />

        </android.support.v7.widget.CardView>

ConcurrentModificationException for ArrayList

there should has a concurrent implemention of List interface supporting such operation.

try java.util.concurrent.CopyOnWriteArrayList.class

Customize the Authorization HTTP header

This is a bit dated but there may be others looking for answers to the same question. You should think about what protection spaces make sense for your APIs. For example, you may want to identify and authenticate client application access to your APIs to restrict their use to known, registered client applications. In this case, you can use the Basic authentication scheme with the client identifier as the user-id and client shared secret as the password. You don't need proprietary authentication schemes just clearly identify the one(s) to be used by clients for each protection space. I prefer only one for each protection space but the HTTP standards allow both multiple authentication schemes on each WWW-Authenticate header response and multiple WWW-Authenticate headers in each response; this will be confusing for API clients which options to use. Be consistent and clear then your APIs will be used.

NameError: global name is not defined

Importing the namespace is somewhat cleaner. Imagine you have two different modules you import, both of them with the same method/class. Some bad stuff might happen. I'd dare say it is usually good practice to use:

import module

over

from module import function/class

How to use pip on windows behind an authenticating proxy

I have tried 2 options which both work on my company's NTLM authenticated proxy. Option 1 is to use --proxy http://user:pass@proxyAddress:proxyPort

If you are still having trouble I would suggest installing a proxy authentication service (I use CNTLM) and pointing pip at it ie something like --proxy http://localhost:3128

Map enum in JPA with fixed values?

From JPA 2.1 you can use AttributeConverter.

Create an enumerated class like so:

public enum NodeType {

    ROOT("root-node"),
    BRANCH("branch-node"),
    LEAF("leaf-node");

    private final String code;

    private NodeType(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }
}

And create a converter like this:

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter(autoApply = true)
public class NodeTypeConverter implements AttributeConverter<NodeType, String> {

    @Override
    public String convertToDatabaseColumn(NodeType nodeType) {
        return nodeType.getCode();
    }

    @Override
    public NodeType convertToEntityAttribute(String dbData) {
        for (NodeType nodeType : NodeType.values()) {
            if (nodeType.getCode().equals(dbData)) {
                return nodeType;
            }
        }

        throw new IllegalArgumentException("Unknown database value:" + dbData);
    }
}

On the entity you just need:

@Column(name = "node_type_code")

You luck with @Converter(autoApply = true) may vary by container but tested to work on Wildfly 8.1.0. If it doesn't work you can add @Convert(converter = NodeTypeConverter.class) on the entity class column.

Preserve line breaks in angularjs

It's so simple with CSS (it works, I swear).

.angular-with-newlines {
  white-space: pre;
}
  • Look ma! No extra HTML tags!

C# Double - ToString() formatting with two decimal places but no rounding

I use the following:

double x = Math.Truncate(myDoubleValue * 100) / 100;

For instance:

If the number is 50.947563 and you use the following, the following will happen:

- Math.Truncate(50.947563 * 100) / 100;
- Math.Truncate(5094.7563) / 100;
- 5094 / 100
- 50.94

And there's your answer truncated, now to format the string simply do the following:

string s = string.Format("{0:N2}%", x); // No fear of rounding and takes the default number format

How to leave/exit/deactivate a Python virtualenv

I had the same problem while working on an installer script. I took a look at what the bin/activate_this.py did and reversed it.

Example:

#! /usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys

# Path to virtualenv
venv_path = os.path.join('/home', 'sixdays', '.virtualenvs', 'test32')

# Save old values
old_os_path = os.environ['PATH']
old_sys_path = list(sys.path)
old_sys_prefix = sys.prefix


def deactivate():
    # Change back by setting values to starting values
    os.environ['PATH'] = old_os_path
    sys.prefix = old_sys_prefix
    sys.path[:0] = old_sys_path


# Activate the virtualenvironment
activate_this = os.path.join(venv_path, 'bin/activate_this.py')
execfile(activate_this, dict(__file__=activate_this))


# Print list of pip packages for virtualenv for example purpose
import pip
print str(pip.get_installed_distributions())

# Unload pip module
del pip

# Deactivate/switch back to initial interpreter
deactivate()

# Print list of initial environment pip packages for example purpose
import pip
print str(pip.get_installed_distributions())

I am not 100% sure if it works as intended. I may have missed something completely.

How to show two figures using matplotlib?

Alternatively to calling plt.show() at the end of the script, you can also control each figure separately doing:

f = plt.figure(1)
plt.hist........
............
f.show()

g = plt.figure(2)
plt.hist(........
................
g.show()

raw_input()

In this case you must call raw_input to keep the figures alive. This way you can select dynamically which figures you want to show

Note: raw_input() was renamed to input() in Python 3

How to send a Post body in the HttpClient request in Windows Phone 8?

This depends on what content do you have. You need to initialize your requestMessage.Content property with new HttpContent. For example:

...
// Add request body
if (isPostRequest)
{
    requestMessage.Content = new ByteArrayContent(content);
}
...

where content is your encoded content. You also should include correct Content-type header.

UPDATE:

Oh, it can be even nicer (from this answer):

requestMessage.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", Encoding.UTF8, "application/json");

Cassandra port usage - how are the ports used?

I resolved issue using below steps :

  1. Stop cassandara services

    sudo su -
    systemctl stop datastax-agent
    systemctl stop opscenterd
    systemctl stop app-dse
    
  2. Take backup and Change port from 9042 to 9035

    cp /opt/dse/resources/cassandra/conf/cassandra.yaml /opt/dse/resources/cassandra/conf/bkp_cassandra.yaml
    Vi /opt/dse/resources/cassandra/conf/cassandra.yaml
    native_transport_port: 9035
    
  3. Start Cassandra services

    systemctl start datastax-agent
    systemctl start opscenterd
    systemctl start app-dse
    
  4. create cqlshrc file.

    vi  /root/.cassandra/cqlshrc
    
    [connection]
    hostname = 198.168.1.100
    port = 9035
    

Thanks, Mahesh

Factorial using Recursion in Java

To understand it you have to declare the method in the simplest way possible and martynas nailed it on May 6th post:

int fact(int n) {
    if(n==0) return 1;
    else return n * fact(n-1);
}

read the above implementation and you will understand.

Auto increment primary key in SQL Server Management Studio 2012

You can use the keyword IDENTITY as the data type to the column along with PRIMARY KEY constraint when creating the table.
ex:

StudentNumber IDENTITY(1,1) PRIMARY KEY

In here the first '1' means the starting value and the second '1' is the incrementing value.

How to find index position of an element in a list when contains returns true

benefit.indexOf(map4)

It either returns an index or -1 if the items is not found.

I strongly recommend wrapping the map in some object and use generics if possible.

How using try catch for exception handling is best practice

An exception is a blocking error.

First of all, the best practice should be don't throw exceptions for any kind of error, unless it's a blocking error.

If the error is blocking, then throw the exception. Once the exception is already thrown, there's no need to hide it because it's exceptional; let the user know about it (you should reformat the whole exception to something useful to the user in the UI).

Your job as software developer is to endeavour to prevent an exceptional case where some parameter or runtime situation may end in an exception. That is, exceptions mustn't be muted, but these must be avoided.

For example, if you know that some integer input could come with an invalid format, use int.TryParse instead of int.Parse. There is a lot of cases where you can do this instead of just saying "if it fails, simply throw an exception".

Throwing exceptions is expensive.

If, after all, an exception is thrown, instead of writing the exception to the log once it has been thrown, one of best practices is catching it in a first-chance exception handler. For example:

  • ASP.NET: Global.asax Application_Error
  • Others: AppDomain.FirstChanceException event.

My stance is that local try/catches are better suited for handling special cases where you may translate an exception into another, or when you want to "mute" it for a very, very, very, very, very special case (a library bug throwing an unrelated exception that you need to mute in order to workaround the whole bug).

For the rest of the cases:

  • Try to avoid exceptions.
  • If this isn't possible: first-chance exception handlers.
  • Or use a PostSharp aspect (AOP).

Answering to @thewhiteambit on some comment...

@thewhiteambit said:

Exceptions are not Fatal-Errors, they are Exceptions! Sometimes they are not even Errors, but to consider them Fatal-Errors is completely false understanding of what Exceptions are.

First of all, how an exception can't be even an error?

  • No database connection => exception.
  • Invalid string format to parse to some type => exception
  • Trying to parse JSON and while input isn't actually JSON => exception
  • Argument null while object was expected => exception
  • Some library has a bug => throws an unexpected exception
  • There's a socket connection and it gets disconnected. Then you try to send a message => exception
  • ...

We might list 1k cases of when an exception is thrown, and after all, any of the possible cases will be an error.

An exception is an error, because at the end of the day it is an object which collects diagnostic information -- it has a message and it happens when something goes wrong.

No one would throw an exception when there's no exceptional case. Exceptions should be blocking errors because once they're thrown, if you don't try to fall into the use try/catch and exceptions to implement control flow they mean your application/service will stop the operation that entered into an exceptional case.

Also, I suggest everyone to check the fail-fast paradigm published by Martin Fowler (and written by Jim Shore). This is how I always understood how to handle exceptions, even before I got to this document some time ago.

[...] consider them Fatal-Errors is completely false understanding of what exceptions are.

Usually exceptions cut some operation flow and they're handled to convert them to human-understandable errors. Thus, it seems like an exception actually is a better paradigm to handle error cases and work on them to avoid an application/service complete crash and notify the user/consumer that something went wrong.

More answers about @thewhiteambit concerns

For example in case of a missing Database-Connection the program could exceptionally continue with writing to a local file and send the changes to the Database once it is available again. Your invalid String-To-Number casting could be tried to parse again with language-local interpretation on Exception, like as you try default English language to Parse("1,5") fails and you try it with German interpretation again which is completely fine because we use comma instead of point as separator. You see these Exceptions must not even be blocking, they only need some Exception-handling.

  1. If your app might work offline without persisting data to database, you shouldn't use exceptions, as implementing control flow using try/catch is considered as an anti-pattern. Offline work is a possible use case, so you implement control flow to check if database is accessible or not, you don't wait until it's unreachable.

  2. The parsing thing is also an expected case (not EXCEPTIONAL CASE). If you expect this, you don't use exceptions to do control flow!. You get some metadata from the user to know what his/her culture is and you use formatters for this! .NET supports this and other environments too, and an exception because number formatting must be avoided if you expect a culture-specific usage of your application/service.

An unhandled Exception usually becomes an Error, but Exceptions itself are not codeproject.com/Articles/15921/Not-All-Exceptions-Are-Errors

This article is just an opinion or a point of view of the author.

Since Wikipedia can be also just the opinion of articule author(s), I wouldn't say it's the dogma, but check what Coding by exception article says somewhere in some paragraph:

[...] Using these exceptions to handle specific errors that arise to continue the program is called coding by exception. This anti-pattern can quickly degrade software in performance and maintainability.

It also says somewhere:

Incorrect exception usage

Often coding by exception can lead to further issues in the software with incorrect exception usage. In addition to using exception handling for a unique problem, incorrect exception usage takes this further by executing code even after the exception is raised. This poor programming method resembles the goto method in many software languages but only occurs after a problem in the software is detected.

Honestly, I believe that software can't be developed don't taking use cases seriously. If you know that...

  • Your database can go offline...
  • Some file can be locked...
  • Some formatting might be not supported...
  • Some domain validation might fail...
  • Your app should work in offline mode...
  • whatever use case...

...you won't use exceptions for that. You would support these use cases using regular control flow.

And if some unexpected use case isn't covered, your code will fail fast, because it'll throw an exception. Right, because an exception is an exceptional case.

In the other hand, and finally, sometimes you cover exceptional cases throwing expected exceptions, but you don't throw them to implement control flow. You do it because you want to notify upper layers that you don't support some use case or your code fails to work with some given arguments or environment data/properties.

The R %in% operator

You can use all

> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE

On a similar note, if you want to check whether any of the elements is TRUE you can use any

> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE

How do I get a python program to do nothing?

You can use continue

if condition:
    continue
else:
    #do something

REST API Token-based Authentication

In the web a stateful protocol is based on having a temporary token that is exchanged between a browser and a server (via cookie header or URI rewriting) on every request. That token is usually created on the server end, and it is a piece of opaque data that has a certain time-to-live, and it has the sole purpose of identifying a specific web user agent. That is, the token is temporary, and becomes a STATE that the web server has to maintain on behalf of a client user agent during the duration of that conversation. Therefore, the communication using a token in this way is STATEFUL. And if the conversation between client and server is STATEFUL it is not RESTful.

The username/password (sent on the Authorization header) is usually persisted on the database with the intent of identifying a user. Sometimes the user could mean another application; however, the username/password is NEVER intended to identify a specific web client user agent. The conversation between a web agent and server based on using the username/password in the Authorization header (following the HTTP Basic Authorization) is STATELESS because the web server front-end is not creating or maintaining any STATE information whatsoever on behalf of a specific web client user agent. And based on my understanding of REST, the protocol states clearly that the conversation between clients and server should be STATELESS. Therefore, if we want to have a true RESTful service we should use username/password (Refer to RFC mentioned in my previous post) in the Authorization header for every single call, NOT a sension kind of token (e.g. Session tokens created in web servers, OAuth tokens created in authorization servers, and so on).

I understand that several called REST providers are using tokens like OAuth1 or OAuth2 accept-tokens to be be passed as "Authorization: Bearer " in HTTP headers. However, it appears to me that using those tokens for RESTful services would violate the true STATELESS meaning that REST embraces; because those tokens are temporary piece of data created/maintained on the server side to identify a specific web client user agent for the valid duration of a that web client/server conversation. Therefore, any service that is using those OAuth1/2 tokens should not be called REST if we want to stick to the TRUE meaning of a STATELESS protocol.

Rubens

Android activity life cycle - what are all these methods for?

ANDROID LIFE-CYCLE

There are seven methods that manage the life cycle of an Android application:


Answer for what are all these methods for:

Let us take a simple scenario where knowing in what order these methods are called will help us give a clarity why they are used.

  • Suppose you are using a calculator app. Three methods are called in succession to start the app.

onCreate() - - - > onStart() - - - > onResume()

  • When I am using the calculator app, suddenly a call comes the. The calculator activity goes to the background and another activity say. Dealing with the call comes to the foreground, and now two methods are called in succession.

onPause() - - - > onStop()

  • Now say I finish the conversation on the phone, the calculator activity comes to foreground from the background, so three methods are called in succession.

onRestart() - - - > onStart() - - - > onResume()

  • Finally, say I have finished all the tasks in calculator app, and I want to exit the app. Futher two methods are called in succession.

onStop() - - - > onDestroy()


There are four states an activity can possibly exist:

  • Starting State
  • Running State
  • Paused State
  • Stopped state

Starting state involves:

Creating a new Linux process, allocating new memory for the new UI objects, and setting up the whole screen. So most of the work is involved here.

Running state involves:

It is the activity (state) that is currently on the screen. This state alone handles things such as typing on the screen, and touching & clicking buttons.

Paused state involves:

When an activity is not in the foreground and instead it is in the background, then the activity is said to be in paused state.

Stopped state involves:

A stopped activity can only be bought into foreground by restarting it and also it can be destroyed at any point in time.

The activity manager handles all these states in such a way that the user experience and performance is always at its best even in scenarios where the new activity is added to the existing activities

Trying to get the average of a count resultset

You just can put your query as a subquery:

SELECT avg(count)
  FROM 
    (
    SELECT COUNT (*) AS Count
      FROM Table T
     WHERE T.Update_time =
               (SELECT MAX (B.Update_time )
                  FROM Table B
                 WHERE (B.Id = T.Id))
    GROUP BY T.Grouping
    ) as counts

Edit: I think this should be the same:

SELECT count(*) / count(distinct T.Grouping)
  FROM Table T
 WHERE T.Update_time =
           (SELECT MAX (B.Update_time)
              FROM Table B
             WHERE (B.Id = T.Id))

Egit rejected non-fast-forward

I had this same problem and I was able to fix it. afk5min was right, the problem is the branch that you pulled code from has since changed on the remote repository. Per the standard git practices(http://git-scm.com/book/en/Git-Basics-Working-with-Remotes), you need to (now) merge those changes at the remote repository into your local changes before you can commit. This makes sense, this forces you to take other's changes and merge them into your code, ensuring that your code continues to function with the other changes in place.

Anyway, on to the steps.

  1. Configure the 'fetch' to fetch the branch you originally pulled from.

  2. Fetch the remote branch.

  3. Merge that remote branch onto your local branch.

  4. Commit the (merge) change in your local repo.

  5. Push the change to the remote repo.

In detail...

  1. In eclipse, open the view 'Git Repositories'.

  2. Ensure you see your local repository and can see the remote repository as a subfolder. In my version, it's called Remotes, and then I can see the remote project within that.

  3. Look for the green arrow pointing to the left, this is the 'fetch' arrow. Right click and select 'Configure Fetch'.

  4. You should see the URI, ensure that it points to the remote repository.

  5. Look in the ref mappings section of the pop-up. Mine was empty. This will indicate which remote references you want to fetch. Click 'Add'.

  6. Type in the branch name you need to fetch from the remote repository. Mine was 'master' (btw, a dropdown here would be great!!, for now, you have to type it). Continue through the pop-up, eventually clicking 'Finish'.

  7. Click 'Save and Fetch'. This will fetch that remote reference.

  8. Look in the 'Branches' folder of your local repository. You should now see that remote branch in the remote folder. Again, I see 'master'.

  9. Right-Click on the local branch in the 'Local' folder of 'Branches', which is named 'master'. Select 'Merge', and then select the remote branch, which is named 'origin/master'.

  10. Process through the merge.

  11. Commit any changes to your local repository.

  12. Push your changes to the remote repository.

  13. Go have a tasty beverage, congratulating yourself. Take the rest of the day off.

Change color and appearance of drop down arrow

Try changing the color of your "border-top" attribute to white

How to do a regular expression replace in MySQL?

With MySQL 8.0+ you could use natively REGEXP_REPLACE function.

12.5.2 Regular Expressions:

REGEXP_REPLACE(expr, pat, repl[, pos[, occurrence[, match_type]]])

Replaces occurrences in the string expr that match the regular expression specified by the pattern pat with the replacement string repl, and returns the resulting string. If expr, pat, or repl is NULL, the return value is NULL.

and Regular expression support:

Previously, MySQL used the Henry Spencer regular expression library to support regular expression operators (REGEXP, RLIKE).

Regular expression support has been reimplemented using International Components for Unicode (ICU), which provides full Unicode support and is multibyte safe. The REGEXP_LIKE() function performs regular expression matching in the manner of the REGEXP and RLIKE operators, which now are synonyms for that function. In addition, the REGEXP_INSTR(), REGEXP_REPLACE(), and REGEXP_SUBSTR() functions are available to find match positions and perform substring substitution and extraction, respectively.

SELECT REGEXP_REPLACE('Stackoverflow','[A-Zf]','-',1,0,'c'); 
-- Output:
-tackover-low

DBFiddle Demo

How to get instance variables in Python?

Every object has a __dict__ variable containing all the variables and its values in it.

Try this

>>> hi_obj = hi()
>>> hi_obj.__dict__.keys()

How to include a child object's child object in Entity Framework 5

A good example of using the Generic Repository pattern and implementing a generic solution for this might look something like this.

public IList<TEntity> Get<TParamater>(IList<Expression<Func<TEntity, TParamater>>> includeProperties)

{

    foreach (var include in includeProperties)
     {

        query = query.Include(include);
     }

        return query.ToList();
}

Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship

You could also disable the cascade delete convention in global scope of your application by doing this:

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>()
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>()

How to check if an array value exists?

Well, first off an associative array can only have a key defined once, so this array would never exist. Otherwise, just use in_array() to determine if that specific array element is in an array of possible solutions.

Count the number of items in my array list

The only thing I would add to Mark Peters solution is that you don't need to iterate over the ArrayList - you should be able to use the addAll(Collection) method on the Set. You only need to iterate over the entire list to do the summations.

Calculate the mean by group

We already have tons of options to get mean by group, adding one more from mosaic package.

mosaic::mean(speed~dive, data = df)
#dive1 dive2 
#0.579 0.440 

This returns a named numeric vector, if needed a dataframe we can wrap it in stack

stack(mosaic::mean(speed~dive, data = df))

#  values   ind
#1  0.579 dive1
#2  0.440 dive2

data

set.seed(123)
df <- data.frame(dive=factor(sample(c("dive1","dive2"),10,replace=TRUE)),
                 speed=runif(10))

How to resolve the error on 'react-native start'

The solution is simple, but temporary...

Note that if you run an npm install or a yarn install you need to change the code again!

So, how can we run this automatically?

Permanent Solution

To do this "automagically" after installing your node modules, you can use patch-package.

  1. Fix the metro-config file, solving the error:

The file appears in \node_modules\metro-config\src\defaults\blacklist.js.

Edit from:

var sharedBlacklist = [
  /node_modules[/\\]react[/\\]dist[/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

To:

var sharedBlacklist = [
  /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];
  1. Then, generate a permanent patch file:

npx patch-package metro-config

  1. In your package.json trigger the patch:
"scripts": {
+  "postinstall": "npx patch-package"
}

All done! Now this patch will be made at every npm install / yarn install.

Thanks to https://github.com/ds300/patch-package

Changing button color programmatically

Probably best to change the className:

document.getElementById("button").className = 'button_color';

Then you add a buton style to the CSS where you can set the background color and anything else.

Strip HTML from Text JavaScript

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

var div = document.getElementsByTagName('div');
for (var i=0; i<div.length; i++) {
    div[i].insertAdjacentHTML('afterend', div[i].innerHTML);
    document.body.removeChild(div[i]);
}

Error: Could not find or load main class in intelliJ IDE

File > Project Structure > Modules > Mark "src" folder as sources. This should fix the problem. Also check latest language is selected so that you don't have to change code or do any config changes. enter image description here

jQuery UI dialog positioning

Thanks to some answers above, I experimented and ultimately found that all you need to do is edit the "position" attribute in the Modal Dialog's definition:

position:['middle',20],

JQuery had no problems with the "middle" text for the horizontal "X" value and my dialog popped up in the middle, 20px down from the top.

I heart JQuery.

How to use z-index in svg elements?

Push SVG element to last, so that its z-index will be in top. In SVG, there s no property called z-index. try below javascript to bring the element to top.

var Target = document.getElementById(event.currentTarget.id);
var svg = document.getElementById("SVGEditor");
svg.insertBefore(Target, svg.lastChild.nextSibling);

Target: Is an element for which we need to bring it to top svg: Is the container of elements

Which is the best library for XML parsing in java

Actually Java supports 4 methods to parse XML out of the box:

DOM Parser/Builder: The whole XML structure is loaded into memory and you can use the well known DOM methods to work with it. DOM also allows you to write to the document with Xslt transformations. Example:

public static void parse() throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setIgnoringElementContentWhitespace(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    File file = new File("test.xml");
    Document doc = builder.parse(file);
    // Do something with the document here.
}

SAX Parser: Solely to read a XML document. The Sax parser runs through the document and calls callback methods of the user. There are methods for start/end of a document, element and so on. They're defined in org.xml.sax.ContentHandler and there's an empty helper class DefaultHandler.

public static void parse() throws ParserConfigurationException, SAXException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    SAXParser saxParser = factory.newSAXParser();
    File file = new File("test.xml");
    saxParser.parse(file, new ElementHandler());    // specify handler
}

StAx Reader/Writer: This works with a datastream oriented interface. The program asks for the next element when it's ready just like a cursor/iterator. You can also create documents with it. Read document:

public static void parse() throws XMLStreamException, IOException {
    try (FileInputStream fis = new FileInputStream("test.xml")) {
        XMLInputFactory xmlInFact = XMLInputFactory.newInstance();
        XMLStreamReader reader = xmlInFact.createXMLStreamReader(fis);
        while(reader.hasNext()) {
            reader.next(); // do something here
        }
    }
}

Write document:

public static void parse() throws XMLStreamException, IOException {
    try (FileOutputStream fos = new FileOutputStream("test.xml")){
        XMLOutputFactory xmlOutFact = XMLOutputFactory.newInstance();
        XMLStreamWriter writer = xmlOutFact.createXMLStreamWriter(fos);
        writer.writeStartDocument();
        writer.writeStartElement("test");
        // write stuff
        writer.writeEndElement();
    }
}

JAXB: The newest implementation to read XML documents: Is part of Java 6 in v2. This allows us to serialize java objects from a document. You read the document with a class that implements a interface to javax.xml.bind.Unmarshaller (you get a class for this from JAXBContext.newInstance). The context has to be initialized with the used classes, but you just have to specify the root classes and don't have to worry about static referenced classes. You use annotations to specify which classes should be elements (@XmlRootElement) and which fields are elements(@XmlElement) or attributes (@XmlAttribute, what a surprise!)

public static void parse() throws JAXBException, IOException {
    try (FileInputStream adrFile = new FileInputStream("test")) {
        JAXBContext ctx = JAXBContext.newInstance(RootElementClass.class);
        Unmarshaller um = ctx.createUnmarshaller();
        RootElementClass rootElement = (RootElementClass) um.unmarshal(adrFile);
    }
}

Write document:

public static void parse(RootElementClass out) throws IOException, JAXBException {
    try (FileOutputStream adrFile = new FileOutputStream("test.xml")) {
        JAXBContext ctx = JAXBContext.newInstance(RootElementClass.class);
        Marshaller ma = ctx.createMarshaller();
        ma.marshal(out, adrFile);
    }
}

Examples shamelessly copied from some old lecture slides ;-)

Edit: About "which API should I use?". Well it depends - not all APIs have the same capabilities as you see, but if you have control over the classes you use to map the XML document JAXB is my personal favorite, really elegant and simple solution (though I haven't used it for really large documents, it could get a bit complex). SAX is pretty easy to use too and just stay away from DOM if you don't have a really good reason to use it - old, clunky API in my opinion. I don't think there are any modern 3rd party libraries that feature anything especially useful that's missing from the STL and the standard libraries have the usual advantages of being extremely well tested, documented and stable.

How to access session variables from any class in ASP.NET?

(Updated for completeness)
You can access session variables from any page or control using Session["loginId"] and from any class (e.g. from inside a class library), using System.Web.HttpContext.Current.Session["loginId"].

But please read on for my original answer...


I always use a wrapper class around the ASP.NET session to simplify access to session variables:

public class MySession
{
    // private constructor
    private MySession()
    {
      Property1 = "default value";
    }

    // Gets the current session.
    public static MySession Current
    {
      get
      {
        MySession session =
          (MySession)HttpContext.Current.Session["__MySession__"];
        if (session == null)
        {
          session = new MySession();
          HttpContext.Current.Session["__MySession__"] = session;
        }
        return session;
      }
    }

    // **** add your session properties here, e.g like this:
    public string Property1 { get; set; }
    public DateTime MyDate { get; set; }
    public int LoginId { get; set; }
}

This class stores one instance of itself in the ASP.NET session and allows you to access your session properties in a type-safe way from any class, e.g like this:

int loginId = MySession.Current.LoginId;

string property1 = MySession.Current.Property1;
MySession.Current.Property1 = newValue;

DateTime myDate = MySession.Current.MyDate;
MySession.Current.MyDate = DateTime.Now;

This approach has several advantages:

  • it saves you from a lot of type-casting
  • you don't have to use hard-coded session keys throughout your application (e.g. Session["loginId"]
  • you can document your session items by adding XML doc comments on the properties of MySession
  • you can initialize your session variables with default values (e.g. assuring they are not null)

Disable Tensorflow debugging information

I have had this problem as well (on tensorflow-0.10.0rc0), but could not fix the excessive nose tests logging problem via the suggested answers.

I managed to solve this by probing directly into the tensorflow logger. Not the most correct of fixes, but works great and only pollutes the test files which directly or indirectly import tensorflow:

# Place this before directly or indirectly importing tensorflow
import logging
logging.getLogger("tensorflow").setLevel(logging.WARNING)

How to cast Object to boolean?

Assuming that yourObject.toString() returns "true" or "false", you can try

boolean b = Boolean.valueOf(yourObject.toString())

C++ Redefinition Header Files (winsock2.h)

In my project (I use VS 2008 SP1) works next solution:

Header file:

//myclass.h
#pragma once
#define _WINSOCKAPI_
#include <windows.h>

Cpp class:

//myclass.cpp
#include "Util.h"
#include "winsock2class.h"
#pragma comment(lib, "Ws2_32.lib")

where #include "winsock2class.h" mean class which implemented winsock2.h :

//winsock2class.h
#include <winsock2.h>
#include <windows.h>
#pragma comment(lib, "Ws2_32.lib")

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

What is the difference between declarative and imperative paradigm in programming?

From my understanding, both terms have roots in philosophy, there are declarative and imperative kinds of knowledge. Declarative knowledge are assertions of truth, statements of fact like math axioms. It tells you something. Imperative, or procedural knowledge, tells you step by step how to arrive at something. That's what the definition of an algorithm essentially is. If you would, compare a computer programming language with the English language. Declarative sentences state something. A boring example, but here's a declarative way of displaying whether two numbers are equal to each other, in Java:

public static void main(String[] args)
{
    System.out.print("4 = 4.");
}

Imperative sentences in English, on the other hand, give a command or make some sort of request. Imperative programming, then, is just a list of commands (do this, do that). Here's an imperative way of displaying whether two numbers are equal to each other or not while accepting user input, in Java:

private static Scanner input;    

public static void main(String[] args) 
{
    input = new Scanner(System.in);
    System.out.println();
    System.out.print("Enter an integer value for x: ");
    int x = input.nextInt();
    System.out.print("Enter an integer value for y: ");        
    int y = input.nextInt();

    System.out.println();
    System.out.printf("%d == %d? %s\n", x, y, x == y);
}

Essentially, declarative knowledge skips over certain elements to form a layer of abstraction over those elements. Declarative programming does the same.

Saving a Excel File into .txt format without quotes

I see this question is already answered, but wanted to offer an alternative in case someone else finds this later.

Depending on the required delimiter, it is possible to do this without writing any code. The original question does not give details on the desired output type but here is an alternative:

PRN File Type

The easiest option is to save the file as a "Formatted Text (Space Delimited)" type. The VBA code line would look similar to this:

ActiveWorkbook.SaveAs FileName:=myFileName, FileFormat:=xlTextPrinter, CreateBackup:=False

In Excel 2007, this will annoyingly put a .prn file extension on the end of the filename, but it can be changed to .txt by renaming manually.

In Excel 2010, you can specify any file extension you want in the Save As dialog.

One important thing to note: the number of delimiters used in the text file is related to the width of the Excel column.

Observe:

Excel Screenshot

Becomes:

Text Screenshot

try/catch blocks with async/await

Alternative Similar To Error Handling In Golang

Because async/await uses promises under the hood, you can write a little utility function like this:

export function catchEm(promise) {
  return promise.then(data => [null, data])
    .catch(err => [err]);
}

Then import it whenever you need to catch some errors, and wrap your async function which returns a promise with it.

import catchEm from 'utility';

async performAsyncWork() {
  const [err, data] = await catchEm(asyncFunction(arg1, arg2));
  if (err) {
    // handle errors
  } else {
    // use data
  }
}

What is move semantics?

If you are really interested in a good, in-depth explanation of move semantics, I'd highly recommend reading the original paper on them, "A Proposal to Add Move Semantics Support to the C++ Language."

It's very accessible and easy to read and it makes an excellent case for the benefits that they offer. There are other more recent and up to date papers about move semantics available on the WG21 website, but this one is probably the most straightforward since it approaches things from a top-level view and doesn't get very much into the gritty language details.

What is 0x10 in decimal?

The simple version is 0x is a prefix denoting a hexadecimal number, source.

So the value you're computing is after the prefix, in this case 10.

But that is not the number 10. The most significant bit 1 denotes the hex value while 0 denotes the units.

So the simple math you would do is

0x10

1 * 16 + 0 = 16

Note - you use 16 because hex is base 16.

Another example:

0xF7

15 * 16 + 7 = 247

You can get a list of values by searching for a hex table. For instance in this chart notice F corresponds with 15.

Extract time from moment js object

This is the good way using formats:

const now = moment()
now.format("hh:mm:ss K") // 1:00:00 PM
now.format("HH:mm:ss") // 13:00:00

Red more about moment sring format

org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused in android

When you test with device you want to add your PC ip address.

in pc run in cmd Ipconfig

in ubuntu run terminal ifconfig

Then use "http://your_pc_ip_address:8080/register" insted of using "http://10.0.2.2:8080/register"

in my pc = 192.168.1.3

and also add internet permission to Manifest

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

How do I match any character across multiple lines in a regular expression?

"." normally doesn't match line-breaks. Most regex engines allows you to add the S-flag (also called DOTALL and SINGLELINE) to make "." also match newlines. If that fails, you could do something like [\S\s].

Could not load file or assembly '' or one of its dependencies

  • Does the version number match?
  • It's weird to see you're trying to load a .lib file instead of a dll. Perhaps you wanted to load a dll instead?
  • To debug this kind of problems, try Fusion Logging
  • You say you're using only one library, but that library might have some dependencies you're not aware of. This SO question deals with listing the dependencies of a managed .NET assembly.

concatenate two database columns into one resultset column

Just Cast Column As Varchar(Size)

If both Column are numeric then use code below.

Example:

Select (Cast(Col1 as Varchar(20)) + '-' + Cast(Col2 as Varchar(20))) As Col3 from Table

What will be the size of col3 it will be 40 or something else

Create a dictionary with list comprehension

In fact, you don't even need to iterate over the iterable if it already comprehends some kind of mapping, the dict constructor doing it graciously for you:

>>> ts = [(1, 2), (3, 4), (5, 6)]
>>> dict(ts)
{1: 2, 3: 4, 5: 6}
>>> gen = ((i, i+1) for i in range(1, 6, 2))
>>> gen
<generator object <genexpr> at 0xb7201c5c>
>>> dict(gen)
{1: 2, 3: 4, 5: 6}

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

You need to update your all packages when you are move VS2015 to VS2017 for discover test in test explorer.

Sum function in VBA

Range("A10") = WorksheetFunction.Sum(Worksheets("Sheet1").Range("A1", "A9"))

Where

Range("A10") is the answer cell

Range("A1", "A9") is the range to calculate

PHP page redirect

Yes.

In essence, as long as nothing is output, you can do whatever you want (kill a session, remove user cookies, calculate Pi to 'n' digits, etc.) prior to issuing a location header.

Capturing multiple line output into a Bash variable

After trying most of the solutions here, the easiest thing I found was the obvious - using a temp file. I'm not sure what you want to do with your multiple line output, but you can then deal with it line by line using read. About the only thing you can't really do is easily stick it all in the same variable, but for most practical purposes this is way easier to deal with.

./myscript.sh > /tmp/foo
while read line ; do 
    echo 'whatever you want to do with $line'
done < /tmp/foo

Quick hack to make it do the requested action:

result=""
./myscript.sh > /tmp/foo
while read line ; do
  result="$result$line\n"
done < /tmp/foo
echo -e $result

Note this adds an extra line. If you work on it you can code around it, I'm just too lazy.


EDIT: While this case works perfectly well, people reading this should be aware that you can easily squash your stdin inside the while loop, thus giving you a script that will run one line, clear stdin, and exit. Like ssh will do that I think? I just saw it recently, other code examples here: https://unix.stackexchange.com/questions/24260/reading-lines-from-a-file-with-bash-for-vs-while

One more time! This time with a different filehandle (stdin, stdout, stderr are 0-2, so we can use &3 or higher in bash).

result=""
./test>/tmp/foo
while read line  <&3; do
    result="$result$line\n"
done 3</tmp/foo
echo -e $result

you can also use mktemp, but this is just a quick code example. Usage for mktemp looks like:

filenamevar=`mktemp /tmp/tempXXXXXX`
./test > $filenamevar

Then use $filenamevar like you would the actual name of a file. Probably doesn't need to be explained here but someone complained in the comments.

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

As @Jthorpe alluded to, ComponentClass only allows either Component or PureComponent but not a FunctionComponent.

If you attempt to pass a FunctionComponent, typescript will throw an error similar to...

Type '(props: myProps) => Element' provides no match for the signature 'new (props: myProps, context?: any): Component<myProps, any, any>'.

However, by using ComponentType rather than ComponentClass you allow for both cases. Per the react declaration file the type is defined as...

type ComponentType<P = {}> = ComponentClass<P, any> | FunctionComponent<P>

Use formula in custom calculated field in Pivot Table

Pivot table Excel2007- average to exclude zeros

=sum(XX:XX)/count if(XX:XX, ">0")

Invoice USD

Qty Rate(count) Value (sum) 300 0.000 000.000 1000 0.385 385.000

Average Rate Count should Exclude 0.000 rate

Global Variable in app.js accessible in routes?

I used app.all

The app.all() method is useful for mapping “global” logic for specific path prefixes or arbitrary matches.

In my case, I'm using confit for configuration management,

app.all('*', function (req, res, next) {
    confit(basedir).create(function (err, config) {
        if (err) {
            throw new Error('Failed to load configuration ', err);
        }
        app.set('config', config);
        next();
    });
});

In routes, you simply do req.app.get('config').get('cookie');

Lost connection to MySQL server during query?

This can also happen if someone or something kills your connection using the KILL command.

NSCameraUsageDescription in iOS 10.0 runtime crash?

You have to add this below key in info.plist.

NSCameraUsageDescription Or Privacy - Camera usage description

And add description of usage.

Detailed screenshots are available in this link

How to grey out a button?

Button button = (Button)findViewById(R.id.buy_btn);
button.setEnabled(false);

Encapsulation vs Abstraction?

in a simple sentence, I cay say: The essence of abstraction is to extract essential properties while omitting inessential details. But why should we omit inessential details? The key motivator is preventing the risk of change. You might consider abstraction is same as encapsulation. But encapsulation means the act of enclosing one or more items within a container, not hiding details. If you make the argument that "everything that was encapsulated was also hidden." This is obviously not true. For example, even though information may be encapsulated within record structures and arrays, this information is usually not hidden (unless hidden via some other mechanism).

Java Error opening registry key

I would have tagged this as a comment but cant (dont have the rep) just wanted to thank Tilman. I was trying to get PDFsam (PDF Split and Merge) to work to no avail.

At launch it would produce an error stating that it could not find JRE 1.6.0. I Have both 32 and 64 bit versions and they check out fine at the java website in their respective browsers.

Tried uninstalling/reinstalling and rebooting repeatedly as well as using JavaRa. No such luck, still no go.

I looked in the registry after reading this post and there was no ...\SOFTWARE\JavaSoft\ key so I added each with their respective string values pointing to my x86 version (PDFsam is a 32bit program). This got past the first problem but an error popped up about amd64 libraries suggesting the machine wanted to run the 64bit version. So I changed the paths to the 64bit JRE and PDFsam now works.

FYI - I got here by searching for Java registry keys after I was unable to launch javaw.exe from command prompt (even after adding the requisite paths to system path), making the aforementioned changes solved this as well.

Error:(23, 17) Failed to resolve: junit:junit:4.12

I'll tryed everithing, but the only thing that helps me resolve the problem was delete the line

testCompile 'junit:junit:4.12'

from the app gradel.

How to remove the hash from window.location (URL) with JavaScript without page refresh?

You can do it as below:

history.replaceState({}, document.title, window.location.href.split('#')[0]);

Autonumber value of last inserted row - MS Access / VBA

Private Function addInsert(Media As String, pagesOut As Integer) As Long


    Set rst = db.OpenRecordset("tblenccomponent")
    With rst
        .AddNew
        !LeafletCode = LeafletCode
        !LeafletName = LeafletName
        !UNCPath = "somePath\" + LeafletCode + ".xml"
        !Media = Media
        !CustomerID = cboCustomerID.Column(0)
        !PagesIn = PagesIn
        !pagesOut = pagesOut
        addInsert = CLng(rst!enclosureID) 'ID is passed back to calling routine
        .Update
    End With
    rst.Close

End Function

Does HTML5 <video> playback support the .avi format?

Short answer: No. Use WebM or Ogg instead.

This article covers just about everything you need to know about the <video> element, including which browsers support which container formats and codecs.

Use CSS3 transitions with gradient backgrounds

Gradients don't support transitions yet (although the current spec says they should support like gradient to like gradient transitions via interpolation.).

If you want a fade-in effect with a background gradient, you have to set an opacity on a container element and 'transition` the opacity.

(There have been some browser releases that supported transitions on gradients (e.g IE10. I tested gradient transitions in 2016 in IE and they seemed to work at the time, but my test code no longer works.)

Update: October 2018 Gradient transitions with un-prefixed new syntax [e.g. radial-gradient(...)]now confirmed to work (again?) on Microsoft Edge 17.17134. I don't know when this was added. Still not working on latest Firefox & Chrome / Windows 10.

Git Extensions: Win32 error 487: Couldn't reserve space for cygwin's heap, Win32 error 0

To fix this issue, I simply let Tortoise Git install its update.

Remove style attribute from HTML tags

I commented on @Mayerln 's function. It does work but DOMDocument really stuffs with encoding. Here's my simplehtmldom version

function stripAttributes($html,$attribs) {
    $dom = new simple_html_dom();
    $dom->load($html);
    foreach($attribs as $attrib)
        foreach($dom->find("*[$attrib]") as $e)
            $e->$attrib = null; 
    $dom->load($dom->save());
    return $dom->save();
}

Is it possible to apply CSS to half of a character?

You can also do it using SVG, if you wish:

_x000D_
_x000D_
var title = document.querySelector('h1'),_x000D_
    text = title.innerHTML,_x000D_
    svgTemplate = document.querySelector('svg'),_x000D_
    charStyle = svgTemplate.querySelector('#text');_x000D_
_x000D_
svgTemplate.style.display = 'block';_x000D_
_x000D_
var space = 0;_x000D_
_x000D_
for (var i = 0; i < text.length; i++) {_x000D_
  var x = charStyle.cloneNode();_x000D_
  x.textContent = text[i];_x000D_
  svgTemplate.appendChild(x);_x000D_
  x.setAttribute('x', space);_x000D_
  space += x.clientWidth || 15;_x000D_
}_x000D_
_x000D_
title.innerHTML = '';_x000D_
title.appendChild(svgTemplate);
_x000D_
<svg style="display: none; height: 100px; width: 100%" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">_x000D_
    <defs id="FooDefs">_x000D_
        <linearGradient id="MyGradient" x1="0%" y1="0%" x2="100%" y2="0%">_x000D_
            <stop offset="50%" stop-color="blue" />_x000D_
            <stop offset="50%" stop-color="red" />_x000D_
        </linearGradient>_x000D_
    </defs>_x000D_
    <text y="50%" id="text" style="font-size: 72px; fill: url(#MyGradient)"></text>_x000D_
</svg>_x000D_
_x000D_
<h1>This is not a solution X</h1>
_x000D_
_x000D_
_x000D_

http://codepen.io/nicbell/pen/jGcbq

How to check if a database exists in SQL Server?

I like @Eduardo's answer and I liked the accepted answer. I like to get back a boolean from something like this, so I wrote it up for you guys.

CREATE FUNCTION dbo.DatabaseExists(@dbname nvarchar(128))
RETURNS bit
AS
BEGIN
    declare @result bit = 0 
    SELECT @result = CAST(
        CASE WHEN db_id(@dbname) is not null THEN 1 
        ELSE 0 
        END 
    AS BIT)
    return @result
END
GO

Now you can use it like this:

select [dbo].[DatabaseExists]('master') --returns 1
select [dbo].[DatabaseExists]('slave') --returns 0

On a CSS hover event, can I change another div's styling?

A pure solution without jQuery:

Javascript (Head)

function chbg(color) {
    document.getElementById('b').style.backgroundColor = color;
}   

HTML (Body)

<div id="a" onmouseover="chbg('red')" onmouseout="chbg('white')">This is element a</div>
<div id="b">This is element b</div>

JSFiddle: http://jsfiddle.net/YShs2/

C# using streams

I would start by reading up on streams on MSDN: http://msdn.microsoft.com/en-us/library/system.io.stream.aspx

Memorystream and FileStream are streams used to work with raw memory and Files respectively...

Check if a string is a date value

Try this:

if (var date = new Date(yourDateString)) {
    // if you get here then you have a valid date       
}

Sibling package imports

  1. Project

1.1 User

1.1.1 about.py

1.1.2 init.py

1.2 Tech

1.2.1 info.py

1.1.2 init.py

Now, if you want to access about.py module in the User package, from the info.py module in Tech package then you have to bring the cmd (in windows) path to Project i.e. **C:\Users\Personal\Desktop\Project>**as per the above Package example. And from this path you have to enter, python -m Package_name.module_name For example for the above Package we have to do,

C:\Users\Personal\Desktop\Project>python -m Tech.info

Imp Points

  1. Don't use .py extension after info module i.e. python -m Tech.info.py
  2. Enter this, where the siblings packages are in the same level.
  3. -m is the flag, to check about it you can type from the cmd python --help

NPM global install "cannot find module"

Had the same problem on one of the test servers running Ubuntu under root. Then created a new user using useradd -m myuser and installed everything (nvm, node, packages) as myuser. Now it's working fine.

HTML5 validation when the input type is not "submit"

I may be late, but the way I did it was to create a hidden submit input, and calling it's click handler upon submit. Something like (using jquery for simplicity):

<input type="text" id="example" name="example" value="" required>
<button type="button"  onclick="submitform()" id="save">Save</button>
<input id="submit_handle" type="submit" style="display: none">

<script>
function submitform() {
    $('#submit_handle').click();
}
</script>

How to Set AllowOverride all

As other users explained here about the usage of allowoveride directive, which is used to give permission to .htaccess usage. one thing I want to point out that never use allowoverride all if other users have access to write .htaccess instead use allowoveride as to permit certain modules.

Such as AllowOverride AuthConfig mod_rewrite Instead of

AllowOverride All

Because module like mod_mime can render your server side files as plain text.

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

Loop through all elements in XML using NodeList

public class XMLParser {
   public static void main(String[] args){
      try {
         DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
         Document doc = dBuilder.parse(new File("xml input"));
         NodeList nl=doc.getDocumentElement().getChildNodes();

         for(int k=0;k<nl.getLength();k++){
             printTags((Node)nl.item(k));
         }
      } catch (Exception e) {/*err handling*/}
   }

   public static void printTags(Node nodes){
       if(nodes.hasChildNodes()  || nodes.getNodeType()!=3){
           System.out.println(nodes.getNodeName()+" : "+nodes.getTextContent());
           NodeList nl=nodes.getChildNodes();
           for(int j=0;j<nl.getLength();j++)printTags(nl.item(j));
       }
   }
}

Recursively loop through and print out all the xml child tags in the document, in case you don't have to change the code to handle dynamic changes in xml, provided it's a well formed xml.

How to enable CORS on Firefox?

This Firefox add-on may work for you:

https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/

It can toggle CORS on and off for development purposes.

use jQuery to get values of selected checkboxes

$("#locationthemes").prop("checked")

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

Logically OLAP functions are calculated after GROUP BY/HAVING, so you can only access columns in GROUP BY or columns with an aggregate function. Following looks strange, but is Standard SQL:

SELECT employee_number,
       MAX(MAX(course_completion_date)) 
           OVER (PARTITION BY course_code) AS max_course_date,
       MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

And as Teradata allows re-using an alias this also works:

SELECT employee_number,
       MAX(max_date) 
           OVER (PARTITION BY course_code) AS max_course_date,
       MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

Want to download a Git repository, what do I need (windows machine)?

I don't want to start a "What's the best unix command line under Windows" war, but have you thought of Cygwin? Git is in the Cygwin package repository.

And you get a lot of beneficial side-effects! (:-)

Python slice first and last element in list

Just thought I'd show how to do this with numpy's fancy indexing:

>>> import numpy
>>> some_list = ['1', 'B', '3', 'D', '5', 'F']
>>> numpy.array(some_list)[[0,-1]]
array(['1', 'F'], 
      dtype='|S1')

Note that it also supports arbitrary index locations, which the [::len(some_list)-1] method would not work for:

>>> numpy.array(some_list)[[0,2,-1]]
array(['1', '3', 'F'], 
      dtype='|S1')

As DSM points out, you can do something similar with itemgetter:

>>> import operator
>>> operator.itemgetter(0, 2, -1)(some_list)
('1', '3', 'F')

What is a stack trace, and how can I use it to debug my application errors?

To understand the name: A stack trace is a a list of Exceptions( or you can say a list of "Cause by"), from the most surface Exception(e.g. Service Layer Exception) to the deepest one (e.g. Database Exception). Just like the reason we call it 'stack' is because stack is First in Last out (FILO), the deepest exception was happened in the very beginning, then a chain of exception was generated a series of consequences, the surface Exception was the last one happened in time, but we see it in the first place.

Key 1:A tricky and important thing here need to be understand is : the deepest cause may not be the "root cause", because if you write some "bad code", it may cause some exception underneath which is deeper than its layer. For example, a bad sql query may cause SQLServerException connection reset in the bottem instead of syndax error, which may just in the middle of the stack.

-> Locate the root cause in the middle is your job. enter image description here

Key 2:Another tricky but important thing is inside each "Cause by" block, the first line was the deepest layer and happen first place for this block. For instance,

Exception in thread "main" java.lang.NullPointerException
        at com.example.myproject.Book.getTitle(Book.java:16)
           at com.example.myproject.Author.getBookTitles(Author.java:25)
               at com.example.myproject.Bootstrap.main(Bootstrap.java:14)

Book.java:16 was called by Auther.java:25 which was called by Bootstrap.java:14, Book.java:16 was the root cause. Here attach a diagram sort the trace stack in chronological order. enter image description here

What are some great online database modeling tools?

Do you mean design as in 'graphic representation of tables' or just plain old 'engineering kind of design'. If it's the latter, use FlameRobin, version 0.9.0 has just been released.

If it's the former, then use DBDesigner. Yup, that uses Java.

Or maybe you meant something more like MS Access. Then Kexi should be right for you.

How to remove button shadow (android)

All above answers are great, but I will suggest an other option:

<style name="FlatButtonStyle" parent="Base.Widget.AppCompat.Button">
 <item name="android:stateListAnimator">@null</item>
 <!-- more style custom here --> 
</style>


CSS display:inline property with list-style-image: property on <li> tags

You want the list items to line up next to each other, but not really be inline elements. So float them instead:

ol.widgets li { 
    float: left;
    margin-left: 10px;
}

Python's "in" set operator

That's right. You could try it in the interpreter like this:

>>> a_set = set(['a', 'b', 'c'])

>>> 'a' in a_set
True

>>>'d' in a_set
False

How do I set the request timeout for one controller action in an asp.net mvc application

<location path="ControllerName/ActionName">
    <system.web>
        <httpRuntime executionTimeout="1000"/>
    </system.web>
</location>

Probably it is better to set such values in web.config instead of controller. Hardcoding of configurable options is considered harmful.

How can I resolve the error: "The command [...] exited with code 1"?

Check your paths: If you are using a separate build server for TFS (most likely), make sure that all your paths in the .csproj file match the TFS server paths. I got the above error when checking in the *.csproj file when it had references to my development machine paths and not the TFS server paths.

Remove multi-line commands: Also, try and remove multi-line commands into single-line commands in xml as a precaution. I had the following xml in the *.proj that caused issues in TFS:

<Exec Condition="bl.." 
Command=" Blah...
..." </Exec>

Changing the above xml to this worked:

  <Exec Condition="bl.." Command=" Blah..." </Exec>

How to extract URL parameters from a URL with Ruby or Rails?

I think you want to turn any given URL string into a HASH?

You can try http://www.ruby-doc.org/stdlib/libdoc/cgi/rdoc/classes/CGI.html#M000075

require 'cgi'

CGI::parse('param1=value1&param2=value2&param3=value3')

returns

{"param1"=>["value1"], "param2"=>["value2"], "param3"=>["value3"]}

LINQ: "contains" and a Lambda query

var depthead = (from s in db.M_Users
                  join m in db.M_User_Types on s.F_User_Type equals m.UserType_Id
                  where m.UserType_Name.ToUpper().Trim().Contains("DEPARTMENT HEAD")
                  select new {s.FullName,s.F_User_Type,s.userId,s.UserCode } 
               ).OrderBy(d => d.userId).ToList();

Model.AvailableDeptHead.Add(new SelectListItem { Text = "Select", Value = "0" });
for (int i = 0; i < depthead.Count; i++)
    Model.AvailableDeptHead.Add(new SelectListItem { Text = depthead[i].UserCode + " - " + depthead[i].FullName, Value = Convert.ToString(depthead[i].userId) });

Session TimeOut in web.xml

you can declare time in two ways for this problem..

1) either give too long time that your file reading is complete in between that time.

<session-config>
    <session-timeout> 1000 </session-timeout>
</session-config>

2)declare time which is never expires your session.

<session-config>
    <session-timeout>-1</session-timeout>
</session-config>

Detect rotation of Android phone in the browser with JavaScript

A little contribution to the two-bit-fool's answer:

As described on the table on droid phones "orientationchange" event gets fired earlier than "resize" event thus blocking the next resize call (because of the if statement). Width property is still not set.

A workaround though maybe not a perfect one could be to not fire the "orientationchange" event. That can be archived by wrapping "orientationchange" event binding in "if" statement:

if (!navigator.userAgent.match(/android/i))
{
    window.addEventListener("orientationchange", checkOrientation, false);
}

Hope it helps

(tests were done on Nexus S)

Moving from position A to position B slowly with animation

I don't understand why other answers are about relative coordinates change, not absolute like OP asked in title.

$("#Friends").animate( {top:
  "-=" + (parseInt($("#Friends").css("top")) - 100) + "px"
} );

Copy output of a JavaScript variable to the clipboard

Very useful. I modified it to copy a JavaScript variable value to clipboard:

function copyToClipboard(val){
    var dummy = document.createElement("input");
    dummy.style.display = 'none';
    document.body.appendChild(dummy);

    dummy.setAttribute("id", "dummy_id");
    document.getElementById("dummy_id").value=val;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}

format a number with commas and decimals in C# (asp.net MVC3)

Try with

ToString("#,##0.00")

From MSDN

*The "0" custom format specifier serves as a zero-placeholder symbol. If the value that is being formatted has a digit in the position where the zero appears in the format string, that digit is copied to the result string; otherwise, a zero appears in the result string. The position of the leftmost zero before the decimal point and the rightmost zero after the decimal point determines the range of digits that are always present in the result string.

The "00" specifier causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "00" would result in the value 35.*

Regular expression to get a string between two strings in Javascript

The chosen answer didn't work for me...hmm...

Just add space after cow and/or before milk to trim spaces from " always gives "

/(?<=cow ).*(?= milk)/

enter image description here

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

I used a global action filter to remove Accept: application/xml when the User-Agent header contains "Chrome":

internal class RemoveXmlForGoogleChromeFilter : IActionFilter
{
    public bool AllowMultiple
    {
        get { return false; }
    }

    public async Task<HttpResponseMessage> ExecuteActionFilterAsync(
        HttpActionContext actionContext,
        CancellationToken cancellationToken,
        Func<Task<HttpResponseMessage>> continuation)
    {
        var userAgent = actionContext.Request.Headers.UserAgent.ToString();
        if (userAgent.Contains("Chrome"))
        {
            var acceptHeaders = actionContext.Request.Headers.Accept;
            var header =
                acceptHeaders.SingleOrDefault(
                    x => x.MediaType.Contains("application/xml"));
            acceptHeaders.Remove(header);
        }

        return await continuation();
    }
}

Seems to work.

How do I parse an ISO 8601-formatted date?

If you don't want to use dateutil, you can try this function:

def from_utc(utcTime,fmt="%Y-%m-%dT%H:%M:%S.%fZ"):
    """
    Convert UTC time string to time.struct_time
    """
    # change datetime.datetime to time, return time.struct_time type
    return datetime.datetime.strptime(utcTime, fmt)

Test:

from_utc("2007-03-04T21:08:12.123Z")

Result:

datetime.datetime(2007, 3, 4, 21, 8, 12, 123000)

nodemon not working: -bash: nodemon: command not found

Put --exec arg in single quotation.

e.g. I changed "nodemon --exec yarn build-langs" to "nodemon --exec 'yarn build-langs'" and worked.

setTimeout or setInterval?

To look at it a bit differently: setInterval insures that a code is run at every given interval (i.e. 1000ms, or how much you specify) while setTimeout sets the time that it 'waits until' it runs the code. And since it takes extra milliseconds to run the code, it adds up to 1000ms and thus, setTimeout runs again at inexact times (over 1000ms).

For example, timers/countdowns are not done with setTimeout, they are done with setInterval, to ensure it does not delay and the code runs at the exact given interval.

How to completely uninstall kubernetes

If you are clearing the cluster so that you can start again, then, in addition to what @rib47 said, I also do the following to ensure my systems are in a state ready for kubeadm init again:

kubeadm reset -f
rm -rf /etc/cni /etc/kubernetes /var/lib/dockershim /var/lib/etcd /var/lib/kubelet /var/run/kubernetes ~/.kube/*
iptables -F && iptables -X
iptables -t nat -F && iptables -t nat -X
iptables -t raw -F && iptables -t raw -X
iptables -t mangle -F && iptables -t mangle -X
systemctl restart docker

You then need to re-install docker.io, kubeadm, kubectl, and kubelet to make sure they are at the latest versions for your distribution before you re-initialize the cluster.

EDIT: Discovered that calico adds firewall rules to the raw table so that needs clearing out as well.

How do I upload a file with the JS fetch API?

Jumping off from Alex Montoya's approach for multiple file input elements

const inputFiles = document.querySelectorAll('input[type="file"]');
const formData = new FormData();

for (const file of inputFiles) {
    formData.append(file.name, file.files[0]);
}

fetch(url, {
    method: 'POST',
    body: formData })

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

EDIT - related to 2.3.0 (2016-12-07)

NOTE: to get solution for previous version, check the history of this post

Similar topic is discussed here Equivalent of $compile in Angular 2. We need to use JitCompiler and NgModule. Read more about NgModule in Angular2 here:

In a Nutshell

There is a working plunker/example (dynamic template, dynamic component type, dynamic module,JitCompiler, ... in action)

The principal is:
1) create Template
2) find ComponentFactory in cache - go to 7)
3) - create Component
4) - create Module
5) - compile Module
6) - return (and cache for later use) ComponentFactory
7) use Target and ComponentFactory to create an Instance of dynamic Component

Here is a code snippet (more of it here) - Our custom Builder is returning just built/cached ComponentFactory and the view Target placeholder consume to create an instance of the DynamicComponent

  // here we get a TEMPLATE with dynamic content === TODO
  var template = this.templateBuilder.prepareTemplate(this.entity, useTextarea);

  // here we get Factory (just compiled or from cache)
  this.typeBuilder
      .createComponentFactory(template)
      .then((factory: ComponentFactory<IHaveDynamicData>) =>
    {
        // Target will instantiate and inject component (we'll keep reference to it)
        this.componentRef = this
            .dynamicComponentTarget
            .createComponent(factory);

        // let's inject @Inputs to component instance
        let component = this.componentRef.instance;

        component.entity = this.entity;
        //...
    });

This is it - in nutshell it. To get more details.. read below

.

TL&DR

Observe a plunker and come back to read details in case some snippet requires more explanation

.

Detailed explanation - Angular2 RC6++ & runtime components

Below description of this scenario, we will

  1. create a module PartsModule:NgModule (holder of small pieces)
  2. create another module DynamicModule:NgModule, which will contain our dynamic component (and reference PartsModule dynamically)
  3. create dynamic Template (simple approach)
  4. create new Component type (only if template has changed)
  5. create new RuntimeModule:NgModule. This module will contain the previously created Component type
  6. call JitCompiler.compileModuleAndAllComponentsAsync(runtimeModule) to get ComponentFactory
  7. create an Instance of the DynamicComponent - job of the View Target placeholder and ComponentFactory
  8. assign @Inputs to new instance (switch from INPUT to TEXTAREA editing), consume @Outputs

NgModule

We need an NgModules.

While I would like to show a very simple example, in this case, I would need three modules (in fact 4 - but I do not count the AppModule). Please, take this rather than a simple snippet as a basis for a really solid dynamic component generator.

There will be one module for all small components, e.g. string-editor, text-editor (date-editor, number-editor...)

@NgModule({
  imports:      [ 
      CommonModule,
      FormsModule
  ],
  declarations: [
      DYNAMIC_DIRECTIVES
  ],
  exports: [
      DYNAMIC_DIRECTIVES,
      CommonModule,
      FormsModule
  ]
})
export class PartsModule { }

Where DYNAMIC_DIRECTIVES are extensible and are intended to hold all small parts used for our dynamic Component template/type. Check app/parts/parts.module.ts

The second will be module for our Dynamic stuff handling. It will contain hosting components and some providers.. which will be singletons. Therefor we will publish them standard way - with forRoot()

import { DynamicDetail }          from './detail.view';
import { DynamicTypeBuilder }     from './type.builder';
import { DynamicTemplateBuilder } from './template.builder';

@NgModule({
  imports:      [ PartsModule ],
  declarations: [ DynamicDetail ],
  exports:      [ DynamicDetail],
})

export class DynamicModule {

    static forRoot()
    {
        return {
            ngModule: DynamicModule,
            providers: [ // singletons accross the whole app
              DynamicTemplateBuilder,
              DynamicTypeBuilder
            ], 
        };
    }
}

Check the usage of the forRoot() in the AppModule

Finally, we will need an adhoc, runtime module.. but that will be created later, as a part of DynamicTypeBuilder job.

The forth module, application module, is the one who keeps declares compiler providers:

...
import { COMPILER_PROVIDERS } from '@angular/compiler';    
import { AppComponent }   from './app.component';
import { DynamicModule }    from './dynamic/dynamic.module';

@NgModule({
  imports:      [ 
    BrowserModule,
    DynamicModule.forRoot() // singletons
  ],
  declarations: [ AppComponent],
  providers: [
    COMPILER_PROVIDERS // this is an app singleton declaration
  ],

Read (do read) much more about NgModule there:

A template builder

In our example we will process detail of this kind of entity

entity = { 
    code: "ABC123",
    description: "A description of this Entity" 
};

To create a template, in this plunker we use this simple/naive builder.

The real solution, a real template builder, is the place where your application can do a lot

// plunker - app/dynamic/template.builder.ts
import {Injectable} from "@angular/core";

@Injectable()
export class DynamicTemplateBuilder {

    public prepareTemplate(entity: any, useTextarea: boolean){
      
      let properties = Object.keys(entity);
      let template = "<form >";
      let editorName = useTextarea 
        ? "text-editor"
        : "string-editor";
        
      properties.forEach((propertyName) =>{
        template += `
          <${editorName}
              [propertyName]="'${propertyName}'"
              [entity]="entity"
          ></${editorName}>`;
      });
  
      return template + "</form>";
    }
}

A trick here is - it builds a template which uses some set of known properties, e.g. entity. Such property(-ies) must be part of dynamic component, which we will create next.

To make it a bit more easier, we can use an interface to define properties, which our Template builder can use. This will be implemented by our dynamic Component type.

export interface IHaveDynamicData { 
    public entity: any;
    ...
}

A ComponentFactory builder

Very important thing here is to keep in mind:

our component type, build with our DynamicTypeBuilder, could differ - but only by its template (created above). Components' properties (inputs, outputs or some protected) are still same. If we need different properties, we should define different combination of Template and Type Builder

So, we are touching the core of our solution. The Builder, will 1) create ComponentType 2) create its NgModule 3) compile ComponentFactory 4) cache it for later reuse.

An dependency we need to receive:

// plunker - app/dynamic/type.builder.ts
import { JitCompiler } from '@angular/compiler';
    
@Injectable()
export class DynamicTypeBuilder {

  // wee need Dynamic component builder
  constructor(
    protected compiler: JitCompiler
  ) {}

And here is a snippet how to get a ComponentFactory:

// plunker - app/dynamic/type.builder.ts
// this object is singleton - so we can use this as a cache
private _cacheOfFactories:
     {[templateKey: string]: ComponentFactory<IHaveDynamicData>} = {};
  
public createComponentFactory(template: string)
    : Promise<ComponentFactory<IHaveDynamicData>> {    
    let factory = this._cacheOfFactories[template];

    if (factory) {
        console.log("Module and Type are returned from cache")
       
        return new Promise((resolve) => {
            resolve(factory);
        });
    }
    
    // unknown template ... let's create a Type for it
    let type   = this.createNewComponent(template);
    let module = this.createComponentModule(type);
    
    return new Promise((resolve) => {
        this.compiler
            .compileModuleAndAllComponentsAsync(module)
            .then((moduleWithFactories) =>
            {
                factory = _.find(moduleWithFactories.componentFactories
                                , { componentType: type });

                this._cacheOfFactories[template] = factory;

                resolve(factory);
            });
    });
}

Above we create and cache both Component and Module. Because if the template (in fact the real dynamic part of that all) is the same.. we can reuse

And here are two methods, which represent the really cool way how to create a decorated classes/types in runtime. Not only @Component but also the @NgModule

protected createNewComponent (tmpl:string) {
  @Component({
      selector: 'dynamic-component',
      template: tmpl,
  })
  class CustomDynamicComponent  implements IHaveDynamicData {
      @Input()  public entity: any;
  };
  // a component for this particular template
  return CustomDynamicComponent;
}
protected createComponentModule (componentType: any) {
  @NgModule({
    imports: [
      PartsModule, // there are 'text-editor', 'string-editor'...
    ],
    declarations: [
      componentType
    ],
  })
  class RuntimeComponentModule
  {
  }
  // a module for just this Type
  return RuntimeComponentModule;
}

Important:

our component dynamic types differ, but just by template. So we use that fact to cache them. This is really very important. Angular2 will also cache these.. by the type. And if we would recreate for the same template strings new types... we will start to generate memory leaks.

ComponentFactory used by hosting component

Final piece is a component, which hosts the target for our dynamic component, e.g. <div #dynamicContentPlaceHolder></div>. We get a reference to it and use ComponentFactory to create a component. That is in a nutshell, and here are all the pieces of that component (if needed, open plunker here)

Let's firstly summarize import statements:

import {Component, ComponentRef,ViewChild,ViewContainerRef}   from '@angular/core';
import {AfterViewInit,OnInit,OnDestroy,OnChanges,SimpleChange} from '@angular/core';

import { IHaveDynamicData, DynamicTypeBuilder } from './type.builder';
import { DynamicTemplateBuilder }               from './template.builder';

@Component({
  selector: 'dynamic-detail',
  template: `
<div>
  check/uncheck to use INPUT vs TEXTAREA:
  <input type="checkbox" #val (click)="refreshContent(val.checked)" /><hr />
  <div #dynamicContentPlaceHolder></div>  <hr />
  entity: <pre>{{entity | json}}</pre>
</div>
`,
})
export class DynamicDetail implements AfterViewInit, OnChanges, OnDestroy, OnInit
{ 
    // wee need Dynamic component builder
    constructor(
        protected typeBuilder: DynamicTypeBuilder,
        protected templateBuilder: DynamicTemplateBuilder
    ) {}
    ...

We just receive, template and component builders. Next are properties which are needed for our example (more in comments)

// reference for a <div> with #dynamicContentPlaceHolder
@ViewChild('dynamicContentPlaceHolder', {read: ViewContainerRef}) 
protected dynamicComponentTarget: ViewContainerRef;
// this will be reference to dynamic content - to be able to destroy it
protected componentRef: ComponentRef<IHaveDynamicData>;

// until ngAfterViewInit, we cannot start (firstly) to process dynamic stuff
protected wasViewInitialized = false;

// example entity ... to be recieved from other app parts
// this is kind of candiate for @Input
protected entity = { 
    code: "ABC123",
    description: "A description of this Entity" 
  };

In this simple scenario, our hosting component does not have any @Input. So it does not have to react to changes. But despite of that fact (and to be ready for coming changes) - we need to introduce some flag if the component was already (firstly) initiated. And only then we can start the magic.

Finally we will use our component builder, and its just compiled/cached ComponentFacotry. Our Target placeholder will be asked to instantiate the Component with that factory.

protected refreshContent(useTextarea: boolean = false){
  
  if (this.componentRef) {
      this.componentRef.destroy();
  }
  
  // here we get a TEMPLATE with dynamic content === TODO
  var template = this.templateBuilder.prepareTemplate(this.entity, useTextarea);

  // here we get Factory (just compiled or from cache)
  this.typeBuilder
      .createComponentFactory(template)
      .then((factory: ComponentFactory<IHaveDynamicData>) =>
    {
        // Target will instantiate and inject component (we'll keep reference to it)
        this.componentRef = this
            .dynamicComponentTarget
            .createComponent(factory);

        // let's inject @Inputs to component instance
        let component = this.componentRef.instance;

        component.entity = this.entity;
        //...
    });
}

small extension

Also, we need to keep a reference to compiled template.. to be able properly destroy() it, whenever we will change it.

// this is the best moment where to start to process dynamic stuff
public ngAfterViewInit(): void
{
    this.wasViewInitialized = true;
    this.refreshContent();
}
// wasViewInitialized is an IMPORTANT switch 
// when this component would have its own changing @Input()
// - then we have to wait till view is intialized - first OnChange is too soon
public ngOnChanges(changes: {[key: string]: SimpleChange}): void
{
    if (this.wasViewInitialized) {
        return;
    }
    this.refreshContent();
}

public ngOnDestroy(){
  if (this.componentRef) {
      this.componentRef.destroy();
      this.componentRef = null;
  }
}

done

That is pretty much it. Do not forget to Destroy anything what was built dynamically (ngOnDestroy). Also, be sure to cache dynamic types and modules if the only difference is their template.

Check it all in action here

to see previous versions (e.g. RC5 related) of this post, check the history

How do I toggle an ng-show in AngularJS based on a boolean?

Basically I solved it by NOT-ing the isReplyFormOpen value whenever it is clicked:

<a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>

<div ng-init="isReplyFormOpen = false" ng-show="isReplyFormOpen" id="replyForm">
    <!-- Form -->
</div>

Should I use alias or alias_method?

I think there is an unwritten rule (something like a convention) that says to use 'alias' just for registering a method-name alias, means if you like to give the user of your code one method with more than one name:

class Engine
  def start
    #code goes here
  end
  alias run start
end

If you need to extend your code, use the ruby meta alternative.

class Engine
  def start
    puts "start me"
  end
end

Engine.new.start() # => start me

Engine.class_eval do
  unless method_defined?(:run)
    alias_method :run, :start
    define_method(:start) do
      puts "'before' extension"
      run()
      puts "'after' extension"
    end
  end
end

Engine.new.start
# => 'before' extension
# => start me
# => 'after' extension

Engine.new.run # => start me

Java Swing revalidate() vs repaint()

You need to call repaint() and revalidate(). The former tells Swing that an area of the window is dirty (which is necessary to erase the image of the old children removed by removeAll()); the latter tells the layout manager to recalculate the layout (which is necessary when adding components). This should cause children of the panel to repaint, but may not cause the panel itself to do so (see this for the list of repaint triggers).

On a more general note: rather than reusing the original panel, I'd recommend building a new panel and swapping them at the parent.

Timeout function if it takes too long to finish

I rewrote David's answer using the with statement, it allows you do do this:

with timeout(seconds=3):
    time.sleep(4)

Which will raise a TimeoutError.

The code is still using signal and thus UNIX only:

import signal

class timeout:
    def __init__(self, seconds=1, error_message='Timeout'):
        self.seconds = seconds
        self.error_message = error_message
    def handle_timeout(self, signum, frame):
        raise TimeoutError(self.error_message)
    def __enter__(self):
        signal.signal(signal.SIGALRM, self.handle_timeout)
        signal.alarm(self.seconds)
    def __exit__(self, type, value, traceback):
        signal.alarm(0)

Show two digits after decimal point in c++

Using header file stdio.h you can easily do it as usual like c. before using %.2lf(set a specific number after % specifier.) using printf().

It simply printf specific digits after decimal point.

#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
   double total=100;
   printf("%.2lf",total);//this prints 100.00 like as C
}

Inserting multiple rows in a single SQL query?

INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas.

Example:

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

How to get Javascript Select box's selected text

I know no-one is asking for a jQuery solution here, but might be worth mentioning that with jQuery you can just ask for:$('#selectorid').val()

How can I de-install a Perl module installed via `cpan`?

Update 2013: This code is obsolescent. Upvote bsb's late-coming answer instead.


I don't need to uninstall modules often, but the .packlist file based approach has never failed me so far.

use 5.010;
use ExtUtils::Installed qw();
use ExtUtils::Packlist qw();

die "Usage: $0 Module::Name Module::Name\n" unless @ARGV;

for my $mod (@ARGV) {
    my $inst = ExtUtils::Installed->new;

    foreach my $item (sort($inst->files($mod))) {
        say "removing $item";
        unlink $item or warn "could not remove $item: $!\n";
    }

    my $packfile = $inst->packlist($mod)->packlist_file;
    print "removing $packfile\n";
    unlink $packfile or warn "could not remove $packfile: $!\n";
}

read string from .resx file in C#

ResourceManager shouldn't be needed unless you're loading from an external resource.
For most things, say you've created a project (DLL, WinForms, whatever) you just use the project namespace, "Resources" and the resource identifier. eg:

Assuming a project namespace: UberSoft.WidgetPro

And your resx contains:

resx content example

You can just use:

Ubersoft.WidgetPro.Properties.Resources.RESPONSE_SEARCH_WILFRED

Tar error: Unexpected EOF in archive

In my case, I had started untar before the uploading of the tar file was complete.

How to downgrade to older version of Gradle

got it resolved:

uninstall the entire android studio

uninstalling android with the following commands

rm -Rf /Applications/Android\ Studio.app  
rm -Rf ~/Library/Preferences/AndroidStudio*  
rm -Rf ~/Library/Preferences/com.google.android.*  
rm -Rf ~/Library/Preferences/com.android.*  
rm -Rf ~/Library/Application\ Support/AndroidStudio*  
rm -Rf ~/Library/Logs/AndroidStudio*  
rm -Rf ~/Library/Caches/AndroidStudio*  
rm -Rf ~/.AndroidStudio*  
rm -Rf ~/.gradle  
rm -Rf ~/.android  
rm -Rf ~/Library/Android*  
rm -Rf /usr/local/var/lib/android-sdk/  
rm -Rf /Users/<username>/.tooling/gradle

Remove your project and clone it again and then goto Gradle Scripts and open gradle-wrapper.properties and change the below url which ever version you need

distributionUrl=https\://services.gradle.org/distributions/gradle-4.2-all.zip

pandas get rows which are NOT in other dataframe

extract the dissimilar rows using the merge function
df = df.merge(same.drop_duplicates(), on=['col1','col2'], 
               how='left', indicator=True)
save the dissimilar rows in CSV
df[df['_merge'] == 'left_only'].to_csv('output.csv')

How do I use a char as the case in a switch-case?

Like that. Except char hi=hello; should be char hi=hello.charAt(0). (Don't forget your break; statements).

Infinite Recursion with Jackson JSON and Hibernate JPA issue

You Should use @JsonBackReference with @ManyToOne entity and @JsonManagedReference with @onetomany containing entity classes.

@OneToMany(
            mappedBy = "queue_group",fetch = FetchType.LAZY,
            cascade = CascadeType.ALL
        )
    @JsonManagedReference
    private Set<Queue> queues;



@ManyToOne(cascade=CascadeType.ALL)
        @JoinColumn(name = "qid")
       // @JsonIgnore
        @JsonBackReference
        private Queue_group queue_group;

How do I pass a variable by reference?

Since your example happens to be object-oriented, you could make the following change to achieve a similar result:

class PassByReference:
    def __init__(self):
        self.variable = 'Original'
        self.change('variable')
        print(self.variable)

    def change(self, var):
        setattr(self, var, 'Changed')

# o.variable will equal 'Changed'
o = PassByReference()
assert o.variable == 'Changed'

What causes imported Maven project in Eclipse to use Java 1.5 instead of Java 1.6 by default and how can I ensure it doesn't?

Your JRE was probably defined in run configuration. Follow these steps in Eclipse to change the build JRE.

1) Right click on the project and select Run As > Run Configurations

2) From Run Configurations window, select your project build configuration on the left panel. On the right, you will see various tabs: Main, JRE, Refresh, Source,...

3) Click on JRE tab, you should see something like this

enter image description here

4) By default, Work Default JRE (The JRE you select as default under Preferences->Java->Installed JREs) will be used. If you want to use another installed JRE, tick the Alternate JRE checkbox and select your preferred JRE from the dropdown.

Java: recommended solution for deep cloning/copying an instance

For deep cloning implement Serializable on every class you want to clone like this

public static class Obj implements Serializable {
    public int a, b;
    public Obj(int a, int b) {
        this.a = a;
        this.b = b;
    }
}

And then use this function:

public static Object deepClone(Object object) {
    try {
        ByteArrayOutputStream baOs = new ByteArrayOutputStream();
        ObjectOutputStream oOs = new ObjectOutputStream(baOs);
        oOs.writeObject(object);
        ByteArrayInputStream baIs = new ByteArrayInputStream(baOs.toByteArray());
        ObjectInputStream oIs = new ObjectInputStream(baIs);
        return oIs.readObject();
    }
    catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

like this: Obj newObject = (Obj)deepClone(oldObject);

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

Here is the complete solution for PostgreSQL 9+, updated recently.

CREATE USER readonly  WITH ENCRYPTED PASSWORD 'readonly';
GRANT USAGE ON SCHEMA public to readonly;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly;

-- repeat code below for each database:

GRANT CONNECT ON DATABASE foo to readonly;
\c foo
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly; --- this grants privileges on new tables generated in new database "foo"
GRANT USAGE ON SCHEMA public to readonly; 
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;

Thanks to https://jamie.curle.io/creating-a-read-only-user-in-postgres/ for several important aspects

If anyone find shorter code, and preferably one that is able to perform this for all existing databases, extra kudos.

Most efficient way to prepend a value to an array

With ES6, you can now use the spread operator to create a new array with your new elements inserted before the original elements.

_x000D_
_x000D_
// Prepend a single item._x000D_
const a = [1, 2, 3];_x000D_
console.log([0, ...a]);
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
// Prepend an array._x000D_
const a = [2, 3];_x000D_
const b = [0, 1];_x000D_
console.log([...b, ...a]);
_x000D_
_x000D_
_x000D_

Update 2018-08-17: Performance

I intended this answer to present an alternative syntax that I think is more memorable and concise. It should be noted that according to some benchmarks (see this other answer), this syntax is significantly slower. This is probably not going to matter unless you are doing many of these operations in a loop.

How do change the color of the text of an <option> within a <select>?

I was recently having trouble with this same thing and I found a really simple solution.

All you have to do is set the first option to disabled and selected. Like this:

_x000D_
_x000D_
<select id="select">_x000D_
    <option disabled="disabled" selected="selected">select one option</option>_x000D_
    <option>one</option>_x000D_
    <option>two</option>_x000D_
    <option>three</option>_x000D_
    <option>four</option>_x000D_
    <option>five</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

This will display the first option (grayed out) when the page is loaded. It also prevents the user from being able to select it once they click on the list.

Insert Multiple Rows Into Temp Table With SQL Server 2012

Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.

That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...

What version of the SQL Server engine do you get from SELECT @@VERSION ??

Reliable way to convert a file to a byte[]

Not to repeat what everyone already have said but keep the following cheat sheet handly for File manipulations:

  1. System.IO.File.ReadAllBytes(filename);
  2. File.Exists(filename)
  3. Path.Combine(folderName, resOfThePath);
  4. Path.GetFullPath(path); // converts a relative path to absolute one
  5. Path.GetExtension(path);

Comment out HTML and PHP together

You can only accomplish this with PHP comments.

 <!-- <tr>
      <td><?php //echo $entry_keyword; ?></td>
      <td><input type="text" name="keyword" value="<?php //echo $keyword; ?>" /></td>
    </tr>
    <tr>
      <td><?php //echo $entry_sort_order; ?></td>
      <td><input name="sort_order" value="<?php //echo $sort_order; ?>" size="1" /></td>
    </tr> -->

The way that PHP and HTML works, it is not able to comment in one swoop unless you do:

<?php

/*

echo <<<ENDHTML
 <tr>
          <td>{$entry_keyword}</td>
          <td><input type="text" name="keyword" value="{echo $keyword}" /></td>
        </tr>
        <tr>
          <td>{$entry_sort_order}</td>
          <td><input name="sort_order" value="{$sort_order}" size="1" /></td>
        </tr>
ENDHTML;

*/
?>

How to Convert double to int in C?

I suspect you don't actually have that problem - I suspect you've really got:

double a = callSomeFunction();
// Examine a in the debugger or via logging, and decide it's 3669.0

// Now cast
int b = (int) a;
// Now a is 3668

What makes me say that is that although it's true that many decimal values cannot be stored exactly in float or double, that doesn't hold for integers of this kind of magnitude. They can very easily be exactly represented in binary floating point form. (Very large integers can't always be exactly represented, but we're not dealing with a very large integer here.)

I strongly suspect that your double value is actually slightly less than 3669.0, but it's being displayed to you as 3669.0 by whatever diagnostic device you're using. The conversion to an integer value just performs truncation, not rounding - hence the issue.

Assuming your double type is an IEEE-754 64-bit type, the largest value which is less than 3669.0 is exactly

3668.99999999999954525264911353588104248046875

So if you're using any diagnostic approach where that value would be shown as 3669.0, then it's quite possible (probable, I'd say) that this is what's happening.

Write a file in external storage in Android

 ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext()); //getappcontext for just this activity context get
 File file = contextWrapper.getDir(file_path, Context.MODE_PRIVATE);  
 if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) 
 { 
  saveToExternalStorage.setEnabled(false);
 }
 else
 {
  External_File = new File(getExternalFilesDir(file_path), file_name);//if ready then create a file for external 
 }

}
 try
  {
   FileInputStream fis = new FileInputStream(External_File);
   DataInputStream in = new DataInputStream(fis);
   BufferedReader br =new BufferedReader(new InputStreamReader(in));
   String strLine;
   while ((strLine = br.readLine()) != null) 
   {
    myData = myData + strLine;
   }
   in.close();
  }
  catch (IOException e) 
  {
   e.printStackTrace();
  }
  InputText.setText("Save data of External file::::  "+myData);


private static boolean isExternalStorageReadOnly() 
{ 
 String extStorageState = Environment.getExternalStorageState(); 
 if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState))
 { 
  return true; 
 } 
 return false; 
} 

private static boolean isExternalStorageAvailable()
{ 
 String extStorageState = Environment.getExternalStorageState(); 
 if (Environment.MEDIA_MOUNTED.equals(extStorageState))
 { 
  return true; 
 } 
 return false; 
} 

What does $(function() {} ); do?

The following is a jQuery function call:

$(...);

Which is the "jQuery function." $ is a function, and $(...) is you calling that function.

The first parameter you've supplied is the following:

function() {}

The parameter is a function that you specified, and the $ function will call the supplied method when the DOM finishes loading.

How to call execl() in C with the proper arguments?

If you need just to execute your VLC playback process and only give control back to your application process when it is done and nothing more complex, then i suppose you can use just:

system("The same thing you type into console");

PHP shell_exec() vs exec()

Here are the differences. Note the newlines at the end.

> shell_exec('date')
string(29) "Wed Mar  6 14:18:08 PST 2013\n"
> exec('date')
string(28) "Wed Mar  6 14:18:12 PST 2013"

> shell_exec('whoami')
string(9) "mark\n"
> exec('whoami')
string(8) "mark"

> shell_exec('ifconfig')
string(1244) "eth0      Link encap:Ethernet  HWaddr 10:bf:44:44:22:33  \n          inet addr:192.168.0.90  Bcast:192.168.0.255  Mask:255.255.255.0\n          inet6 addr: fe80::12bf:ffff:eeee:2222/64 Scope:Link\n          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1\n          RX packets:16264200 errors:0 dropped:1 overruns:0 frame:0\n          TX packets:7205647 errors:0 dropped:0 overruns:0 carrier:0\n          collisions:0 txqueuelen:1000 \n          RX bytes:13151177627 (13.1 GB)  TX bytes:2779457335 (2.7 GB)\n"...
> exec('ifconfig')
string(0) ""

Note that use of the backtick operator is identical to shell_exec().

Update: I really should explain that last one. Looking at this answer years later even I don't know why that came out blank! Daniel explains it above -- it's because exec only returns the last line, and ifconfig's last line happens to be blank.

Django set field value after a form is initialized

If you've already initialized the form, you can use the initial property of the field. For example,

form = CustomForm()
form.fields["Email"].initial = GetEmailString()

MySQL Multiple Left Joins

To display the all details for each news post title ie. "news.id" which is the primary key, you need to use GROUP BY clause for "news.id"

SELECT news.id, users.username, news.title, news.date,
       news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id

What does "wrong number of arguments (1 for 0)" mean in Ruby?

I assume you called a function with an argument which was defined without taking any.

def f()
  puts "hello world"
end

f(1)   # <= wrong number of arguments (1 for 0)

Set specific precision of a BigDecimal

Try this code ...

    Integer perc = 5;
    BigDecimal spread = BigDecimal.ZERO; 
    BigDecimal perc = spread.setScale(perc,BigDecimal.ROUND_HALF_UP);
    System.out.println(perc);

Result: 0.00000

Compare two files and write it to "match" and "nomatch" files

Though its really long back this question was posted, I wish to answer as it might help others. This can be done easily by means of JOINKEYS in a SINGLE step. Here goes the pseudo code:

  • Code JOINKEYS PAIRED(implicit) and get both the records via reformatting filed. If there is NO match from either of files then append/prefix some special character say '$'
  • Compare via IFTHEN for '$', if exists then it doesnt have a paired record, it'll be written into unpaired file and rest to paired file.

Please do get back incase of any questions.

mongod command not recognized when trying to connect to a mongodb server

It is probably too late, but for the sake of others (like me) who faced the same problem. It is all about the little '\' at the end of the path variable. When you insert the path to MongoDB's bin directory at the end of the PATH windows variable, do not forget to put the '\' (Backslash) at the end, which tells windows it is a directory and not an executable named bin... e.g. I:\Program Files\MongoDB\Server\3.0\bin\

How to use UIVisualEffectView to Blur Image?

Here is how to use UIVibrancyEffect and UIBlurEffect with UIVisualEffectView

Objective-C:

// Blur effect
UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
[blurEffectView setFrame:self.view.bounds];
[self.view addSubview:blurEffectView];

// Vibrancy effect
UIVibrancyEffect *vibrancyEffect = [UIVibrancyEffect effectForBlurEffect:blurEffect];
UIVisualEffectView *vibrancyEffectView = [[UIVisualEffectView alloc] initWithEffect:vibrancyEffect];
[vibrancyEffectView setFrame:self.view.bounds];

// Label for vibrant text
UILabel *vibrantLabel = [[UILabel alloc] init];
[vibrantLabel setText:@"Vibrant"];
[vibrantLabel setFont:[UIFont systemFontOfSize:72.0f]];
[vibrantLabel sizeToFit];
[vibrantLabel setCenter: self.view.center];

// Add label to the vibrancy view
[[vibrancyEffectView contentView] addSubview:vibrantLabel];

// Add the vibrancy view to the blur view
[[blurEffectView contentView] addSubview:vibrancyEffectView];

Swift 4:

    // Blur Effect
    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.frame = view.bounds
    view.addSubview(blurEffectView)

    // Vibrancy Effect
    let vibrancyEffect = UIVibrancyEffect(blurEffect: blurEffect)
    let vibrancyEffectView = UIVisualEffectView(effect: vibrancyEffect)
    vibrancyEffectView.frame = view.bounds

    // Label for vibrant text
    let vibrantLabel = UILabel()
    vibrantLabel.text = "Vibrant"
    vibrantLabel.font = UIFont.systemFont(ofSize: 72.0)
    vibrantLabel.sizeToFit()
    vibrantLabel.center = view.center

    // Add label to the vibrancy view
    vibrancyEffectView.contentView.addSubview(vibrantLabel)

    // Add the vibrancy view to the blur view
    blurEffectView.contentView.addSubview(vibrancyEffectView)

Android - default value in editText

 public class Main extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EditText et = (EditText) findViewById(R.id.et);
        EditText et_city = (EditText) findViewById(R.id.et_city);
        // Set the default text of second EditText widget
        et_city.setText("USA");
 }
}

What's the best/easiest GUI Library for Ruby?

If you're looking for a cross-platform GUI, then I'd highly recommend going with JRuby and Swing.

Also, take a look at the monkeybars library, which is a Ruby library for building MVC applications using JRuby and Swing, where you can also use the excellent Netbeans IDE to visually build your GUI.

Do we need type="text/css" for <link> in HTML5

You don't really need it today, because the current standard makes it optional -- and every useful browser currently assumes that a style sheet is CSS, even in versions of HTML that considered the attribute "required".

With HTML being a "living standard" now, though -- and thus subject to change -- you can only guarantee so much. And there's no new DTD that you can point to and say the page was written for that version of HTML, and no reliable way even to say "HTML as of such-and-such a date". For forward-compatibility reasons, in my opinion, you should specify the type.

How to install OpenSSL in windows 10?

Check openssl tool which is a collection of Openssl from the LibreSSL project and Cygwin libraries (2.5 MB). NB! We're the packager.

One liner to create a self signed certificate:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout selfsigned.key -out selfsigned.crt

How to enable file upload on React's Material UI simple input?

You can use Material UI's Input and InputLabel components. Here's an example if you were using them to input spreadsheet files.

import { Input, InputLabel } from "@material-ui/core";

const styles = {
  hidden: {
    display: "none",
  },
  importLabel: {
    color: "black",
  },
};

<InputLabel htmlFor="import-button" style={styles.importLabel}>
    <Input
        id="import-button"
        inputProps={{
          accept:
            ".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel",
        }}
        onChange={onInputChange}
        style={styles.hidden}
        type="file"
    />
    Import Spreadsheet
</InputLabel>

Get first day of week in SQL Server

To answer why you're getting a Monday and not a Sunday:

You're adding a number of weeks to the date 0. What is date 0? 1900-01-01. What was the day on 1900-01-01? Monday. So in your code you're saying, how many weeks have passed since Monday, January 1, 1900? Let's call that [n]. Ok, now add [n] weeks to Monday, January 1, 1900. You should not be surprised that this ends up being a Monday. DATEADD has no idea that you want to add weeks but only until you get to a Sunday, it's just adding 7 days, then adding 7 more days, ... just like DATEDIFF only recognizes boundaries that have been crossed. For example, these both return 1, even though some folks complain that there should be some sensible logic built in to round up or down:

SELECT DATEDIFF(YEAR, '2010-01-01', '2011-12-31');
SELECT DATEDIFF(YEAR, '2010-12-31', '2011-01-01');

To answer how to get a Sunday:

If you want a Sunday, then pick a base date that's not a Monday but rather a Sunday. For example:

DECLARE @dt DATE = '1905-01-01';
SELECT [start_of_week] = DATEADD(WEEK, DATEDIFF(WEEK, @dt, CURRENT_TIMESTAMP), @dt);

This will not break if you change your DATEFIRST setting (or your code is running for a user with a different setting) - provided that you still want a Sunday regardless of the current setting. If you want those two answers to jive, then you should use a function that does depend on the DATEFIRST setting, e.g.

SELECT DATEADD(DAY, 1-DATEPART(WEEKDAY, CURRENT_TIMESTAMP), CURRENT_TIMESTAMP);

So if you change your DATEFIRST setting to Monday, Tuesday, what have you, the behavior will change. Depending on which behavior you want, you could use one of these functions:

CREATE FUNCTION dbo.StartOfWeek1 -- always a Sunday
(
    @d DATE
)
RETURNS DATE
AS
BEGIN
    RETURN (SELECT DATEADD(WEEK, DATEDIFF(WEEK, '19050101', @d), '19050101'));
END
GO

...or...

CREATE FUNCTION dbo.StartOfWeek2 -- always the DATEFIRST weekday
(
    @d DATE
)
RETURNS DATE
AS
BEGIN
    RETURN (SELECT DATEADD(DAY, 1-DATEPART(WEEKDAY, @d), @d));
END
GO

Now, you have plenty of alternatives, but which one performs best? I'd be surprised if there would be any major differences but I collected all the answers provided so far and ran them through two sets of tests - one cheap and one expensive. I measured client statistics because I don't see I/O or memory playing a part in the performance here (though those may come into play depending on how the function is used). In my tests the results are:

"Cheap" assignment query:

Function - client processing time / wait time on server replies / total exec time
Gandarez     - 330/2029/2359 - 0:23.6
me datefirst - 329/2123/2452 - 0:24.5
me Sunday    - 357/2158/2515 - 0:25.2
trailmax     - 364/2160/2524 - 0:25.2
Curt         - 424/2202/2626 - 0:26.3

"Expensive" assignment query:

Function - client processing time / wait time on server replies / total exec time
Curt         - 1003/134158/135054 - 2:15
Gandarez     -  957/142919/143876 - 2:24
me Sunday    -  932/166817/165885 - 2:47
me datefirst -  939/171698/172637 - 2:53
trailmax     -  958/173174/174132 - 2:54

I can relay the details of my tests if desired - stopping here as this is already getting quite long-winded. I was a bit surprised to see Curt's come out as the fastest at the high end, given the number of calculations and inline code. Maybe I'll run some more thorough tests and blog about it... if you guys don't have any objections to me publishing your functions elsewhere.

How to copy a java.util.List into another java.util.List

originalArrayList.addAll(copyArrayofList);

Please keep on mind whenever using the addAll() method for copy, the contents of both the array lists (originalArrayList and copyArrayofList) references to the same objects will be added to the list so if you modify any one of them then copyArrayofList also will also reflect the same change.

If you don't want side effect then you need to copy each of element from the originalArrayList to the copyArrayofList, like using a for or while loop. for deep copy you can use below code snippet.

but one more thing you need to do, implement the Cloneable interface and override the clone() method for SomeBean class.

public static List<SomeBean> cloneList(List<SomeBean> originalArrayList) {
    List<SomeBean> copyArrayofList = new ArrayList<SomeBean>(list.size());
    for (SomeBean item : list) copyArrayofList.add(item.clone());
    return clone;
}

Difference between res.send and res.json in Express.js

Looking in the headers sent...
res.send uses content-type:text/html
res.json uses content-type:application/json

edit: send actually changes what is sent based on what it's given, so strings are sent as text/html, but it you pass it an object it emits application/json.

How to validate GUID is a GUID

Based on the accepted answer I created an Extension method as follows:

public static Guid ToGuid(this string aString)
{
    Guid newGuid;

    if (string.IsNullOrWhiteSpace(aString))
    {
        return MagicNumbers.defaultGuid;
    }

    if (Guid.TryParse(aString, out newGuid))
    {
        return newGuid;
    }

    return MagicNumbers.defaultGuid;
}

Where "MagicNumbers.defaultGuid" is just "an empty" all zero Guid "00000000-0000-0000-0000-000000000000".

In my case returning that value as the result of an invalid ToGuid conversion was not a problem.

Is there an addHeaderView equivalent for RecyclerView?

Probably http://alexzh.com/tutorials/multiple-row-layouts-using-recyclerview/ will help. It uses only RecyclerView and CardView. Here is an adapter:

public class DifferentRowAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<CityEvent> mList;
    public DifferentRowAdapter(List<CityEvent> list) {
        this.mList = list;
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;
        switch (viewType) {
            case CITY_TYPE:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_city, parent, false);
                return new CityViewHolder(view);
            case EVENT_TYPE:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_event, parent, false);
                return new EventViewHolder(view);
        }
        return null;
    }
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        CityEvent object = mList.get(position);
        if (object != null) {
            switch (object.getType()) {
                case CITY_TYPE:
                    ((CityViewHolder) holder).mTitle.setText(object.getName());
                    break;
                case EVENT_TYPE:
                    ((EventViewHolder) holder).mTitle.setText(object.getName());
                    ((EventViewHolder) holder).mDescription.setText(object.getDescription());
                    break;
            }
        }
    }
    @Override
    public int getItemCount() {
        if (mList == null)
            return 0;
        return mList.size();
    }
    @Override
    public int getItemViewType(int position) {
        if (mList != null) {
            CityEvent object = mList.get(position);
            if (object != null) {
                return object.getType();
            }
        }
        return 0;
    }
    public static class CityViewHolder extends RecyclerView.ViewHolder {
        private TextView mTitle;
        public CityViewHolder(View itemView) {
            super(itemView);
            mTitle = (TextView) itemView.findViewById(R.id.titleTextView);
        }
    }
    public static class EventViewHolder extends RecyclerView.ViewHolder {
        private TextView mTitle;
        private TextView mDescription;
        public EventViewHolder(View itemView) {
            super(itemView);
            mTitle = (TextView) itemView.findViewById(R.id.titleTextView);
            mDescription = (TextView) itemView.findViewById(R.id.descriptionTextView);
        }
    }
}

And here's an entity:

public class CityEvent {
    public static final int CITY_TYPE = 0;
    public static final int EVENT_TYPE = 1;
    private String mName;
    private String mDescription;
    private int mType;
    public CityEvent(String name, String description, int type) {
        this.mName = name;
        this.mDescription = description;
        this.mType = type;
    }
    public String getName() {
        return mName;
    }
    public void setName(String name) {
        this.mName = name;
    }
    public String getDescription() {
        return mDescription;
    }
    public void setDescription(String description) {
        this.mDescription = description;
    }
    public int getType() {
        return mType;
    }
    public void setType(int type) {
        this.mType = type;
    }
}

How can I draw circle through XML Drawable - Android?

no need for the padding or the corners.

here's a sample:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
    <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
        android:angle="270"/>
</shape>

based on :

https://stackoverflow.com/a/10104037/878126

How to wait for a process to terminate to execute another process in batch file

'start /w' does NOT work in all cases. The original solution works great. However, on some machines, it is wise to put a delay immediately after starting the executable. Otherwise, the task name may not appear in the task list yet, and the loop will not work as expected (someone pointed that out). The 2 delays can be combined and put at the top of the loop. Can also get rid of the 'else' just to shorten. Example of 2 programs running sequentially:

c:\prog1.exe 
:loop1
timeout /t 1 /nobreak >nul 2>&1
tasklist | find /i "prog1.exe" >nul 2>&1
if errorlevel 1 goto cont1
goto loop1
:cont1

c:\prog2.exe
:loop2
timeout /t 1 /nobreak >nul 2>&1
tasklist | find /i "prog2.exe" >nul 2>&1
if errorlevel 1 goto cont2
goto loop2
:cont2

john refling

how to remove only one style property with jquery

You can also replace "-moz-user-select:none" with "-moz-user-select:inherit". This will inherit the style value from any parent style or from the default style if no parent style was defined.

Function is not defined - uncaught referenceerror

Thought I would mention this because it took a while for me to fix this issue and I couldn't find the answer anywhere on SO. The code I was working on worked for a co-worker but not for me (I was getting this same error). It worked for me in Chrome, but not in Edge.

I was able to get it working by clearing the cache in Edge.

This may not be the answer to this specific question, but I thought I would mention it in case it saves someone else a little time.

Pick a random value from an enum?

I would use this:

private static Random random = new Random();

public Object getRandomFromEnum(Class<? extends Enum<?>> clazz) {
    return clazz.values()[random.nextInt(clazz.values().length)];
}

“Unable to find manifest signing certificate in the certificate store” - even when add new key

If you need just build the project or solution locally then removing the signing might be a dead simple solution as others suggest.

But if you have this error on your automation build server like TeamCity where you build your actual release pieces for deployment or distribution you might want to consider how you can get this cert properly installed to the cert store on the build machine, so that you get a signed packages at the end of the build.

Generally it is not recommenced to check-in/commit any PFX certificates into source control, so how you get this files on your build server during the build process is a bit another question, but sometimes people do have this file stored along with the solution code, so you can find it in the project folder.

All you need to do is just install this certificate under proper account on your build server.

  1. Download PsExec from Windows Sysinternals.

  2. Open a command prompt, and enter the following. It will spawn a new command prompt, running as Local System (assuming that your TeamCity is running under the default Local System account):

    > psexec.exe -i -s cmd.exe

  3. In this new command prompt, change to the directory containing the certificate and enter the filename to install (change the name of the file to yours):

    > mykey.pfx

  4. The Import Certificate wizard will start up. Click through and select all the suggested defaults.

  5. Run the build.

All credits goes to Stuart Noble (and then further to Laurent Kempé I believe ?).

How can I get a list of repositories 'apt-get' is checking?

It's not a format suitable for blindly copying to another machine, but users who wish to work out whether they've added a repository yet or not (like I did), you can just do:

sudo apt update

When apt is updating, it outputs a list of repositories it fetches. It seems obvious, but I've just realised what the GET URLs are that it spits out.

The following awk-based expression could be used to generate a sources.list file:

 cat /tmp/apt-update.txt | awk '/http/ { gsub("/", " ", $3); gsub("^\s\*$", "main", $3); printf("deb "); if($4 ~ "^[a-z0-9]$") printf("[arch=" $4 "] "); print($2 " " $3) }' | sort | uniq

Alternatively, as other answers suggest, you could just cat all the pre-existing sources like this:

cat /etc/apt/sources.list /etc/apt/sources.list.d/*

Since the disabled repositories are commented out with hash, this should work as intended.

Is there a "do ... while" loop in Ruby?

a = 1
while true
  puts a
  a += 1
  break if a > 10
end

Save base64 string as PDF at client side with JavaScript

You will do not need any library for this. JavaScript support this already. Here is my end-to-end solution.

const xhr = new XMLHttpRequest();
xhr.open('GET', 'your-end-point', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.responseType = 'blob';
xhr.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
       if (window.navigator.msSaveOrOpenBlob) {
           window.navigator.msSaveBlob(this.response, "fileName.pdf");
        } else {
           const downloadLink = window.document.createElement('a');
           const contentTypeHeader = xhr.getResponseHeader("Content-Type");
           downloadLink.href = window.URL.createObjectURL(new Blob([this.response], { type: contentTypeHeader }));
           downloadLink.download = "fileName.pdf";
           document.body.appendChild(downloadLink);
           downloadLink.click();
           document.body.removeChild(downloadLink);
        }
    }
};
xhr.send(null);

This also work for .xls or .zip file. You just need to change file name to fileName.xls or fileName.zip. This depends on your case.

How to format a URL to get a file from Amazon S3?

As @stevebot said, do this:

https://<bucket-name>.s3.amazonaws.com/<key>

The one important thing I would like to add is that you either have to make your bucket objects all publicly accessible OR you can add a custom policy to your bucket policy. That custom policy could allow traffic from your network IP range or a different credential.

How can I set the current working directory to the directory of the script in Bash?

Get the real path to your script

if [ -L $0 ] ; then
    ME=$(readlink $0)
else
    ME=$0
fi
DIR=$(dirname $ME)

(This is answer to the same my question here: Get the name of the directory where a script is executed)

read file in classpath

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class readFile {
    /**
     * feel free to make any modification I have have been here so I feel you
     * 
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        File dir = new File(".");// read file from same directory as source //
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                // if you wanna read file name with txt files
                if (file.getName().contains("txt")) {
                    System.out.println(file.getName());
                }

                // if you want to open text file and read each line then
                if (file.getName().contains("txt")) {
                    try {
                        // FileReader reads text files in the default encoding.
                        FileReader fileReader = new FileReader(
                                file.getAbsolutePath());
                        // Always wrap FileReader in BufferedReader.
                        BufferedReader bufferedReader = new BufferedReader(
                                fileReader);
                        String line;
                        // get file details and get info you need.
                        while ((line = bufferedReader.readLine()) != null) {
                            System.out.println(line);
                            // here you can say...
                            // System.out.println(line.substring(0, 10)); this
                            // prints from 0 to 10 indext
                        }
                    } catch (FileNotFoundException ex) {
                        System.out.println("Unable to open file '"
                                + file.getName() + "'");
                    } catch (IOException ex) {
                        System.out.println("Error reading file '"
                                + file.getName() + "'");
                        // Or we could just do this:
                        ex.printStackTrace();
                    }
                }
            }
        }

    }`enter code here`

}

Delete data with foreign key in SQL Server table

SET foreign_key_checks = 0; DELETE FROM yourtable; SET foreign_key_checks = 1;

Editing specific line in text file in Python

I have been practising working on files this evening and realised that I can build on Jochen's answer to provide greater functionality for repeated/multiple use. Unfortunately my answer does not address issue of dealing with large files but does make life easier in smaller files.

with open('filetochange.txt', 'r+') as foo:
    data = foo.readlines()                  #reads file as list
    pos = int(input("Which position in list to edit? "))-1  #list position to edit
    data.insert(pos, "more foo"+"\n")           #inserts before item to edit
    x = data[pos+1]
    data.remove(x)                      #removes item to edit
    foo.seek(0)                     #seeks beginning of file
    for i in data:
        i.strip()                   #strips "\n" from list items
        foo.write(str(i))

retrieve data from db and display it in table in php .. see this code whats wrong with it?

<html>
    <head>
        <meta charset="UTF-8">
        <title>LoginDB</title>
    </head>
    <body>

        <?php
        $con=  mysqli_connect("localhost", "root", "", "detail");
<!-- detail is the database in MySqli Database -->
        if(!$con)
       {
           die('not connected');
       }
            $con=  mysqli_query($con, "select * from signup");
<!-- signup is the table in the detail_Database -->
       ?>
        <div>
            <td>Login Page Database</td>
         <table border="1">
            <th> First Name</th>
                    <th>Last Name</th>
                    <th>UserName</th>
                     <th>Password</th>
                    <th>Gender</th>
                    <th>D.O.B.</th>
                    <th>Phone Number</th>
                    <th>Address</th>

            </tr>

        <?php

             while($row=  mysqli_fetch_array($con))
<!-- Fetch each row from signup Table  -->
             {
                 ?>
            <tr>
                <td><?php echo $row['FirstName']; ?></td>
                <td><?php echo $row['LastName']; ?></td>
                <td><?php echo $row['Username']; ?></td>
                <td><?php echo $row['Password'] ;?></td>
                <td><?php echo $row['Gender'] ;?></td>
                <td><?php echo $row['DOB'] ;?></td>
                <td><?php echo $row['PhoneNumber'] ;?></td>
                <td><?php echo $row['Address'] ;?></td>
            </tr>
        <?php
             }
             ?>
             </table>
            </div>
    </body>
</html>