Programs & Examples On #Aspectj

AspectJ is an aspect-oriented extension to the Java programming language that enables clean modularization of crosscutting concerns such as logging, error handling, standards enforcement and feature variations. Use this tag for questions about the programmatic use of this extension. For downloads, support, IDE integration, & documentation, see the "learn more" for this tag.

@AspectJ pointcut for all methods of a class with specific annotation

From Spring's AnnotationTransactionAspect:

/**
 * Matches the execution of any public method in a type with the Transactional
 * annotation, or any subtype of a type with the Transactional annotation.
 */
private pointcut executionOfAnyPublicMethodInAtTransactionalType() :
    execution(public * ((@Transactional *)+).*(..)) && within(@Transactional *);

How to assign execute permission to a .sh file in windows to be executed in linux

As far as I know the permission system in Linux is set up in such a way to prevent exactly what you are trying to accomplish.

I think the best you can do is to give your Linux user a custom unzip one-liner to run on the prompt:

unzip zip_name.zip && chmod +x script_name.sh

If there are multiple scripts that you need to give execute permission to, write a grant_perms.sh as follows:

#!/bin/bash
# file: grant_perms.sh

chmod +x script_1.sh
chmod +x script_2.sh
...
chmod +x script_n.sh

(You can put the scripts all on one line for chmod, but I found separate lines easier to work with in vim and with shell script commands.)

And now your unzip one-liner becomes:

unzip zip_name.zip && source grant_perms.sh

Note that since you are using source to run grant_perms.sh, it doesn't need execute permission

How To Set A JS object property name from a variable

Use a variable as an object key

let key = 'myKey';

let data = {[key] : 'name1'; }

See How to iterete on your object here

Whitespaces in java

boolean whitespaceSearchRegExp(String input) {

    return java.util.regex.Pattern.compile("\\s").matcher(input).find();

} 

How do you rename a MongoDB database?

There is no mechanism to re-name databases. The currently accepted answer at time of writing is factually correct and offers some interesting background detail as to the excuse upstream, but offers no suggestions for replicating the behavior. Other answers point at copyDatabase, which is no longer an option as the functionality has been removed in 4.0. I've updated SERVER-701 with my notes and incredulity.

Equivalent behavior involves mongodump and mongorestore in a bit of a dance:

  1. Export your data, making note of the "namespaces" in use. For example, on one of my datasets, I have a collection with the namespace byzmcbehoomrfjcs9vlj.Analytics — that prefix (actually the database name) will be needed in the next step.

  2. Import your data, supplying --nsFrom and --nsTo arguments. (Documentation.) Continuing with my above hypothetical (and extremely unreadable) example, to restore to a more sensical name, I invoke:

mongorestore --archive=backup.agz --gzip --drop \
    --nsFrom 'byzmcbehoomrfjcs9vlj.*' --nsTo 'rita.*'

Some may also point at the --db argument to mongorestore, however this, too, is deprecated and triggers a warning against use on non-BSON folder backups with a completely erroneous suggestion to "use --nsInclude instead". The above namespace translation is equivalent to use of the --db option, and is the correct namespace manipulation setup to use as we are not attempting to filter what is being restored.

How to add "Maven Managed Dependencies" library in build path eclipse?

Likely quite simple but best way is to edit manually the file .classpath at the root of your project folder with something like

<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
        <attributes>
            <attribute name="maven.pomderived" value="true"/>
            <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
        </attributes>
    </classpathentry>

when you want to have jar in your WEB-IN/lib folder (case for a web app)

Domain Account keeping locking out with correct password every few minutes

Try this solution from http://social.technet.microsoft.com/Forums/en/w7itprosecurity/thread/e1ef04fa-6aea-47fe-9392-45929239bd68

Microsoft Support found the problem for us. Our domain accounts were locking when a Windows 7 computer was started. The Windows 7 computer had a hidden old password from that domain account. There are passwords that can be stored in the SYSTEM context that can't be seen in the normal Credential Manager view.

Download PsExec.exe from http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx and copy it to C:\Windows\System32.

From a command prompt run: psexec -i -s -d cmd.exe

From the new DOS window run: rundll32 keymgr.dll,KRShowKeyMgr

Remove any items that appear in the list of Stored User Names and Passwords. Restart the computer.

Invoking a static method using reflection

public class Add {
    static int add(int a, int b){
        return (a+b);
    }
}

In the above example, 'add' is a static method that takes two integers as arguments.

Following snippet is used to call 'add' method with input 1 and 2.

Class myClass = Class.forName("Add");
Method method = myClass.getDeclaredMethod("add", int.class, int.class);
Object result = method.invoke(null, 1, 2);

Reference link.

Concat a string to SELECT * MySql

You cannot concatenate multiple fields with a string. You need to select a field instand of all (*).

Shorter syntax for casting from a List<X> to a List<Y>?

If X can really be cast to Y you should be able to use

List<Y> listOfY = listOfX.Cast<Y>().ToList();

Some things to be aware of (H/T to commenters!)

Tomcat Server not starting with in 45 seconds

I had tried increasing the Server Start up time for tomcat server, removed server and created new server, removed server and changed run-time environment configurations. Those thing didn't work for me. At last, i found deployment descriptor(url pattern of servlet-mapping) is the one that making the trouble.

PHP checkbox set to check based on database value

Use checked="checked" attribute if you want your checkbox to be checked.

how to calculate percentage in python

I know I am late, but if you want to know the easiest way, you could do a code like this:

number = 100
right_questions = 1
control = 100
c = control / number
cc = right_questions * c
print float(cc)

You can change up the number score, and right_questions. It will tell you the percent.

How do I update the GUI from another thread?

You'll need to Invoke the method on the GUI thread. You can do that by calling Control.Invoke.

For example:

delegate void UpdateLabelDelegate (string message);

void UpdateLabel (string message)
{
    if (InvokeRequired)
    {
         Invoke (new UpdateLabelDelegate (UpdateLabel), message);
         return;
    }

    MyLabelControl.Text = message;
}

How can I configure Logback to log different levels for a logger to different destinations?

I believe this would be the simplest solution:

<configuration>
    <contextName>selenium-plugin</contextName>
    <!-- Logging configuration -->  
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <Target>System.out</Target>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <encoder>
            <pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%level] %msg%n</pattern>
        </encoder>
    </appender>
    <appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
            <Target>System.err</Target>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <encoder> 
            <pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%level] [%thread] %logger{10} [%file:%line] %msg%n</pattern> 
        </encoder> 
    </appender>
    <root level="INFO">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="STDERR" />
    </root>
</configuration>

How to work on UAC when installing XAMPP

To disable UAC go to Start>Control Panel>User Accounts there you will find an option Turn User Account Control on or off just click on it and uncheck User Account Control to help protect your computer click OK.

Please refer to this link : https://community.apachefriends.org/f/viewtopic.php?f=16&t=45364

Can you pass parameters to an AngularJS controller on creation?

The view should not dictate config

In Angular, the template should never dictate configuration, which is inherently what people desire when they want to pass arguments to controllers from a template file. This becomes a slippery slope. If config settings are hard-coded in templates (such as by a directive or controller argument attribute), you can no longer re-use that template for anything but that single use. Soon you'll want to re-use that template, but with different config and now in order to do so you'll either be pre-processing the templates to inject variables before it gets passed to angular or using massive directives to spit out giant blocks of HTML so you re-use all of the controller HTML except for the wrapper div and it's arguments. For small projects it's no big deal. For something big (what angular excels at), it gets ugly quick.

The Alternative: Modules

This type of configuration is what modules were designed to handle. In many angular tutorials people have a single module for their entire application, but really the system is designed and fully supports many small modules each which wrap small pieces of the total application. Ideally, controllers, modules etc would be declared in separate files and stitched together in specific re-usable chunks. When your application is designed this way, you get a lot of re-use in addition to easy controller arguments.

The example below has 2 modules, re-using the same controller, but each with their own config settings. That config settings are passed in via dependency injection using module.value. This adheres to the angular way because we have the following: constructor dependency injection, reusable controller code, reusable controller templates (the controller div could easily be included with ng-include), easily unit-testable system without HTML, and lastly re-usable modules as the vehicle for stitching the pieces together.

Here's an example:

<!-- index.html -->
<div id="module1">
    <div ng-controller="MyCtrl">
        <div>{{foo}}</div>
    </div>
</div>
<div id="module2">
    <div ng-controller="MyCtrl">
        <div>{{foo}}</div>
    </div>
</div>
<script>
    // part of this template, or a JS file designed to be used with this template
    angular.element(document).ready(function() {
        angular.bootstrap(document.getElementById("module1"), ["module1"]);
        angular.bootstrap(document.getElementById("module2"), ["module2"]);
    });
</script>

<!-- scripts which will likely in be in their seperate files -->
<script>
    // MyCtrl.js
    var MyCtrl = function($scope, foo) {
    $scope.foo = foo;
    }

    MyCtrl.$inject = ["$scope", "foo"];

    // Module1.js
    var module1 = angular.module('module1', []);
    module1.value("foo", "fooValue1");
    module1.controller("MyCtrl", MyCtrl);

    // Module2.js file
    var module2 = angular.module('module2', []);
    module2.value("foo", "fooValue2");
    module2.controller("MyCtrl", MyCtrl);
</script>

See it in action: jsFiddle.

What is the difference between fastcgi and fpm?

What Anthony says is absolutely correct, but I'd like to add that your experience will likely show a lot better performance and efficiency (due not to fpm-vs-fcgi but more to the implementation of your httpd).

For example, I had a quad-core machine running lighttpd + fcgi humming along nicely. I upgraded to a 16-core machine to cope with growth, and two things exploded: RAM usage, and segfaults. I found myself restarting lighttpd every 30 minutes to keep the website up.

I switched to php-fpm and nginx, and RAM usage dropped from >20GB to 2GB. Segfaults disappeared as well. After doing some research, I learned that lighttpd and fcgi don't get along well on multi-core machines under load, and also have memory leak issues in certain instances.

Is this due to php-fpm being better than fcgi? Not entirely, but how you hook into php-fpm seems to be a whole heckuva lot more efficient than how you serve via fcgi.

PHP - Check if the page run on Mobile or Desktop browser

I used Robert Lee`s answer and it works great! Just writing down the complete function i'm using:

function isMobileDevice(){
    $aMobileUA = array(
        '/iphone/i' => 'iPhone', 
        '/ipod/i' => 'iPod', 
        '/ipad/i' => 'iPad', 
        '/android/i' => 'Android', 
        '/blackberry/i' => 'BlackBerry', 
        '/webos/i' => 'Mobile'
    );

    //Return true if Mobile User Agent is detected
    foreach($aMobileUA as $sMobileKey => $sMobileOS){
        if(preg_match($sMobileKey, $_SERVER['HTTP_USER_AGENT'])){
            return true;
        }
    }
    //Otherwise return false..  
    return false;
}

Best practice multi language website

I will suggest you not to really depend of database for translation it could be really a messy task and could be a extreme problem in case of data encoding.

I had face similar issue while ago and written following class to solve my problem

Object: Locale\Locale

<?php

  namespace Locale;

  class Locale{

// Following array stolen from Zend Framework
public $country_to_locale = array(
    'AD' => 'ca_AD',
    'AE' => 'ar_AE',
    'AF' => 'fa_AF',
    'AG' => 'en_AG',
    'AI' => 'en_AI',
    'AL' => 'sq_AL',
    'AM' => 'hy_AM',
    'AN' => 'pap_AN',
    'AO' => 'pt_AO',
    'AQ' => 'und_AQ',
    'AR' => 'es_AR',
    'AS' => 'sm_AS',
    'AT' => 'de_AT',
    'AU' => 'en_AU',
    'AW' => 'nl_AW',
    'AX' => 'sv_AX',
    'AZ' => 'az_Latn_AZ',
    'BA' => 'bs_BA',
    'BB' => 'en_BB',
    'BD' => 'bn_BD',
    'BE' => 'nl_BE',
    'BF' => 'mos_BF',
    'BG' => 'bg_BG',
    'BH' => 'ar_BH',
    'BI' => 'rn_BI',
    'BJ' => 'fr_BJ',
    'BL' => 'fr_BL',
    'BM' => 'en_BM',
    'BN' => 'ms_BN',
    'BO' => 'es_BO',
    'BR' => 'pt_BR',
    'BS' => 'en_BS',
    'BT' => 'dz_BT',
    'BV' => 'und_BV',
    'BW' => 'en_BW',
    'BY' => 'be_BY',
    'BZ' => 'en_BZ',
    'CA' => 'en_CA',
    'CC' => 'ms_CC',
    'CD' => 'sw_CD',
    'CF' => 'fr_CF',
    'CG' => 'fr_CG',
    'CH' => 'de_CH',
    'CI' => 'fr_CI',
    'CK' => 'en_CK',
    'CL' => 'es_CL',
    'CM' => 'fr_CM',
    'CN' => 'zh_Hans_CN',
    'CO' => 'es_CO',
    'CR' => 'es_CR',
    'CU' => 'es_CU',
    'CV' => 'kea_CV',
    'CX' => 'en_CX',
    'CY' => 'el_CY',
    'CZ' => 'cs_CZ',
    'DE' => 'de_DE',
    'DJ' => 'aa_DJ',
    'DK' => 'da_DK',
    'DM' => 'en_DM',
    'DO' => 'es_DO',
    'DZ' => 'ar_DZ',
    'EC' => 'es_EC',
    'EE' => 'et_EE',
    'EG' => 'ar_EG',
    'EH' => 'ar_EH',
    'ER' => 'ti_ER',
    'ES' => 'es_ES',
    'ET' => 'en_ET',
    'FI' => 'fi_FI',
    'FJ' => 'hi_FJ',
    'FK' => 'en_FK',
    'FM' => 'chk_FM',
    'FO' => 'fo_FO',
    'FR' => 'fr_FR',
    'GA' => 'fr_GA',
    'GB' => 'en_GB',
    'GD' => 'en_GD',
    'GE' => 'ka_GE',
    'GF' => 'fr_GF',
    'GG' => 'en_GG',
    'GH' => 'ak_GH',
    'GI' => 'en_GI',
    'GL' => 'iu_GL',
    'GM' => 'en_GM',
    'GN' => 'fr_GN',
    'GP' => 'fr_GP',
    'GQ' => 'fan_GQ',
    'GR' => 'el_GR',
    'GS' => 'und_GS',
    'GT' => 'es_GT',
    'GU' => 'en_GU',
    'GW' => 'pt_GW',
    'GY' => 'en_GY',
    'HK' => 'zh_Hant_HK',
    'HM' => 'und_HM',
    'HN' => 'es_HN',
    'HR' => 'hr_HR',
    'HT' => 'ht_HT',
    'HU' => 'hu_HU',
    'ID' => 'id_ID',
    'IE' => 'en_IE',
    'IL' => 'he_IL',
    'IM' => 'en_IM',
    'IN' => 'hi_IN',
    'IO' => 'und_IO',
    'IQ' => 'ar_IQ',
    'IR' => 'fa_IR',
    'IS' => 'is_IS',
    'IT' => 'it_IT',
    'JE' => 'en_JE',
    'JM' => 'en_JM',
    'JO' => 'ar_JO',
    'JP' => 'ja_JP',
    'KE' => 'en_KE',
    'KG' => 'ky_Cyrl_KG',
    'KH' => 'km_KH',
    'KI' => 'en_KI',
    'KM' => 'ar_KM',
    'KN' => 'en_KN',
    'KP' => 'ko_KP',
    'KR' => 'ko_KR',
    'KW' => 'ar_KW',
    'KY' => 'en_KY',
    'KZ' => 'ru_KZ',
    'LA' => 'lo_LA',
    'LB' => 'ar_LB',
    'LC' => 'en_LC',
    'LI' => 'de_LI',
    'LK' => 'si_LK',
    'LR' => 'en_LR',
    'LS' => 'st_LS',
    'LT' => 'lt_LT',
    'LU' => 'fr_LU',
    'LV' => 'lv_LV',
    'LY' => 'ar_LY',
    'MA' => 'ar_MA',
    'MC' => 'fr_MC',
    'MD' => 'ro_MD',
    'ME' => 'sr_Latn_ME',
    'MF' => 'fr_MF',
    'MG' => 'mg_MG',
    'MH' => 'mh_MH',
    'MK' => 'mk_MK',
    'ML' => 'bm_ML',
    'MM' => 'my_MM',
    'MN' => 'mn_Cyrl_MN',
    'MO' => 'zh_Hant_MO',
    'MP' => 'en_MP',
    'MQ' => 'fr_MQ',
    'MR' => 'ar_MR',
    'MS' => 'en_MS',
    'MT' => 'mt_MT',
    'MU' => 'mfe_MU',
    'MV' => 'dv_MV',
    'MW' => 'ny_MW',
    'MX' => 'es_MX',
    'MY' => 'ms_MY',
    'MZ' => 'pt_MZ',
    'NA' => 'kj_NA',
    'NC' => 'fr_NC',
    'NE' => 'ha_Latn_NE',
    'NF' => 'en_NF',
    'NG' => 'en_NG',
    'NI' => 'es_NI',
    'NL' => 'nl_NL',
    'NO' => 'nb_NO',
    'NP' => 'ne_NP',
    'NR' => 'en_NR',
    'NU' => 'niu_NU',
    'NZ' => 'en_NZ',
    'OM' => 'ar_OM',
    'PA' => 'es_PA',
    'PE' => 'es_PE',
    'PF' => 'fr_PF',
    'PG' => 'tpi_PG',
    'PH' => 'fil_PH',
    'PK' => 'ur_PK',
    'PL' => 'pl_PL',
    'PM' => 'fr_PM',
    'PN' => 'en_PN',
    'PR' => 'es_PR',
    'PS' => 'ar_PS',
    'PT' => 'pt_PT',
    'PW' => 'pau_PW',
    'PY' => 'gn_PY',
    'QA' => 'ar_QA',
    'RE' => 'fr_RE',
    'RO' => 'ro_RO',
    'RS' => 'sr_Cyrl_RS',
    'RU' => 'ru_RU',
    'RW' => 'rw_RW',
    'SA' => 'ar_SA',
    'SB' => 'en_SB',
    'SC' => 'crs_SC',
    'SD' => 'ar_SD',
    'SE' => 'sv_SE',
    'SG' => 'en_SG',
    'SH' => 'en_SH',
    'SI' => 'sl_SI',
    'SJ' => 'nb_SJ',
    'SK' => 'sk_SK',
    'SL' => 'kri_SL',
    'SM' => 'it_SM',
    'SN' => 'fr_SN',
    'SO' => 'sw_SO',
    'SR' => 'srn_SR',
    'ST' => 'pt_ST',
    'SV' => 'es_SV',
    'SY' => 'ar_SY',
    'SZ' => 'en_SZ',
    'TC' => 'en_TC',
    'TD' => 'fr_TD',
    'TF' => 'und_TF',
    'TG' => 'fr_TG',
    'TH' => 'th_TH',
    'TJ' => 'tg_Cyrl_TJ',
    'TK' => 'tkl_TK',
    'TL' => 'pt_TL',
    'TM' => 'tk_TM',
    'TN' => 'ar_TN',
    'TO' => 'to_TO',
    'TR' => 'tr_TR',
    'TT' => 'en_TT',
    'TV' => 'tvl_TV',
    'TW' => 'zh_Hant_TW',
    'TZ' => 'sw_TZ',
    'UA' => 'uk_UA',
    'UG' => 'sw_UG',
    'UM' => 'en_UM',
    'US' => 'en_US',
    'UY' => 'es_UY',
    'UZ' => 'uz_Cyrl_UZ',
    'VA' => 'it_VA',
    'VC' => 'en_VC',
    'VE' => 'es_VE',
    'VG' => 'en_VG',
    'VI' => 'en_VI',
    'VN' => 'vn_VN',
    'VU' => 'bi_VU',
    'WF' => 'wls_WF',
    'WS' => 'sm_WS',
    'YE' => 'ar_YE',
    'YT' => 'swb_YT',
    'ZA' => 'en_ZA',
    'ZM' => 'en_ZM',
    'ZW' => 'sn_ZW'
);

/**
 * Store the transaltion for specific languages
 *
 * @var array
 */
protected $translation = array();

/**
 * Current locale
 *
 * @var string
 */
protected $locale;

/**
 * Default locale
 *
 * @var string
 */
protected $default_locale;

/**
 *
 * @var string
 */
protected $locale_dir;

/**
 * Construct.
 *
 *
 * @param string $locale_dir            
 */
public function __construct($locale_dir)
{
    $this->locale_dir = $locale_dir;
}

/**
 * Set the user define localte
 *
 * @param string $locale            
 */
public function setLocale($locale = null)
{
    $this->locale = $locale;

    return $this;
}

/**
 * Get the user define locale
 *
 * @return string
 */
public function getLocale()
{
    return $this->locale;
}

/**
 * Get the Default locale
 *
 * @return string
 */
public function getDefaultLocale()
{
    return $this->default_locale;
}

/**
 * Set the default locale
 *
 * @param string $locale            
 */
public function setDefaultLocale($locale)
{
    $this->default_locale = $locale;

    return $this;
}

/**
 * Determine if transltion exist or translation key exist
 *
 * @param string $locale            
 * @param string $key            
 * @return boolean
 */
public function hasTranslation($locale, $key = null)
{
    if (null == $key && isset($this->translation[$locale])) {
        return true;
    } elseif (isset($this->translation[$locale][$key])) {
        return true;
    }

    return false;
}

/**
 * Get the transltion for required locale or transtion for key
 *
 * @param string $locale            
 * @param string $key            
 * @return array
 */
public function getTranslation($locale, $key = null)
{
    if (null == $key && $this->hasTranslation($locale)) {
        return $this->translation[$locale];
    } elseif ($this->hasTranslation($locale, $key)) {
        return $this->translation[$locale][$key];
    }

    return array();
}

/**
 * Set the transtion for required locale
 *
 * @param string $locale
 *            Language code
 * @param string $trans
 *            translations array
 */
public function setTranslation($locale, $trans = array())
{
    $this->translation[$locale] = $trans;
}

/**
 * Remove transltions for required locale
 *
 * @param string $locale            
 */
public function removeTranslation($locale = null)
{
    if (null === $locale) {
        unset($this->translation);
    } else {
        unset($this->translation[$locale]);
    }
}

/**
 * Initialize locale
 *
 * @param string $locale            
 */
public function init($locale = null, $default_locale = null)
{
    // check if previously set locale exist or not
    $this->init_locale();
    if ($this->locale != null) {
        return;
    }

    if ($locale == null || (! preg_match('#^[a-z]+_[a-zA-Z_]+$#', $locale) && ! preg_match('#^[a-z]+_[a-zA-Z]+_[a-zA-Z_]+$#', $locale))) {
        $this->detectLocale();
    } else {
        $this->locale = $locale;
    }

    $this->init_locale();
}

/**
 * Attempt to autodetect locale
 *
 * @return void
 */
private function detectLocale()
{
    $locale = false;

    // GeoIP
    if (function_exists('geoip_country_code_by_name') && isset($_SERVER['REMOTE_ADDR'])) {

        $country = geoip_country_code_by_name($_SERVER['REMOTE_ADDR']);

        if ($country) {

            $locale = isset($this->country_to_locale[$country]) ? $this->country_to_locale[$country] : false;
        }
    }

    // Try detecting locale from browser headers
    if (! $locale) {

        if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {

            $languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);

            foreach ($languages as $lang) {

                $lang = str_replace('-', '_', trim($lang));

                if (strpos($lang, '_') === false) {

                    if (isset($this->country_to_locale[strtoupper($lang)])) {

                        $locale = $this->country_to_locale[strtoupper($lang)];
                    }
                } else {

                    $lang = explode('_', $lang);

                    if (count($lang) == 3) {
                        // language_Encoding_COUNTRY
                        $this->locale = strtolower($lang[0]) . ucfirst($lang[1]) . strtoupper($lang[2]);
                    } else {
                        // language_COUNTRY
                        $this->locale = strtolower($lang[0]) . strtoupper($lang[1]);
                    }

                    return;
                }
            }
        }
    }

    // Resort to default locale specified in config file
    if (! $locale) {
        $this->locale = $this->default_locale;
    }
}

/**
 * Check if config for selected locale exists
 *
 * @return void
 */
private function init_locale()
{
    if (! file_exists(sprintf('%s/%s.php', $this->locale_dir, $this->locale))) {
        $this->locale = $this->default_locale;
    }
}

/**
 * Load a Transtion into array
 *
 * @return void
 */
private function loadTranslation($locale = null, $force = false)
{
    if ($locale == null)
        $locale = $this->locale;

    if (! $this->hasTranslation($locale)) {
        $this->setTranslation($locale, include (sprintf('%s/%s.php', $this->locale_dir, $locale)));
    }
}

/**
 * Translate a key
 *
 * @param
 *            string Key to be translated
 * @param
 *            string optional arguments
 * @return string
 */
public function translate($key)
{
    $this->init();
    $this->loadTranslation($this->locale);

    if (! $this->hasTranslation($this->locale, $key)) {

        if ($this->locale !== $this->default_locale) {

            $this->loadTranslation($this->default_locale);

            if ($this->hasTranslation($this->default_locale, $key)) {

                $translation = $this->getTranslation($this->default_locale, $key);
            } else {
                // return key as it is or log error here
                return $key;
            }
        } else {
            return $key;
        }
    } else {
        $translation = $this->getTranslation($this->locale, $key);
    }
    // Replace arguments
    if (false !== strpos($translation, '{a:')) {
        $replace = array();
        $args = func_get_args();
        for ($i = 1, $max = count($args); $i < $max; $i ++) {
            $replace['{a:' . $i . '}'] = $args[$i];
        }
        // interpolate replacement values into the messsage then return
        return strtr($translation, $replace);
    }

    return $translation;
  }
}

Usage

 <?php
    ## /locale/en.php

    return array(
       'name' => 'Hello {a:1}'
       'name_full' => 'Hello {a:1} {a:2}'
   );

$locale = new Locale(__DIR__ . '/locale');
$locale->setLocale('en');// load en.php from locale dir
//want to work with auto detection comment $locale->setLocale('en');

echo $locale->translate('name', 'Foo');
echo $locale->translate('name', 'Foo', 'Bar');

How it works

{a:1} is replaced by 1st argument passed to method Locale::translate('key_name','arg1') {a:2} is replaced by 2nd argument passed to method Locale::translate('key_name','arg1','arg2')

How detection works

  • By default if geoip is installed then it will return country code by geoip_country_code_by_name and if geoip is not installed the fallback to HTTP_ACCEPT_LANGUAGE header

How to set lifetime of session

The sessions on PHP works with a Cookie type session, while on server-side the session information is constantly deleted.

For set the time life in php, you can use the function session_set_cookie_params, before the session_start:

session_set_cookie_params(3600,"/");
session_start();

For ex, 3600 seconds is one hour, for 2 hours 3600*2 = 7200.

But it is session cookie, the browser can expire it by itself, if you want to save large time sessions (like remember login), you need to save the data in the server and a standard cookie in the client side.

You can have a Table "Sessions":

  • session_id int
  • session_hash varchar(20)
  • session_data text

And validating a Cookie, you save the "session id" and the "hash" (for security) on client side, and you can save the session's data on the server side, ex:

On login:

setcookie('sessid', $sessionid, 604800);      // One week or seven days
setcookie('sesshash', $sessionhash, 604800);  // One week or seven days
// And save the session data:
saveSessionData($sessionid, $sessionhash, serialize($_SESSION)); // saveSessionData is your function

If the user return:

if (isset($_COOKIE['sessid'])) {
    if (valide_session($_COOKIE['sessid'], $_COOKIE['sesshash'])) {
        $_SESSION = unserialize(get_session_data($_COOKIE['sessid']));
    } else {
        // Dont validate the hash, possible session falsification
    }
}

Obviously, save all session/cookies calls, before sending data.

Why do I need to do `--set-upstream` all the time?

You can set up a really good alias that can handle this without the overly verbose syntax.

I have the following alias in ~/.gitconfig:

po = "!git push -u origin \"$(git rev-parse --abbrev-ref HEAD)\""

After making a commit on a new branch, you can push your new branch by simply typing the command:

git po

Calling a function when ng-repeat has finished

If you need to call different functions for different ng-repeats on the same controller you can try something like this:

The directive:

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.broadcasteventname ? attr.broadcasteventname : 'ngRepeatFinished');
            });
            }
        }
    }
});

In your controller, catch events with $on:

$scope.$on('ngRepeatBroadcast1', function(ngRepeatFinishedEvent) {
// Do something
});

$scope.$on('ngRepeatBroadcast2', function(ngRepeatFinishedEvent) {
// Do something
});

In your template with multiple ng-repeat

<div ng-repeat="item in collection1" on-finish-render broadcasteventname="ngRepeatBroadcast1">
    <div>{{item.name}}}<div>
</div>

<div ng-repeat="item in collection2" on-finish-render broadcasteventname="ngRepeatBroadcast2">
    <div>{{item.name}}}<div>
</div>

NSDate get year/month/day

New In iOS 8

ObjC

NSDate *date = [NSDate date];
NSInteger era, year, month, day;
[[NSCalendar currentCalendar] getEra:&era year:&year month:&month day:&day fromDate:date];

Swift

let date = NSDate.init()
var era = 0, year = 0, month = 0, day = 0
NSCalendar.currentCalendar().getEra(&era, year:&year, month:&month, day:&day, fromDate: date)

How to set up Spark on Windows?

The guide by Ani Menon (thx!) almost worked for me on windows 10, i just had to get a newer winutils.exe off that git (currently hadoop-2.8.1): https://github.com/steveloughran/winutils

Uncaught TypeError: Cannot read property 'msie' of undefined - jQuery tools

As I don't plan to support old MS IE versions at all, I've simply replaced all references to browser.msie with false. Not a nice solution, I know, but it works for me.

(Actually, they appeared as !browser.msie, which could be omitted from the conditions.)

How to prevent Google Colab from disconnecting?

the following LATEST solution works for me:

function ClickConnect(){
  colab.config
  console.log("Connnect Clicked - Start"); 
  document.querySelector("#top-toolbar > colab-connect-button").shadowRoot.querySelector("#connect").click();
  console.log("Connnect Clicked - End");
};
setInterval(ClickConnect, 60000)

HTTP GET request in JavaScript?

Ajax

You'd be best off using a library such as Prototype or jQuery.

How to convert an image to base64 encoding?

<img src="data:image/png;base64,<?php echo base64_encode(file_get_contents("IMAGE URL HERE")) ?>">

I was trying to use this resource but kept getting an error, I found the code above worked perfectly.

Just replaced IMAGE URL HERE with the URL of your image - http://www.website.com/image.jpg

one line if statement in php

use the ternary operator ?:

change this

<?php if ($requestVars->_name == '') echo $redText; ?>

with

<?php echo ($requestVars->_name == '') ? $redText : ''; ?>

In short

// (Condition)?(thing's to do if condition true):(thing's to do if condition false);

DD/MM/YYYY Date format in Moment.js

This actually worked for me:

moment(mydate).format('L');

Oracle query to fetch column names

in oracle you can use

desc users

to display all columns containing in users table

How to detect current state within directive

Update:

This answer was for a much older release of Ui-Router. For the more recent releases (0.2.5+), please use the helper directive ui-sref-active. Details here.


Original Answer:

Include the $state service in your controller. You can assign this service to a property on your scope.

An example:

$scope.$state = $state;

Then to get the current state in your templates:

$state.current.name

To check if a state is current active:

$state.includes('stateName'); 

This method returns true if the state is included, even if it's part of a nested state. If you were at a nested state, user.details, and you checked for $state.includes('user'), it'd return true.

In your class example, you'd do something like this:

ng-class="{active: $state.includes('stateName')}"

How to create web service (server & Client) in Visual Studio 2012?

--- create a ws server vs2012 upd 3

  1. new project

  2. choose .net framework 3.5

  3. asp.net web service application

  4. right click on the project root

  5. choose add service reference

  6. choose wsdl

--- how can I create a ws client from a wsdl file?

I´ve a ws server Axis2 under tomcat 7 and I want to test the compatibility

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

Because otherwise scanf will think you are passing a pointer to a float which is a smaller size than a double, and it will return an incorrect value.

Assert equals between 2 Lists in Junit

assertEquals(expected, result); works for me. Since this function gets two objects, you can pass anything to it.

public static void assertEquals(Object expected, Object actual) {
    AssertEquals.assertEquals(expected, actual);
}

Identifying Exception Type in a handler Catch Block

try
{
    // Some code
}
catch (Web2PDFException ex)
{
    // It's your special exception
}
catch (Exception ex)
{
    // Any other exception here
}

FPDF error: Some data has already been output, can't send PDF

For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:

<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

While this will not (note the leading space before the opening <? tag)

 <?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

Also, this will not work either (the echo will break it):

<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.


add ob_start (); at the top and at the end add ob_end_flush();

<?php
    ob_start();
    require('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,'Hello World!');
    $pdf->Output();
    ob_end_flush(); 
?>

give me an error as below:
FPDF error: Some data has already been output, can't send PDF

to over come this error: go to fpdf.php in that,goto line number 996

function Output($name='', $dest='')

after that make changes like this:

function Output($name='', $dest='') {   
    ob_clean();     //Output PDF to so

Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.

<?

while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);

?>

cheers :-)


In my case i had set:

ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);

When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off the display_errors option, the report was generated successfully.

how to display a div triggered by onclick event

function showstuff(boxid){
   document.getElementById(boxid).style.visibility="visible";
}
<button onclick="showstuff('id_to_show');" />

This will help you, I think.

How do I truly reset every setting in Visual Studio 2012?

Visual Studio has multiple flags to reset various settings:

  • /ResetUserData - (AFAICT) Removes all user settings and makes you set them again. This will get you the initial prompt for settings again, clear your recent project history, etc.
  • /ResetSettings - Restores the IDE's default settings, optionally resets to the specified VSSettings file.
  • /ResetSkipPkgs - Clears all SkipLoading tags added to VSPackages.
  • /ResetAddin - Removes commands and command UI associated with the specified Add-in.

The last three show up when running devenv.exe /?. The first one seems to be undocumented/unsupported/the big hammer. From here:

Disclaimer: you will lose all your environment settings and customizations if you use this switch. It is for this reason that this switch is not officially supported and Microsoft does not advertise this switch to the public (you won't see this switch if you type devenv.exe /? in the command prompt). You should only use this switch as the last resort if you are experiencing an environment problem, and make sure you back up your environment settings by exporting them before using this switch.

How to draw a path on a map using kml file?

Thank Mathias Lin, tested and it works!

In addition, sample implementation of Mathias's method in activity can be as follows.

public class DirectionMapActivity extends MapActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.directionmap);

        MapView mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);

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

        String locationProvider = LocationManager.NETWORK_PROVIDER;
        Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);

        StringBuilder urlString = new StringBuilder();
        urlString.append("http://maps.google.com/maps?f=d&hl=en");
        urlString.append("&saddr=");//from
        urlString.append( Double.toString(lastKnownLocation.getLatitude() ));
        urlString.append(",");
        urlString.append( Double.toString(lastKnownLocation.getLongitude() ));
        urlString.append("&daddr=");//to
        urlString.append( Double.toString((double)dest[0]/1.0E6 ));
        urlString.append(",");
        urlString.append( Double.toString((double)dest[1]/1.0E6 ));
        urlString.append("&ie=UTF8&0&om=0&output=kml");

        try{
            // setup the url
            URL url = new URL(urlString.toString());
            // create the factory
            SAXParserFactory factory = SAXParserFactory.newInstance();
            // create a parser
            SAXParser parser = factory.newSAXParser();
            // create the reader (scanner)
            XMLReader xmlreader = parser.getXMLReader();
            // instantiate our handler
            NavigationSaxHandler navSaxHandler = new NavigationSaxHandler();
            // assign our handler
            xmlreader.setContentHandler(navSaxHandler);
            // get our data via the url class
            InputSource is = new InputSource(url.openStream());
            // perform the synchronous parse           
            xmlreader.parse(is);
            // get the results - should be a fully populated RSSFeed instance, or null on error
            NavigationDataSet ds = navSaxHandler.getParsedData();

            // draw path
            drawPath(ds, Color.parseColor("#add331"), mapView );

            // find boundary by using itemized overlay
            GeoPoint destPoint = new GeoPoint(dest[0],dest[1]);
            GeoPoint currentPoint = new GeoPoint( new Double(lastKnownLocation.getLatitude()*1E6).intValue()
                                                ,new Double(lastKnownLocation.getLongitude()*1E6).intValue() );

            Drawable dot = this.getResources().getDrawable(R.drawable.pixel);
            MapItemizedOverlay bgItemizedOverlay = new MapItemizedOverlay(dot,this);
            OverlayItem currentPixel = new OverlayItem(destPoint, null, null );
            OverlayItem destPixel = new OverlayItem(currentPoint, null, null );
            bgItemizedOverlay.addOverlay(currentPixel);
            bgItemizedOverlay.addOverlay(destPixel);

            // center and zoom in the map
            MapController mc = mapView.getController();
            mc.zoomToSpan(bgItemizedOverlay.getLatSpanE6()*2,bgItemizedOverlay.getLonSpanE6()*2);
            mc.animateTo(new GeoPoint(
                    (currentPoint.getLatitudeE6() + destPoint.getLatitudeE6()) / 2
                    , (currentPoint.getLongitudeE6() + destPoint.getLongitudeE6()) / 2));

        } catch(Exception e) {
            Log.d("DirectionMap","Exception parsing kml.");
        }

    }
    // and the rest of the methods in activity, e.g. drawPath() etc...

MapItemizedOverlay.java

public class MapItemizedOverlay extends ItemizedOverlay{
    private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
    private Context mContext;

    public MapItemizedOverlay(Drawable defaultMarker, Context context) {
          super(boundCenterBottom(defaultMarker));
          mContext = context;
    }

    public void addOverlay(OverlayItem overlay) {
        mOverlays.add(overlay);
        populate();
    }

    @Override
    protected OverlayItem createItem(int i) {
      return mOverlays.get(i);
    }

    @Override
    public int size() {
      return mOverlays.size();
    }

}

delete word after or around cursor in VIM

To delete all characters between two whitespaces, in normal mode:

daW

To delete just one word:

daw 

Setting action for back button in navigation controller

Using Swift:

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    if self.navigationController?.topViewController != self {
        print("back button tapped")
    }
}

How do I check in python if an element of a list is empty?

If you want to know if list element at index i is set or not, you can simply check the following:

if len(l)<=i:
    print ("empty")

If you are looking for something like what is a NULL-Pointer or a NULL-Reference in other languages, Python offers you None. That is you can write:

l[0] = None # here, list element at index 0 has to be set already
l.append(None) # here the list can be empty before
# checking
if l[i] == None:
    print ("list has actually an element at position i, which is None")

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

Have a look at the GROUP_CONCAT project on Github, I think I does exactly what you are searching for:

This project contains a set of SQLCLR User-defined Aggregate functions (SQLCLR UDAs) that collectively offer similar functionality to the MySQL GROUP_CONCAT function. There are multiple functions to ensure the best performance based on the functionality required...

How to tell if a file is git tracked (by shell exit code)?

I suggest a custom alias on you .gitconfig.

You have to way to do:

1) With git command:

git config --global alias.check-file <command>

2) Editing ~/.gitconfig and add this line on alias section:

[alias]
    check-file = "!f() { if [ $# -eq 0 ]; then echo 'Filename missing!'; else tracked=$(git ls-files ${1}); if [[ -z ${tracked} ]]; then echo 'File not tracked'; else echo 'File tracked'; fi; fi;  };  f"

Once launched command (1) or saved file (2), on your workspace you can test it:

$ git check-file
$ Filename missing 

$ git check-file README.md
$ File tracked 

$ git check-file foo
$ File not tracked

Is there a Google Keep API?

No there's not and developers still don't know why google doesn't pay attention to this request!

As you can see in this link it's one of the most popular issues with many stars in google code but still no response from google! You can also add stars to this issue, maybe google hears that!

How to run a C# console application with the console hidden

If you're interested in the output, you can use this function:

private static string ExecCommand(string filename, string arguments)
{
    Process process = new Process();
    ProcessStartInfo psi = new ProcessStartInfo(filename);
    psi.Arguments = arguments;
    psi.CreateNoWindow = true;
    psi.RedirectStandardOutput = true;
    psi.RedirectStandardError = true;
    psi.UseShellExecute = false;
    process.StartInfo = psi;

    StringBuilder output = new StringBuilder();
    process.OutputDataReceived += (sender, e) => { output.AppendLine(e.Data); };
    process.ErrorDataReceived += (sender, e) => { output.AppendLine(e.Data); };

    // run the process
    process.Start();

    // start reading output to events
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();

    // wait for process to exit
    process.WaitForExit();

    if (process.ExitCode != 0)
        throw new Exception("Command " + psi.FileName + " returned exit code " + process.ExitCode);

    return output.ToString();
}

It runs the given command line program, waits for it to finish and returns the output as string.

show more/Less text with just HTML and JavaScript

 <script type="text/javascript">
     function showml(divId,inhtmText) 
     {  
        var x = document.getElementById(divId).style.display; 

        if(x=="block")
        {
          document.getElementById(divId).style.display = "none";
          document.getElementById(inhtmText).innerHTML="Show More...";
        }
       if(x=="none")
       {
          document.getElementById(divId).style.display = "block";
          document.getElementById(inhtmText).innerHTML="Show Less";
        }
     }
</script>

 <p id="show_more1" onclick="showml('content1','show_more1')" onmouseover="this.style.cursor='pointer'">Show More...</p>

 <div id="content1" style="display: none; padding: 16px 20px 4px; margin-bottom: 15px; background-color: rgb(239, 239, 239);">
 </div>

if more div use like this change only 1 to 2

<p id="show_more2" onclick="showml('content2','show_more2')" onmouseover="this.style.cursor='pointer'">Show More...</p>

 <div id="content2" style="display: none; padding: 16px 20px 4px; margin-bottom: 15px; background-color: rgb(239, 239, 239);">
 </div>

demo jsfiddle

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

in SQL*Plus you could also use a REFCURSOR variable:

SQL> VARIABLE x REFCURSOR
SQL> DECLARE
  2   V_Sqlstatement Varchar2(2000);
  3  BEGIN
  4   V_Sqlstatement := 'SELECT * FROM DUAL';
  5   OPEN :x for v_Sqlstatement;
  6  End;
  7  /

ProcÚdure PL/SQL terminÚe avec succÞs.

SQL> print x;

D
-
X

Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape

There's a far more simpler solution to tackle this.

The reason why you get ValueError: Index contains duplicate entries, cannot reshape is because, once you unstack "Location", then the remaining index columns "id" and "date" combinations are no longer unique.

You can avoid this by retaining the default index column (row #) and while setting the index using "id", "date" and "location", add it in "append" mode instead of the default overwrite mode.

So use,

e.set_index(['id', 'date', 'location'], append=True)

Once this is done, your index columns will still have the default index along with the set indexes. And unstack will work.

Let me know how it works out.

jQuery - Get Width of Element when Not Visible (Display: None)

function realWidth(obj){
    var clone = obj.clone();
    clone.css("visibility","hidden");
    $('body').append(clone);
    var width = clone.outerWidth();
    clone.remove();
    return width;
}
realWidth($("#parent").find("table:first"));

How to save all files from source code of a web site?

In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as

save page as  
filename     : any_name.html 
save as type : webpage complete.

Then you will get any_name.html and any_name folder.

How to check if a file exists from inside a batch file

if exist <insert file name here> (
    rem file exists
) else (
    rem file doesn't exist
)

Or on a single line (if only a single action needs to occur):

if exist <insert file name here> <action>

for example, this opens notepad on autoexec.bat, if the file exists:

if exist c:\autoexec.bat notepad c:\autoexec.bat

WAMP Server ERROR "Forbidden You don't have permission to access /phpmyadmin/ on this server."

Change httpd.conf file as follows:

from

<Directory />
    AllowOverride none
    Require all denied
</Directory>

to

<Directory />
    AllowOverride none
    Require all granted
</Directory>

URL encode sees “&” (ampersand) as “&amp;” HTML entity

There is HTML and URI encodings. &amp; is & encoded in HTML while %26 is & in URI encoding.

So before URI encoding your string you might want to HTML decode and then URI encode it :)

var div = document.createElement('div');
div.innerHTML = '&amp;AndOtherHTMLEncodedStuff';
var htmlDecoded = div.firstChild.nodeValue;
var urlEncoded = encodeURIComponent(htmlDecoded);

result %26AndOtherHTMLEncodedStuff

Hope this saves you some time

Given an array of numbers, return array of products of all other numbers (no division)

Translating Michael Anderson's solution into Haskell:

otherProducts xs = zipWith (*) below above

     where below = scanl (*) 1 $ init xs

           above = tail $ scanr (*) 1 xs

how to kill the tty in unix

In addition to AIXroot's answer, there is also a logout function that can be used to write a utmp logout record. So if you don't have any processes for user xxxx, but userdel says "userdel: account xxxx is currently in use", you can add a logout record manually. Create a file logout.c like this:

#include <stdio.h>
#include <utmp.h>

int main(int argc, char *argv[])
{
  if (argc == 2) {
    return logout(argv[1]);
  }
  else {
    fprintf(stderr, "Usage: logout device\n");
    return 1;
  }
}

Compile it:

gcc -lutil -o logout logout.c

And then run it for whatever it says in the output of finger's "On since" line(s) as a parameter:

# finger xxxx
Login: xxxx                             Name:
Directory: /home/xxxx                   Shell: /bin/bash
On since Sun Feb 26 11:06 (GMT) on 127.0.0.1:6 (messages off) from 127.0.0.1
On since Fri Feb 24 16:53 (GMT) on pts/6, idle 3 days 17:16, from 127.0.0.1
Last login Mon Feb 10 14:45 (GMT) on pts/11 from somehost.example.com
Mail last read Sun Feb 27 08:44 2014 (GMT)
No Plan.

# userdel xxxx
userdel: account `xxxx' is currently in use.
# ./logout 127.0.0.1:6
# ./logout pts/6
# userdel xxxx
no crontab for xxxx

How to retrieve a user environment variable in CMake (Windows)

You need to have your variables exported. So for example in Linux:

export EnvironmentVariableName=foo

Unexported variables are empty in CMAKE.

Javascript to export html table to Excel

For UTF 8 Conversion and Currency Symbol Export Use this:

var tableToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,'
    , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><?xml version="1.0" encoding="UTF-8" standalone="yes"?><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
    , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
    , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
  return function(table, name) {
      if (!table.nodeType) table = document.getElementById(table)
      var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
    window.location.href = uri + base64(format(template, ctx))
  }
})()

How to set an button align-right with Bootstrap?

function Continue({show, onContinue}) {
  return(<div className="row continue">
  { show ? <div className="col-11">
    <button class="btn btn-primary btn-lg float-right" onClick= {onContinue}>Continue</button>
    </div>
    : null }
  </div>);
}

How do I specify the platform for MSBuild?

In MSBuild or Teamcity use command line

MSBuild yourproject.sln /property:Configuration=Release /property:Platform=x64

or use shorter form:

MSBuild yourproject.sln /p:Configuration=Release /p:Platform=x64

However you need to set up platform in your project anyway, see the answer by Julien Hoarau.

Make JQuery UI Dialog automatically grow or shrink to fit its contents

I used the following property which works fine for me:

$('#selector').dialog({
     minHeight: 'auto'
});

Parsing ISO 8601 date in Javascript

According to MSDN, the JavaScript Date object does not provide any specific date formatting methods (as you may see with other programming languages). However, you can use a few of the Date methods and formatting to accomplish your goal:

function dateToString (date) {
  // Use an array to format the month numbers
  var months = [
    "January",
    "February",
    "March",
    ...
  ];

  // Use an object to format the timezone identifiers
  var timeZones = {
    "360": "EST",
    ...
  };

  var month = months[date.getMonth()];
  var day = date.getDate();
  var year = date.getFullYear();

  var hours = date.getHours();
  var minutes = date.getMinutes();
  var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
  var timezone = timeZones[date.getTimezoneOffset()];

  // Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
  return month + " " + day + ", " + year + " - " + time + " " + timezone;
}

var date = new Date("2011-01-28T19:30:00-05:00");

alert(dateToString(date));

You could even take it one step further and override the Date.toString() method:

function dateToString () { // No date argument this time
  // Use an array to format the month numbers
  var months = [
    "January",
    "February",
    "March",
    ...
  ];

  // Use an object to format the timezone identifiers
  var timeZones = {
    "360": "EST",
    ...
  };

  var month = months[*this*.getMonth()];
  var day = *this*.getDate();
  var year = *this*.getFullYear();

  var hours = *this*.getHours();
  var minutes = *this*.getMinutes();
  var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
  var timezone = timeZones[*this*.getTimezoneOffset()];

  // Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
  return month + " " + day + ", " + year + " - " + time + " " + timezone;
}

var date = new Date("2011-01-28T19:30:00-05:00");
Date.prototype.toString = dateToString;

alert(date.toString());

Correct redirect URI for Google API and OAuth 2.0

There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.

You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.

When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.

How do I set a fixed background image for a PHP file?

It's not a good coding to put PHP code into CSS

body
{
    background-image:url('bg.png');
}

that's it

How to determine if a String has non-alphanumeric characters?

If you can use the Apache Commons library, then Commons-Lang StringUtils has a method called isAlphanumeric() that does what you're looking for.

How do you do natural logs (e.g. "ln()") with numpy in Python?

from numpy.lib.scimath import logn
from math import e

#using: x - var
logn(e, x)

Rotating a two-dimensional array in Python

Just an observation. The input is a list of lists, but the output from the very nice solution: rotated = zip(*original[::-1]) returns a list of tuples.

This may or may not be an issue.

It is, however, easily corrected:

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


def rotated(array_2d):
    list_of_tuples = zip(*array_2d[::-1])
    return [list(elem) for elem in list_of_tuples]
    # return map(list, list_of_tuples)

print(list(rotated(original)))

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

The list comp or the map will both convert the interior tuples back to lists.

Giving my function access to outside variable

$myArr = array();

function someFuntion(array $myArr) {
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;

    return $myArr;
}

$myArr = someFunction($myArr);

Test if remote TCP port is open from a shell script

I needed short script which was run in cron and hasn't output. I solve my trouble using nmap

open=`nmap -p $PORT $SERVER | grep "$PORT" | grep open`
if [ -z "$open" ]; then
  echo "Connection to $SERVER on port $PORT failed"
  exit 1
else
  echo "Connection to $SERVER on port $PORT succeeded"
  exit 0
fi

To run it You should install nmap because it is not default installed package.

How do I change Android Studio editor's background color?

You can change it by going File => Settings (Shortcut CTRL+ ALT+ S) , from Left panel Choose Appearance , Now from Right Panel choose theme.

enter image description here

Android Studio 2.1

Preference -> Search for Appearance -> UI options , Click on DropDown Theme

enter image description here

Android 2.2

Android studio -> File -> Settings -> Appearance & Behavior -> Look for UI Options

EDIT :

Import External Themes

You can download custom theme from this website. Choose your theme, download it. To set theme Go to Android studio -> File -> Import Settings -> Choose the .jar file downloaded.

CSS3 gradient background set on body doesn't stretch but instead repeats?

Regarding a previous answer, setting html and body to height: 100% doesn't seem to work if the content needs to scroll. Adding fixed to the background seems to fix that - no need for height: 100%;

E.g.:

_x000D_
_x000D_
body {_x000D_
  background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#cbccc8)) fixed;_x000D_
}
_x000D_
_x000D_
_x000D_

Are these methods thread safe?

It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.

Wheel file installation

you can follow the below command to install using the wheel file at your local

pip install /users/arpansaini/Downloads/h5py-3.0.0-cp39-cp39-macosx_10_9_x86_64.whl

Android Studio: “Execution failed for task ':app:mergeDebugResources'” if project is created on drive C:

I have a similar problem with Error:Execution failed for task ':app:mergeDebugResources. And at last I found the reason is the pictures resource error which use the incorrect ".9.png".

HTML favicon won't show on google chrome

Note if you have so many tabs open that Google Chrome is only showing the favicons then Google Chrome won't show the favicon for the selected tab, so if you keep reloading the tab with your page loaded in order to see your new favicon you will only see the text of your page's title.

You will need to reload your page, and then select a different tab in order to see your favicon.

enter image description here

how to convert a string date to date format in oracle10g

You need to use the TO_DATE function.

SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM DUAL;

How to put a UserControl into Visual Studio toolBox

The issue with my designer was 32 vs 64 bit issue. I could add the control to tool box after following the instructions in Cannot add Controls from 64-bit Assemblies to the Toolbox or Use in Designers Within the Visual Studio IDE MS KB article.

jQuery .get error response function?

$.get does not give you the opportunity to set an error handler. You will need to use the low-level $.ajax function instead:

$.ajax({
    url: 'http://example.com/page/2/',
    type: 'GET',
    success: function(data){ 
        $(data).find('#reviews .card').appendTo('#reviews');
    },
    error: function(data) {
        alert('woops!'); //or whatever
    }
});

Edit March '10

Note that with the new jqXHR object in jQuery 1.5, you can set an error handler after calling $.get:

$.get('http://example.com/page/2/', function(data){ 
    $(data).find('#reviews .card').appendTo('#reviews');
}).fail(function() {
    alert('woops'); // or whatever
});

Using Python, how can I access a shared folder on windows network?

Use forward slashes to specify the UNC Path:

open('//HOST/share/path/to/file')

(if your Python client code is also running under Windows)

How to open a web page from my application?

Microsoft explains it in the KB305703 article on How to start the default Internet browser programmatically by using Visual C#.

Don't forget to check the Troubleshooting section.

How to assign bean's property an Enum value in Spring config file?

Use the value child element instead of the value attribute and specify the Enum class name:

<property name="residence">
    <value type="SocialSecurity$Residence">ALIEN</value>
</property>

The advantage of this approach over just writing value="ALIEN" is that it also works if Spring can't infer the actual type of the enum from the property (e.g. the property's declared type is an interface).Adapted from araqnid's comment.

How to format numbers?

If you want to use built-in code, you can use toLocaleString() with minimumFractionDigits. Browser compatibility for the extended options on toLocaleString() was limited when I first wrote this answer, but the current status looks good.

_x000D_
_x000D_
var n = 100000;
var value = n.toLocaleString(
  undefined, // leave undefined to use the browser's locale,
             // or use a string like 'en-US' to override it.
  { minimumFractionDigits: 2 }
);
console.log(value);
// In en-US, logs '100,000.00'
// In de-DE, logs '100.000,00'
// In hi-IN, logs '1,00,000.00'
_x000D_
_x000D_
_x000D_

If you're using Node.js, you will need to npm install the intl package.

Can't include C++ headers like vector in Android NDK

I'm using Android Studio and as of 19th of January 2016 this did the trick for me. (This seems like something that changes every year or so)

Go to: app -> Gradle Scripts -> build.gradle (Module: app)

Then under model { ... android.ndk { ... and add a line: stl = "gnustl_shared"

Like this:

model {

    ...

    android.ndk {
        moduleName = "gl2jni"
        cppFlags.add("-Werror")
        ldLibs.addAll(["log", "GLESv2"])
        stl = "gnustl_shared"     //  <-- this is the line that I added
    }

    ...

}

Java equivalent of unsigned long long?

Nope, there is not. You'll have to use the primitive long data type and deal with signedness issues, or use a class such as BigInteger.

Sound alarm when code finishes

import subprocess

subprocess.call(['D:\greensoft\TTPlayer\TTPlayer.exe', "E:\stridevampaclip.mp3"])

Android Lint contentDescription warning

If you want to suppress this warning in elegant way (because you are sure that accessibility is not needed for this particular ImageView), you can use special attribute:

android:importantForAccessibility="no"

How do I retrieve the number of columns in a Pandas data frame?

#use a regular expression to parse the column count
#https://docs.python.org/3/library/re.html

buffer = io.StringIO()
df.info(buf=buffer)
s = buffer.getvalue()
pat=re.search(r"total\s{1}[0-9]\s{1}column",s)
print(s)
phrase=pat.group(0)
value=re.findall(r'[0-9]+',phrase)[0]
print(int(value))

GDB: break if variable equal value

You can use a watchpoint for this (A breakpoint on data instead of code).

You can start by using watch i.
Then set a condition for it using condition <breakpoint num> i == 5

You can get the breakpoint number by using info watch

How to increase code font size in IntelliJ?

First press Ctrl+Shift+A

then search increase font enter image description here

For Mac Users, It's cmd + shift + A

Oracle PL/SQL - How to create a simple array variable?

You can use VARRAY for a fixed-size array:

declare
   type array_t is varray(3) of varchar2(10);
   array array_t := array_t('Matt', 'Joanne', 'Robert');
begin
   for i in 1..array.count loop
       dbms_output.put_line(array(i));
   end loop;
end;

Or TABLE for an unbounded array:

...
   type array_t is table of varchar2(10);
...

The word "table" here has nothing to do with database tables, confusingly. Both methods create in-memory arrays.

With either of these you need to both initialise and extend the collection before adding elements:

declare
   type array_t is varray(3) of varchar2(10);
   array array_t := array_t(); -- Initialise it
begin
   for i in 1..3 loop
      array.extend(); -- Extend it
      array(i) := 'x';
   end loop;
end;

The first index is 1 not 0.

Java array assignment (multiple values)

If you know the values at compile time you can do :

float[] values = {0.1f, 0.2f, 0.3f};

There is no way to do that if values are variables in runtime.

How can I align YouTube embedded video in the center in bootstrap

I set the max width for my video to be 100%. On phones the video automatically fits the width of the screen. Since the embedded video is only 560px wide, I just added a 10% left-margin to the iframe, and put a "0" back in for the margin for the mobile CSS (to allow the full width view). I did't want to bother putting a div around every video...

Desktop CSS:

_x000D_
_x000D_
iframe {_x000D_
  margin-left: 10%;_x000D_
 }
_x000D_
_x000D_
_x000D_

Mobile CSS:

_x000D_
_x000D_
iframe {_x000D_
  margin-left: 0;_x000D_
 }
_x000D_
_x000D_
_x000D_

Worked perfect for my blog (Botanical Amy).

how to display data values on Chart.js

From chart.js samples (file Chart.js-2.4.0/samples/data_labelling.html) :

``` // Define a plugin to provide data labels

    Chart.plugins.register({
        afterDatasetsDraw: function(chartInstance, easing) {
            // To only draw at the end of animation, check for easing === 1
            var ctx = chartInstance.chart.ctx;

            chartInstance.data.datasets.forEach(function (dataset, i) {
                var meta = chartInstance.getDatasetMeta(i);
                if (!meta.hidden) {
                    meta.data.forEach(function(element, index) {
                        // Draw the text in black, with the specified font
                        ctx.fillStyle = 'rgb(0, 0, 0)';

                        var fontSize = 16;
                        var fontStyle = 'normal';
                        var fontFamily = 'Helvetica Neue';
                        ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily);

                        // Just naively convert to string for now
                        var dataString = dataset.data[index].toString();

                        // Make sure alignment settings are correct
                        ctx.textAlign = 'center';
                        ctx.textBaseline = 'middle';

                        var padding = 5;
                        var position = element.tooltipPosition();
                        ctx.fillText(dataString, position.x, position.y - (fontSize / 2) - padding);
                    });
                }
            });
        }
    });

```

With CSS, use "..." for overflowed block of multi-lines

Bit late to this party but I came up with, what I think, is a unique solution. Rather than trying to insert your own ellipsis through css trickery or js I thought i'd try and roll with the single line only restriction. So I duplicate the text for every "line" and just use a negative text-indent to make sure one line starts where the last one stops. FIDDLE

CSS:

#wrapper{
    font-size: 20pt;
    line-height: 22pt;
    width: 100%;
    overflow: hidden;
    padding: 0;
    margin: 0;
}

.text-block-line{
    height: 22pt;
    display: inline-block;
    max-width: 100%;
    overflow: hidden;
    white-space: nowrap;
    width: auto;
}
.text-block-line:last-child{
    text-overflow: ellipsis;
}

/*the follwing is suboptimal but neccesary I think. I'd probably just make a sass mixin that I can feed a max number of lines to and have them avialable. Number of lines will need to be controlled by server or client template which is no worse than doing a character count clip server side now. */
.line2{
    text-indent: -100%;
}
.line3{
    text-indent: -200%;
}
.line4{
    text-indent: -300%;
}

HTML:

<p id="wrapper" class="redraw">
    <span class="text-block-line line1">This text is repeated for every line that you want to be displayed in your element. This example has a max of 4 lines before the ellipsis occurs. Try scaling the preview window width to see the effect.</span>
    <span class="text-block-line line2">This text is repeated for every line that you want to be displayed in your element. This example has a max of 4 lines before the ellipsis occurs. Try scaling the preview window width to see the effect.</span>
    <span class="text-block-line line3">This text is repeated for every line that you want to be displayed in your element. This example has a max of 4 lines before the ellipsis occurs. Try scaling the preview window width to see the effect.</span>
    <span class="text-block-line line4">This text is repeated for every line that you want to be displayed in your element. This example has a max of 4 lines before the ellipsis occurs. Try scaling the preview window width to see the effect.</span>
</p>

More details in the fiddle. There is an issue with the browser reflowing that I use a JS redraw for and such so do check it out but this is the basic concept. Any thoughts/suggestions are much appreciated.

Catching multiple exception types in one catch block

As of PHP 8.0 you can use even cleaner way to catch your exceptions when you don't need to output the content of the error (from variable $e). However you must replace default Exception with Throwable.

try {
    /* something */
} catch (AError | BError) {
    handler1()
} catch (Throwable) {
    handler2()
}

"No rule to make target 'install'"... But Makefile exists

I also came across the same error. Here is the fix: If you are using Cmake-GUI:

  1. Clean the cache of the loaded libraries in Cmake-GUI File menu.
  2. Configure the libraries.
  3. Generate the Unix file.

If you missed the 3rd step:

*** No rule to make target `install'. Stop.

error will occur.

Pass correct "this" context to setTimeout callback?

In browsers other than Internet Explorer, you can pass parameters to the function together after the delay:

var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);

So, you can do this:

var timeoutID = window.setTimeout(function (self) {
  console.log(self); 
}, 500, this);

This is better in terms of performance than a scope lookup (caching this into a variable outside of the timeout / interval expression), and then creating a closure (by using $.proxy or Function.prototype.bind).

The code to make it work in IEs from Webreflection:

/*@cc_on
(function (modifierFn) {
  // you have to invoke it as `window`'s property so, `window.setTimeout`
  window.setTimeout = modifierFn(window.setTimeout);
  window.setInterval = modifierFn(window.setInterval);
})(function (originalTimerFn) {
    return function (callback, timeout){
      var args = [].slice.call(arguments, 2);
      return originalTimerFn(function () { 
        callback.apply(this, args) 
      }, timeout);
    }
});
@*/

CSS fixed width in a span

Unfortunately inline elements (or elements having display:inline) ignore the width property. You should use floating divs instead:

<style type="text/css">
div.f1 { float: left; width: 20px; }
div.f2 { float: left; }
div.f3 { clear: both; }
</style>

<div class="f1"></div><div class="f2">The Lazy dog</div><div class="f3"></div>
<div class="f1">AND</div><div class="f2">The Lazy cat</div><div class="f3"></div>
<div class="f1">OR</div><div class="f2">The active goldfish</div><div class="f3"></div>

Now I see you need to use spans and lists, so we need to rewrite this a little bit:

<html><head>
<style type="text/css">
        span.f1 { display: block; float: left; clear: left; width: 60px; }
    li { list-style-type: none; }
    </style>

</head><body>
<ul>
<li><span class="f1">&nbsp;</span>The lazy dog.</li>
<li><span class="f1">AND</span> The lazy cat.</li>
<li><span class="f1">OR</span> The active goldfish.</li>
</ul>
</body>
</html>

What is the difference between an IntentService and a Service?

In short, a Service is a broader implementation for the developer to set up background operations, while an IntentService is useful for "fire and forget" operations, taking care of background Thread creation and cleanup.

From the docs:

Service A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.

IntentService Service is a base class for IntentService Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

Refer this doc - http://developer.android.com/reference/android/app/IntentService.html

php mail setup in xampp

My favorite smtp server is hMailServer.

It has a nice windows friendly installer and wizard. Hands down the easiest mail server I've ever setup.

It can proxy through your gmail/yahoo/etc account or send email directly.

Once it is installed, email in xampp just works with no config changes.

SQL command to display history of queries

For MySQL > 5.1.11 or MariaDB

  1. SET GLOBAL log_output = 'TABLE';
  2. SET GLOBAL general_log = 'ON';
  3. Take a look at the table mysql.general_log

If you want to output to a log file:

  1. SET GLOBAL log_output = "FILE";
  2. SET GLOBAL general_log_file = "/path/to/your/logfile.log"
  3. SET GLOBAL general_log = 'ON';

As mentioned by jeffmjack in comments, these settings will be forgetting before next session unless you edit the configuration files (e.g. edit /etc/mysql/my.cnf, then restart to apply changes).

Now, if you'd like you can tail -f /var/log/mysql/mysql.log

More info here: Server System Variables

How do I print my Java object without getting "SomeType@2f92e0f4"?

In intellij you can auto generate toString method by pressing alt+inset and then selecting toString() here is an out put for a test class:

public class test  {
int a;
char b;
String c;
Test2 test2;

@Override
public String toString() {
    return "test{" +
            "a=" + a +
            ", b=" + b +
            ", c='" + c + '\'' +
            ", test2=" + test2 +
            '}';
 }
}

As you can see, it generates a String by concatenating, several attributes of the class, for primitives it will print their values and for reference types it will use their class type (in this case to string method of Test2).

Difference between /res and /assets directories

I know this is old, but just to make it clear, there is an explanation of each in the official android documentation:

from http://developer.android.com/tools/projects/index.html

assets/

This is empty. You can use it to store raw asset files. Files that you save here are compiled into an .apk file as-is, and the original filename is preserved. You can navigate this directory in the same way as a typical file system using URIs and read files as a stream of bytes using the AssetManager. For example, this is a good location for textures and game data.

res/raw/

For arbitrary raw asset files. Saving asset files here instead of in the assets/ directory only differs in the way that you access them. These files are processed by aapt and must be referenced from the application using a resource identifier in the R class. For example, this is a good place for media, such as MP3 or Ogg files.

Decrypt password created with htpasswd

.htpasswd entries are HASHES. They are not encrypted passwords. Hashes are designed not to be decryptable. Hence there is no way (unless you bruteforce for a loooong time) to get the password from the .htpasswd file.

What you need to do is apply the same hash algorithm to the password provided to you and compare it to the hash in the .htpasswd file. If the user and hash are the same then you're a go.

Chrome disable SSL checking for sites?

In my case I was developing an ASP.Net MVC5 web app and the certificate errors on my local dev machine (IISExpress certificate) started becoming a practical concern once I started working with service workers. Chrome simply wouldn't register my service worker because of the certificate error.

I did, however, notice that during my automated Selenium browser tests, Chrome seem to just "ignore" all these kinds of problems (e.g. the warning page about an insecure site), so I asked myself the question: How is Selenium starting Chrome for running its tests, and might it also solve the service worker problem?

Using Process Explorer on Windows, I was able to find out the command-line arguments with which Selenium is starting Chrome:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-background-networking --disable-client-side-phishing-detection --disable-default-apps --disable-hang-monitor --disable-popup-blocking --disable-prompt-on-repost --disable-sync --disable-web-resources --enable-automation --enable-logging --force-fieldtrials=SiteIsolationExtensions/Control --ignore-certificate-errors --log-level=0 --metrics-recording-only --no-first-run --password-store=basic --remote-debugging-port=12207 --safebrowsing-disable-auto-update --test-type=webdriver --use-mock-keychain --user-data-dir="C:\Users\Sam\AppData\Local\Temp\some-non-existent-directory" data:,

There are a bunch of parameters here that I didn't end up doing necessity-testing for, but if I run Chrome this way, my service worker registers and works as expected.

The only one that does seem to make a difference is the --user-data-dir parameter, which to make things work can be set to a non-existent directory (things won't work if you don't provide the parameter).

Hope that helps someone else with a similar problem. I'm using Chrome 60.0.3112.90.

Can I change the fill color of an svg path with CSS?

if you want to change color by hovering in the element, try this:

path:hover{
  fill:red;
}

Python spacing and aligning strings

Resurrecting another topic, but this may come in handy for some.

With a little bit of inspiration from https://pyformat.info you can build a method to get a Table of Content [TOC] style printout.

# Define parameters
Location = '10-10-10-10'
Revision = 1
District = 'Tower'
MyDate = 'May 16, 2012'
MyUser = 'LOD'
MyTime = '10:15'

# This is just one way to arrange the data
data = [
    ['Location: '+Location, 'Revision:'+str(Revision)],
    ['District: '+District, 'Date: '+MyDate],
    ['User: '+MyUser,'Time: '+MyTime]
]

# The 'Table of Content' [TOC] style print function
def print_table_line(key,val,space_char,val_loc):
    # key:        This would be the TOC item equivalent
    # val:        This would be the TOC page number equivalent
    # space_char: This is the spacing character between key and val (often a dot for a TOC), must be >= 5
    # val_loc:    This is the location in the string where the first character of val would be located

    val_loc = max(5,val_loc)

    if (val_loc <= len(key)):
        # if val_loc is within the space of key, truncate key and
        cut_str =  '{:.'+str(val_loc-4)+'}'
        key = cut_str.format(key)+'...'+space_char

    space_str = '{:'+space_char+'>'+str(val_loc-len(key)+len(str(val)))+'}'
    print(key+space_str.format(str(val)))

# Examples
for d in data:
    print_table_line(d[0],d[1],' ',30)

print('\n')
for d in data:
    print_table_line(d[0],d[1],'_',25)

print('\n')
for d in data:
    print_table_line(d[0],d[1],' ',20)

The resulting output is as follows:

Location: 10-10-10-10         Revision:1
District: Tower               Date: May 16, 2012
User: LOD                     Time: 10:15


Location: 10-10-10-10____Revision:1
District: Tower__________Date: May 16, 2012
User: LOD________________Time: 10:15


Location: 10-10-... Revision:1
District: Tower     Date: May 16, 2012
User: LOD           Time: 10:15

Groovy write to file (newline)

Might be cleaner to use PrintWriter and its method println.
Just make sure you close the writer when you're done

How to get the response of XMLHttpRequest?

You can get it by XMLHttpRequest.responseText in XMLHttpRequest.onreadystatechange when XMLHttpRequest.readyState equals to XMLHttpRequest.DONE.

Here's an example (not compatible with IE6/7).

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);

For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.

$.get('http://example.com', function(responseText) {
    alert(responseText);
});

Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.

Smooth scroll without the use of jQuery

<script>
var set = 0;

function animatescroll(x, y) {
    if (set == 0) {
        var val72 = 0;
        var val73 = 0;
        var setin = 0;
        set = 1;

        var interval = setInterval(function() {
            if (setin == 0) {
                val72++;
                val73 += x / 1000;
                if (val72 == 1000) {
                    val73 = 0;
                    interval = clearInterval(interval);
                }
                document.getElementById(y).scrollTop = val73;
            }
        }, 1);
    }
}
</script>

x = scrollTop
y = id of the div that is used to scroll

Note: For making the body to scroll give the body an ID.

How to use 'cp' command to exclude a specific directory?

It's relative to the source directory.
This will exclude the directory source/.git from being copied.

rsync -r --exclude '.git' source target

Python: TypeError: object of type 'NoneType' has no len()

You don't need to assign names to list or [] or anything else until you wish to use it.

It's neater to use a list comprehension to make the list of names.

shuffle modifies the list you pass to it. It always returns None

If you are using a context manager (with ...) you don't need to close the file explicitly

from random import shuffle

with open('names') as f:
    names = [name.rstrip() for name in f if not name.isspace()]
    shuffle(names)

assert len(names) > 100

Which characters make a URL invalid?

All valid characters that can be used in a URI (a URL is a type of URI) are defined in RFC 3986.

All other characters can be used in a URL provided that they are "URL Encoded" first. This involves changing the invalid character for specific "codes" (usually in the form of the percent symbol (%) followed by a hexadecimal number).

This link, HTML URL Encoding Reference, contains a list of the encodings for invalid characters.

Similarity String Comparison in Java

Thank to the first answerer, I think there are 2 calculations of computeEditDistance(s1, s2). Due to high time spending of it, decided to improve the code's performance. So:

public class LevenshteinDistance {

public static int computeEditDistance(String s1, String s2) {
    s1 = s1.toLowerCase();
    s2 = s2.toLowerCase();

    int[] costs = new int[s2.length() + 1];
    for (int i = 0; i <= s1.length(); i++) {
        int lastValue = i;
        for (int j = 0; j <= s2.length(); j++) {
            if (i == 0) {
                costs[j] = j;
            } else {
                if (j > 0) {
                    int newValue = costs[j - 1];
                    if (s1.charAt(i - 1) != s2.charAt(j - 1)) {
                        newValue = Math.min(Math.min(newValue, lastValue),
                                costs[j]) + 1;
                    }
                    costs[j - 1] = lastValue;
                    lastValue = newValue;
                }
            }
        }
        if (i > 0) {
            costs[s2.length()] = lastValue;
        }
    }
    return costs[s2.length()];
}

public static void printDistance(String s1, String s2) {
    double similarityOfStrings = 0.0;
    int editDistance = 0;
    if (s1.length() < s2.length()) { // s1 should always be bigger
        String swap = s1;
        s1 = s2;
        s2 = swap;
    }
    int bigLen = s1.length();
    editDistance = computeEditDistance(s1, s2);
    if (bigLen == 0) {
        similarityOfStrings = 1.0; /* both strings are zero length */
    } else {
        similarityOfStrings = (bigLen - editDistance) / (double) bigLen;
    }
    //////////////////////////
    //System.out.println(s1 + "-->" + s2 + ": " +
      //      editDistance + " (" + similarityOfStrings + ")");
    System.out.println(editDistance + " (" + similarityOfStrings + ")");
}

public static void main(String[] args) {
    printDistance("", "");
    printDistance("1234567890", "1");
    printDistance("1234567890", "12");
    printDistance("1234567890", "123");
    printDistance("1234567890", "1234");
    printDistance("1234567890", "12345");
    printDistance("1234567890", "123456");
    printDistance("1234567890", "1234567");
    printDistance("1234567890", "12345678");
    printDistance("1234567890", "123456789");
    printDistance("1234567890", "1234567890");
    printDistance("1234567890", "1234567980");

    printDistance("47/2010", "472010");
    printDistance("47/2010", "472011");

    printDistance("47/2010", "AB.CDEF");
    printDistance("47/2010", "4B.CDEFG");
    printDistance("47/2010", "AB.CDEFG");

    printDistance("The quick fox jumped", "The fox jumped");
    printDistance("The quick fox jumped", "The fox");
    printDistance("The quick fox jumped",
            "The quick fox jumped off the balcany");
    printDistance("kitten", "sitting");
    printDistance("rosettacode", "raisethysword");
    printDistance(new StringBuilder("rosettacode").reverse().toString(),
            new StringBuilder("raisethysword").reverse().toString());
    for (int i = 1; i < args.length; i += 2) {
        printDistance(args[i - 1], args[i]);
    }


 }
}

How to delete a cookie using jQuery?

You can try this:

$.removeCookie('the_cookie', { path: '/' });

source: https://github.com/carhartl/jquery-cookie#readme

Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

I am assuming Basic authentication here.

$cred = Get-Credential
Invoke-WebRequest -Uri 'https://whatever' -Credential $cred

You can get your credential through other means (Import-Clixml, etc.), but it does have to be a [PSCredential] object.

Edit based on comments:

GitHub is breaking RFC as they explain in the link you provided:

The API supports Basic Authentication as defined in RFC2617 with a few slight differences. The main difference is that the RFC requires unauthenticated requests to be answered with 401 Unauthorized responses. In many places, this would disclose the existence of user data. Instead, the GitHub API responds with 404 Not Found. This may cause problems for HTTP libraries that assume a 401 Unauthorized response. The solution is to manually craft the Authorization header.

Powershell's Invoke-WebRequest does to my knowledge wait for a 401 response before sending the credentials, and since GitHub never provides one, your credentials will never be sent.

Manually build the headers

Instead you'll have to create the basic auth headers yourself.

Basic authentication takes a string that consists of the username and password separated by a colon user:pass and then sends the Base64 encoded result of that.

Code like this should work:

$user = 'user'
$pass = 'pass'

$pair = "$($user):$($pass)"

$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))

$basicAuthValue = "Basic $encodedCreds"

$Headers = @{
    Authorization = $basicAuthValue
}

Invoke-WebRequest -Uri 'https://whatever' -Headers $Headers

You could combine some of the string concatenation but I wanted to break it out to make it clearer.

Java System.out.print formatting

Just use \t to space it.

Example:

System.out.println(monthlyInterest + "\t")

//as far as the two 0 in front of it just use a if else statement. ex: 
x = x+1;
if (x < 10){
    System.out.println("00" +x);
}
else if( x < 100){
    System.out.println("0" +x);
}
else{
    System.out.println(x);
}

There are other ways to do it, but this is the simplest.

PHP not displaying errors even though display_errors = On

Though this thread is old but still, I feel I should post a good answer from this stackoverflow answer.

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

This sure saved me after hours of trying to get things to work. I hope this helps someone.

How to print to the console in Android Studio?

You can see the println() statements in the Run window of Android Studio.

See detailed answer with screenshot here.

Assembly - JG/JNLE/JL/JNGE after CMP

The command JG simply means: Jump if Greater. The result of the preceding instructions is stored in certain processor flags (in this it would test if ZF=0 and SF=OF) and jump instruction act according to their state.

Sorting objects by property values

Here's a short example, that creates and array of objects, and sorts numerically or alphabetically:

// Create Objects Array

var arrayCarObjects = [
{brand: "Honda",        topSpeed: 45},
{brand: "Ford",         topSpeed: 6},
{brand: "Toyota",       topSpeed: 240},
{brand: "Chevrolet",    topSpeed: 120},
{brand: "Ferrari",      topSpeed: 1000}
];

// Sort Objects Numerically

arrayCarObjects.sort((a, b) => (a.topSpeed - b.topSpeed));

// Sort Objects Alphabetically

arrayCarObjects.sort((a, b) => (a.brand > b.brand) ? 1 : -1);

Excluding Maven dependencies

Global exclusions look like they're being worked on, but until then...

From the Sonatype maven reference (bottom of the page):

Dependency management in a top-level POM is different from just defining a dependency on a widely shared parent POM. For starters, all dependencies are inherited. If mysql-connector-java were listed as a dependency of the top-level parent project, every single project in the hierarchy would have a reference to this dependency. Instead of adding in unnecessary dependencies, using dependencyManagement allows you to consolidate and centralize the management of dependency versions without adding dependencies which are inherited by all children. In other words, the dependencyManagement element is equivalent to an environment variable which allows you to declare a dependency anywhere below a project without specifying a version number.

As an example:

  <dependencies>
    <dependency>
      <groupId>commons-httpclient</groupId>
      <artifactId>commons-httpclient</artifactId>
      <version>3.1</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>3.0.5.RELEASE</version>
    </dependency>
  </dependencies>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <exclusions>
          <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
          </exclusion>
        </exclusions>
      </dependency>
      <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <exclusions>
          <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
          </exclusion>
        </exclusions>
      </dependency>
    </dependencies>
  </dependencyManagement>

It doesn't make the code less verbose overall, but it does make it less verbose where it counts. If you still want it less verbose you can follow these tips also from the Sonatype reference.

Looping over arrays, printing both index and value

you can always use iteration param:

ITER=0
for I in ${FOO[@]}
do  
    echo ${I} ${ITER}
    ITER=$(expr $ITER + 1)
done

Application not picking up .css file (flask/python)

Still having problems after following the solution provided by codegeek:
<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='styles/mainpage.css') }}"> ?

In Google Chrome pressing the reload button (F5) will not reload the static files. If you have followed the accepted solution but still don't see the changes you have made to CSS, then press ctrl + shift + R to ignore cached files and reload the static files.

In Firefox pressing the reload button appears to reload the static files.

In Edge pressing the refresh button does not reload the static file. Pressing ctrl + shift + R is supposed to ignore cached files and reload the static files. However this does not work on my computer.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

Many time this error is caused when you update a product in your custom module's observer as shown below.

class [NAMESPACE]_[MODULE NAME]_Model_Observer
{
    /**
     * Flag to stop observer executing more than once
     *
     * @var static bool
     */
    static protected $_singletonFlag = false;

    public function saveProductData(Varien_Event_Observer $observer)
    {
        if (!self::$_singletonFlag) {
            self::$_singletonFlag = true;

            $product = $observer->getEvent()->getProduct();
             //do stuff to the $product object
            // $product->save();  // commenting out this line prevents the error
            $product->getResource()->save($product);
    }
} 

Hence whenever you save your product after updating some properties in your module's observer use $product->getResource()->save($product) instead of $product->save()

CSS selector for a checked radio button's label

You could use a bit of jQuery:

$('input:radio').click(function(){
    $('label#' + $(this).attr('id')).toggleClass('checkedClass'); // checkedClass is defined in your CSS
});

You'd need to make sure your checked radio buttons have the correct class on page load as well.

Is it possible to insert HTML content in XML document?

You can include HTML content. One possibility is encoding it in BASE64 as you have mentioned.

Another might be using CDATA tags.

Example using CDATA:

<xml>
    <title>Your HTML title</title>
    <htmlData><![CDATA[<html>
        <head>
            <script/>
        </head>
        <body>
        Your HTML's body
        </body>
        </html>
     ]]>
    </htmlData>
</xml>

Please note:

CDATA's opening character sequence: <![CDATA[

CDATA's closing character sequence: ]]>

MongoDB what are the default user and password?

In addition with what @Camilo Silva already mentioned, if you want to give free access to create databases, read, write databases, etc, but you don't want to create a root role, you can change the 3rd step with the following:

use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: "abc123",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, 
             { role: "dbAdminAnyDatabase", db: "admin" }, 
             { role: "readWriteAnyDatabase", db: "admin" } ]
  }
)

Error: expected type-specifier before 'ClassName'

For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).

This can be caused in many ways:

  • You forgot to #include the header that defines it.
  • Your inclusion guards (#ifndef BLAH_H) are defective (your #ifndef BLAH_H doesn't match your #define BALH_H due to a typo or copy+paste mistake).
  • Your inclusion guards are accidentally used twice (two separate files both using #define MYHEADER_H, even if they are in separate directories)
  • You forgot that you are using a template (eg. new Vector() should be new Vector<int>())
  • The compiler is thinking you meant one scope when really you meant another (For example, if you have NamespaceA::NamespaceB, AND a <global scope>::NamespaceB, if you are already within NamespaceA, it'll look in NamespaceA::NamespaceB and not bother checking <global scope>::NamespaceB) unless you explicitly access it.
  • You have a name clash (two entities with the same name, such as a class and an enum member).

To explicitly access something in the global namespace, prefix it with ::, as if the global namespace is a namespace with no name (e.g. ::MyType or ::MyNamespace::MyType).

Accessing dict keys like an attribute?

I found myself wondering what the current state of "dict keys as attr" in the python ecosystem. As several commenters have pointed out, this is probably not something you want to roll your own from scratch, as there are several pitfalls and footguns, some of them very subtle. Also, I would not recommend using Namespace as a base class, I've been down that road, it isn't pretty.

Fortunately, there are several open source packages providing this functionality, ready to pip install! Unfortunately, there are several packages. Here is a synopsis, as of Dec 2019.

Contenders (most recent commit to master|#commits|#contribs|coverage%):

  • addict (2019-04-28 | 217 | 22 | 100%)
  • munch (2019-12-16 | 160 | 17 | ?%)
  • easydict (2018-10-18 | 51 | 6 | ?%)
  • attrdict (2019-02-01 | 108 | 5 | 100%)
  • prodict (2019-10-01 | 65 | 1 | ?%)

No longer maintained or under-maintained:

  • treedict (2014-03-28 | 95 | 2 | ?%)
  • bunch (2012-03-12 | 20 | 2 | ?%)
  • NeoBunch

I currently recommend munch or addict. They have the most commits, contributors, and releases, suggesting a healthy open-source codebase for each. They have the cleanest-looking readme.md, 100% coverage, and good looking set of tests.

I do not have a dog in this race (for now!), besides having rolled my own dict/attr code and wasted a ton of time because I was not aware of all these options :). I may contribute to addict/munch in the future as I would rather see one solid package than a bunch of fragmented ones. If you like them, contribute! In particular, looks like munch could use a codecov badge and addict could use a python version badge.

addict pros:

  • recursive initialization (foo.a.b.c = 'bar'), dict-like arguments become addict.Dict

addict cons:

  • shadows typing.Dict if you from addict import Dict
  • No key checking. Due to allowing recursive init, if you misspell a key, you just create a new attribute, rather than KeyError (thanks AljoSt)

munch pros:

  • unique naming
  • built-in ser/de functions for JSON and YAML

munch cons:

  • no recursive init / only can init one attr at a time

Wherein I Editorialize

Many moons ago, when I used text editors to write python, on projects with only myself or one other dev, I liked the style of dict-attrs, the ability to insert keys by just declaring foo.bar.spam = eggs. Now I work on teams, and use an IDE for everything, and I have drifted away from these sorts of data structures and dynamic typing in general, in favor of static analysis, functional techniques and type hints. I've started experimenting with this technique, subclassing Pstruct with objects of my own design:

class  BasePstruct(dict):
    def __getattr__(self, name):
        if name in self.__slots__:
            return self[name]
        return self.__getattribute__(name)

    def __setattr__(self, key, value):
        if key in self.__slots__:
            self[key] = value
            return
        if key in type(self).__dict__:
            self[key] = value
            return
        raise AttributeError(
            "type object '{}' has no attribute '{}'".format(type(self).__name__, key))


class FooPstruct(BasePstruct):
    __slots__ = ['foo', 'bar']

This gives you an object which still behaves like a dict, but also lets you access keys like attributes, in a much more rigid fashion. The advantage here is I (or the hapless consumers of your code) know exactly what fields can and can't exist, and the IDE can autocomplete fields. Also subclassing vanilla dict means json serialization is easy. I think the next evolution in this idea would be a custom protobuf generator which emits these interfaces, and a nice knock-on is you get cross-language data structures and IPC via gRPC for nearly free.

If you do decide to go with attr-dicts, it's essential to document what fields are expected, for your own (and your teammates') sanity.

Feel free to edit/update this post to keep it recent!

How can I get a resource "Folder" from inside my jar File?

Below code gets .yaml files from a custom resource directory.

ClassLoader classLoader = this.getClass().getClassLoader();
            URI uri = classLoader.getResource(directoryPath).toURI();
    
            if("jar".equalsIgnoreCase(uri.getScheme())){
                Pattern pattern = Pattern.compile("^.+" +"/classes/" + directoryPath + "/.+.yaml$");
                log.debug("pattern {} ", pattern.pattern());
                ApplicationHome home = new ApplicationHome(SomeApplication.class);
                JarFile file = new JarFile(home.getSource());
                Enumeration<JarEntry>  jarEntries = file.entries() ;
                while(jarEntries.hasMoreElements()){
                    JarEntry entry = jarEntries.nextElement();
                    Matcher matcher = pattern.matcher(entry.getName());
                    if(matcher.find()){
                        InputStream in =
                                file.getInputStream(entry);
                        //work on the stream
    
    
                    }
                }
    
            }else{
                //When Spring boot application executed through Non-Jar strategy like through IDE or as a War.
    
                String path = uri.getPath();
                File[] files = new File(path).listFiles();
               
                for(File file: files){
                    if(file != null){
                        try {
                            InputStream is = new FileInputStream(file);
                           //work on stream
                            
                        } catch (Exception e) {
                            log.error("Exception while parsing file yaml file {} : {} " , file.getAbsolutePath(), e.getMessage());
                        }
                    }else{
                        log.warn("File Object is null while parsing yaml file");
                    }
                }
            }
             

event.preventDefault() function not working in IE

preventDefault is a widespread standard; using an adhoc every time you want to be compliant with old IE versions is cumbersome, better to use a polyfill:

if (typeof Event.prototype.preventDefault === 'undefined') {
    Event.prototype.preventDefault = function (e, callback) {
        this.returnValue = false;
    };
}

This will modify the prototype of the Event and add this function, a great feature of javascript/DOM in general. Now you can use e.preventDefault with no problem.

Getting selected value of a combobox

You have to cast the selected item to your custom class (ComboboxItem) Try this:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
            int selectedIndex = cmb.SelectedIndex;
            string selectedText = this.comboBox1.Text;
            string selectedValue = ((ComboboxItem)cmb.SelectedItem).Value.ToString();

ComboboxItem selectedCar = (ComboboxItem)cmb.SelectedItem;
MessageBox.Show(String.Format("Index: [{0}] CarName={1}; Value={2}", selectedIndex, selectedCar.Text, selecteVal));        

}

How do HashTables deal with collisions?

As there is some confusion about which algorithm Java's HashMap is using (in the Sun/Oracle/OpenJDK implementation), here the relevant source code snippets (from OpenJDK, 1.6.0_20, on Ubuntu):

/**
 * Returns the entry associated with the specified key in the
 * HashMap.  Returns null if the HashMap contains no mapping
 * for the key.
 */
final Entry<K,V> getEntry(Object key) {
    int hash = (key == null) ? 0 : hash(key.hashCode());
    for (Entry<K,V> e = table[indexFor(hash, table.length)];
         e != null;
         e = e.next) {
        Object k;
        if (e.hash == hash &&
            ((k = e.key) == key || (key != null && key.equals(k))))
            return e;
    }
    return null;
}

This method (cite is from lines 355 to 371) is called when looking up an entry in the table, for example from get(), containsKey() and some others. The for loop here goes through the linked list formed by the entry objects.

Here the code for the entry objects (lines 691-705 + 759):

static class Entry<K,V> implements Map.Entry<K,V> {
    final K key;
    V value;
    Entry<K,V> next;
    final int hash;

    /**
     * Creates new entry.
     */
    Entry(int h, K k, V v, Entry<K,V> n) {
        value = v;
        next = n;
        key = k;
        hash = h;
    }

  // (methods left away, they are straight-forward implementations of Map.Entry)

}

Right after this comes the addEntry() method:

/**
 * Adds a new entry with the specified key, value and hash code to
 * the specified bucket.  It is the responsibility of this
 * method to resize the table if appropriate.
 *
 * Subclass overrides this to alter the behavior of put method.
 */
void addEntry(int hash, K key, V value, int bucketIndex) {
    Entry<K,V> e = table[bucketIndex];
    table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
    if (size++ >= threshold)
        resize(2 * table.length);
}

This adds the new Entry on the front of the bucket, with a link to the old first entry (or null, if no such one). Similarily, the removeEntryForKey() method goes through the list and takes care of deleting only one entry, letting the rest of the list intact.

So, here is a linked entry list for each bucket, and I very doubt that this changed from _20 to _22, since it was like this from 1.2 on.

(This code is (c) 1997-2007 Sun Microsystems, and available under GPL, but for copying better use the original file, contained in src.zip in each JDK from Sun/Oracle, and also in OpenJDK.)

'mvn' is not recognized as an internal or external command, operable program or batch file

Go to the shell (cmd for windows) and set the path variable manually from there. It works often from there. Read more at http://www.howtogeek.com/118594/how-to-edit-your-system-path-for-easy-command-line-access/

Combining CSS Pseudo-elements, ":after" the ":last-child"

To have something like One, two and three you should add one more css style

li:nth-last-child(2):after {
    content: ' ';
}

This would remove the comma from the second last element.

Complete Code

_x000D_
_x000D_
li {_x000D_
  display: inline;_x000D_
  list-style-type: none;_x000D_
}_x000D_
_x000D_
li:after {_x000D_
  content: ", ";_x000D_
}_x000D_
_x000D_
li:nth-last-child(2):after {_x000D_
  content: '';_x000D_
}_x000D_
_x000D_
li:last-child:before {_x000D_
  content: " and ";_x000D_
}_x000D_
_x000D_
li:last-child:after {_x000D_
  content: ".";_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <ul>_x000D_
    <li>One</li>_x000D_
    <li>Two</li>_x000D_
    <li>Three</li>_x000D_
  </ul>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do you add an SDK to Android Studio?

Download your sdk file, go to Android studio: File->New->Import Module

How to get current route

You can use ActivatedRoute to get the current router

Original Answer (for RC version)

I found a solution on AngularJS Google Group and it's so easy!

ngOnInit() {
  this.router.subscribe((url) => console.log(url));
}

Here's the original answer

https://groups.google.com/d/msg/angular/wn1h0JPrF48/zl1sHJxbCQAJ

How to get GET (query string) variables in Express.js on Node.js?

There are 2 ways to pass parameters via GET method

Method 1 : The MVC approach where you pass the parameters like /routename/:paramname
In this case you can use req.params.paramname to get the parameter value For Example refer below code where I am expecting Id as a param
link could be like : http://myhost.com/items/23

var express = require('express');
var app = express();
app.get("items/:id", function(req, res) {
    var id = req.params.id;
    //further operations to perform
});
app.listen(3000);

Method 2 : General Approach : Passing variables as query string using '?' operator
For Example refer below code where I am expecting Id as a query parameter
link could be like : http://myhost.com/items?id=23

var express = require('express');
var app = express();
app.get("/items", function(req, res) {
    var id = req.query.id;
    //further operations to perform
});
app.listen(3000);

FB OpenGraph og:image not pulling images (possibly https?)

In my case, it seems that the crawler is just having a bug. I've tried:

  • Changing links to http only
  • Removing end white space
  • Switching back to http completely
  • Reinstalling the website
  • Installing a bunch of OG plugins (I use WordPress)
  • Suspecting the server has a weird misconfiguration that blocks the bots (because all the OG checkers are unable to fetch tags, and other requests to my sites are unstable)

None of these works. This costed me a week. And suddenly out of nowhere it seems to work again.

Here are my research, if someone meets this problem again:

Also, there are more checkers other than the Facebook's Object Debugger for you to check: OpenGraphCheck.com, Abhinay Rathore's Open Graph Tester, Iframely's Embed Codes, Card Validator | Twitter Developers.

Efficient way to apply multiple filters to pandas DataFrame or Series

Why not do this?

def filt_spec(df, col, val, op):
    import operator
    ops = {'eq': operator.eq, 'neq': operator.ne, 'gt': operator.gt, 'ge': operator.ge, 'lt': operator.lt, 'le': operator.le}
    return df[ops[op](df[col], val)]
pandas.DataFrame.filt_spec = filt_spec

Demo:

df = pd.DataFrame({'a': [1,2,3,4,5], 'b':[5,4,3,2,1]})
df.filt_spec('a', 2, 'ge')

Result:

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

You can see that column 'a' has been filtered where a >=2.

This is slightly faster (typing time, not performance) than operator chaining. You could of course put the import at the top of the file.

How to read a file in reverse order?

A correct, efficient answer written as a generator.

import os

def reverse_readline(filename, buf_size=8192):
    """A generator that returns the lines of a file in reverse order"""
    with open(filename) as fh:
        segment = None
        offset = 0
        fh.seek(0, os.SEEK_END)
        file_size = remaining_size = fh.tell()
        while remaining_size > 0:
            offset = min(file_size, offset + buf_size)
            fh.seek(file_size - offset)
            buffer = fh.read(min(remaining_size, buf_size))
            remaining_size -= buf_size
            lines = buffer.split('\n')
            # The first line of the buffer is probably not a complete line so
            # we'll save it and append it to the last line of the next buffer
            # we read
            if segment is not None:
                # If the previous chunk starts right from the beginning of line
                # do not concat the segment to the last line of new chunk.
                # Instead, yield the segment first 
                if buffer[-1] != '\n':
                    lines[-1] += segment
                else:
                    yield segment
            segment = lines[0]
            for index in range(len(lines) - 1, 0, -1):
                if lines[index]:
                    yield lines[index]
        # Don't yield None if the file was empty
        if segment is not None:
            yield segment

How to hide navigation bar permanently in android activity?

According to Android Developer site

I think you cant(as far as i know) hide navigation bar permanently..

However you can do one trick. Its a trick mind you.

Just when the navigation bar shows up when user touches the screen. Immediately hide it again. Its fun.

Check this.

void setNavVisibility(boolean visible) {
int newVis = SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        | SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
        | SYSTEM_UI_FLAG_LAYOUT_STABLE;
if (!visible) {
    newVis |= SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_FULLSCREEN
            | SYSTEM_UI_FLAG_HIDE_NAVIGATION;
}

// If we are now visible, schedule a timer for us to go invisible.
if (visible) {
    Handler h = getHandler();
    if (h != null) {
        h.removeCallbacks(mNavHider);
        if (!mMenusOpen && !mPaused) {
            // If the menus are open or play is paused, we will not auto-hide.
            h.postDelayed(mNavHider, 1500);
        }
    }
}

// Set the new desired visibility.
setSystemUiVisibility(newVis);
mTitleView.setVisibility(visible ? VISIBLE : INVISIBLE);
mPlayButton.setVisibility(visible ? VISIBLE : INVISIBLE);
mSeekView.setVisibility(visible ? VISIBLE : INVISIBLE);
}

See this for more information on this ..

Hide System Bar in Tablets

Checking host availability by using ping in bash scripts

I liked the idea of checking a list like:

for i in `cat Hostlist`
do  
  ping -c1 -w2 $i | grep "PING" | awk '{print $2,$3}'
done

but that snippet doesn't care if a host is unreachable, so is not a great answer IMHO.

I ran with it and wrote

for i in `cat Hostlist`
do
  ping -c1 -w2 $i >/dev/null 2>&1 ; echo $i $?
done

And I can then handle each accordingly.

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

The code above exports data without the heading columns which is weird. Here's how to do it. You have to merge the two files later though using text a editor.

SELECT column_name FROM information_schema.columns WHERE table_schema = 'my_app_db' AND table_name = 'customers' INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 5.6/Uploads/customers_heading_cols.csv' FIELDS TERMINATED BY '' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY ',';

Can I set an unlimited length for maxJsonLength in web.config?

We don't need any server side changes. you can fix this only modify by web.config file This helped for me. try this out

<appSettings>
 <add key="aspnet:MaxJsonDeserializerMembers" value="2147483647" />
<add key="aspnet:UpdatePanelMaxScriptLength" value="2147483647" />
</appSettings>  

and   

<system.web.extensions>
<scripting>
  <webServices>
    <jsonSerialization maxJsonLength="2147483647"/>
  </webServices>
</scripting>

How to set host_key_checking=false in ansible inventory file?

Adding following to ansible config worked while using ansible ad-hoc commands:

[ssh_connection]
# ssh arguments to use
ssh_args = -o StrictHostKeyChecking=no

Ansible Version

ansible 2.1.6.0
config file = /etc/ansible/ansible.cfg

Good Linux (Ubuntu) SVN client

For Ubuntu you cane make use of KDESVN integrated with Nautilus to five a Tortoise SVN Feel.

Try this ClickOffline.com : Ubuntu alternatives for Tortoise SVN

Difference between x86, x32, and x64 architectures?

As the 64bit version is an x86 architecture and was accordingly first called x86-64, that would be the most appropriate name, IMO. Also, x32 is a thing (as mentioned before)—‘x64’, however, is not a continuation of that, so is (theoretically) missleading (even though many people will know what you are talking about) and should thus only be recognised as a marketing thing, not an ‘official’ architecture (again, IMO–obviously, others disagree).

Encrypt and decrypt a String in java

I had a doubt that whether the encrypted text will be same for single text when encryption done by multiple times on a same text??

This depends strongly on the crypto algorithm you use:

  • One goal of some/most (mature) algorithms is that the encrypted text is different when encryption done twice. One reason to do this is, that an attacker how known the plain and the encrypted text is not able to calculate the key.
  • Other algorithm (mainly one way crypto hashes) like MD5 or SHA based on the fact, that the hashed text is the same for each encryption/hash.

Export a graph to .eps file with R

Another way is to use Cairographics-based SVG, PDF and PostScript Graphics Devices. This way you don't need to setEPS()

cairo_ps("image.eps")
plot(1, 10)
dev.off()

Sending and receiving data over a network using TcpClient

I've developed a dotnet library that might come in useful. I have fixed the problem of never getting all of the data if it exceeds the buffer, which many posts have discounted. Still some problems with the solution but works descently well https://github.com/NicholasLKSharp/DotNet-TCP-Communication

Unfamiliar symbol in algorithm: what does ? mean?

The upside-down A symbol is the universal quantifier from predicate logic. (Also see the more complete discussion of the first-order predicate calculus.) As others noted, it means that the stated assertions holds "for all instances" of the given variable (here, s). You'll soon run into its sibling, the backwards capital E, which is the existential quantifier, meaning "there exists at least one" of the given variable conforming to the related assertion.

If you're interested in logic, you might enjoy the book Logic and Databases: The Roots of Relational Theory by C.J. Date. There are several chapters covering these quantifiers and their logical implications. You don't have to be working with databases to benefit from this book's coverage of logic.

After MySQL install via Brew, I get the error - The server quit without updating PID file

Find usr/local/var/mysql/your_computer_name.local.err file and understand the more information about error

Location : /usr/local/var/mysql/your_computer_name.local.err

It's probably problem with permissions

  1. Find if mysql is running and kill it

ps -ef | grep mysql

kill -9 PID

where PID is second column value 2. check ownership of mysql

ls -laF /usr/local/var/mysql/

if it is owned by root, change it mysql or your user name
?

sudo chown -R mysql /usr/local/var/mysql/

Calculate time difference in minutes in SQL Server

The following works as expected:

SELECT  Diff = CASE DATEDIFF(HOUR, StartTime, EndTime)
                    WHEN 0 THEN CAST(DATEDIFF(MINUTE, StartTime, EndTime) AS VARCHAR(10))
                    ELSE CAST(60 - DATEPART(MINUTE, StartTime) AS VARCHAR(10)) +
                        REPLICATE(',60', DATEDIFF(HOUR, StartTime, EndTime) - 1) + 
                        + ',' + CAST(DATEPART(MINUTE, EndTime) AS VARCHAR(10))
                END
FROM    (VALUES 
            (CAST('11:15' AS TIME), CAST('13:15' AS TIME)),
            (CAST('10:45' AS TIME), CAST('18:59' AS TIME)),
            (CAST('10:45' AS TIME), CAST('11:59' AS TIME))
        ) t (StartTime, EndTime);

To get 24 columns, you could use 24 case expressions, something like:

SELECT  [0] = CASE WHEN DATEDIFF(HOUR, StartTime, EndTime) = 0
                        THEN DATEDIFF(MINUTE, StartTime, EndTime)
                    ELSE 60 - DATEPART(MINUTE, StartTime)
                END,
        [1] = CASE WHEN DATEDIFF(HOUR, StartTime, EndTime) = 1 
                        THEN DATEPART(MINUTE, EndTime)
                    WHEN DATEDIFF(HOUR, StartTime, EndTime) > 1 THEN 60
                END,
        [2] = CASE WHEN DATEDIFF(HOUR, StartTime, EndTime) = 2
                        THEN DATEPART(MINUTE, EndTime)
                    WHEN DATEDIFF(HOUR, StartTime, EndTime) > 2 THEN 60
                END -- ETC
FROM    (VALUES 
            (CAST('11:15' AS TIME), CAST('13:15' AS TIME)),
            (CAST('10:45' AS TIME), CAST('18:59' AS TIME)),
            (CAST('10:45' AS TIME), CAST('11:59' AS TIME))
        ) t (StartTime, EndTime);

The following also works, and may end up shorter than repeating the same case expression over and over:

WITH Numbers (Number) AS
(   SELECT  ROW_NUMBER() OVER(ORDER BY t1.N) - 1
    FROM    (VALUES (1), (1), (1), (1), (1), (1)) AS t1 (N)
            CROSS JOIN (VALUES (1), (1), (1), (1)) AS t2 (N)
), YourData AS
(   SELECT  StartTime, EndTime
    FROM    (VALUES 
                (CAST('11:15' AS TIME), CAST('13:15' AS TIME)),
                (CAST('09:45' AS TIME), CAST('18:59' AS TIME)),
                (CAST('10:45' AS TIME), CAST('11:59' AS TIME))
            ) AS t (StartTime, EndTime)
), PivotData AS
(   SELECT  t.StartTime,
            t.EndTime,
            n.Number,
            MinuteDiff = CASE WHEN n.Number = 0 AND DATEDIFF(HOUR, StartTime, EndTime) = 0 THEN DATEDIFF(MINUTE, StartTime, EndTime)
                                WHEN n.Number = 0 THEN 60 - DATEPART(MINUTE, StartTime)
                                WHEN DATEDIFF(HOUR, t.StartTime, t.EndTime) <= n.Number THEN DATEPART(MINUTE, EndTime)
                                ELSE 60
                            END
    FROM    YourData AS t
            INNER JOIN Numbers AS n
                ON n.Number <= DATEDIFF(HOUR, StartTime, EndTime)
)
SELECT  *
FROM    PivotData AS d
        PIVOT 
        (   MAX(MinuteDiff)
            FOR Number IN 
            (   [0], [1], [2], [3], [4], [5], 
                [6], [7], [8], [9], [10], [11],
                [12], [13], [14], [15], [16], [17], 
                [18], [19], [20], [21], [22], [23]
            ) 
        ) AS pvt;

It works by joining to a table of 24 numbers, so the case expression doesn't need to be repeated, then rolling these 24 numbers back up into columns using PIVOT

Conditional HTML Attributes using Razor MVC3

I guess a little more convenient and structured way is to use Html helper. In your view it can be look like:

@{
 var htmlAttr = new Dictionary<string, object>();
 htmlAttr.Add("id", strElementId);
 if (!CSSClass.IsEmpty())
 {
   htmlAttr.Add("class", strCSSClass);
 }
}

@* ... *@

@Html.TextBox("somename", "", htmlAttr)

If this way will be useful for you i recommend to define dictionary htmlAttr in your model so your view doesn't need any @{ } logic blocks (be more clear).

How to import other Python files?

How I import is import the file and use shorthand of it's name.

import DoStuff.py as DS
DS.main()

Don't forget that your importing file MUST BE named with .py extension

VB.NET Switch Statement GoTo Case

Why don't you just refactor the default case as a method and call it from both places? This should be more readable and will allow you to change the code later in a more efficient manner.

Why am I getting InputMismatchException?

Here you can see the nature of Scanner:

double nextDouble()

Returns the next token as a double. If the next token is not a float or is out of range, InputMismatchException is thrown.

Try to catch the exception

try {
    // ...
} catch (InputMismatchException e) {
    System.out.print(e.getMessage()); //try to find out specific reason.
}

UPDATE

CASE 1

I tried your code and there is nothing wrong with it. Your are getting that error because you must have entered String value. When I entered a numeric value, it runs without any errors. But once I entered String it throw the same Exception which you have mentioned in your question.

CASE 2

You have entered something, which is out of range as I have mentioned above.

I'm really wondering what you could have tried to enter. In my system, it is running perfectly without changing a single line of code. Just copy as it is and try to compile and run it.

import java.util.*;

public class Test {
    public static void main(String... args) {
        new Test().askForMarks(5);
    }

    public void askForMarks(int student) {
        double marks[] = new double[student];
        int index = 0;
        Scanner reader = new Scanner(System.in);
        while (index < student) {
            System.out.print("Please enter a mark (0..30): ");
            marks[index] = (double) checkValueWithin(0, 30); 
            index++;
        }
    }

    public double checkValueWithin(int min, int max) {
        double num;
        Scanner reader = new Scanner(System.in);
        num = reader.nextDouble();                         
        while (num < min || num > max) {                 
            System.out.print("Invalid. Re-enter number: "); 
            num = reader.nextDouble();                         
        } 

        return num;
    }
}

As you said, you have tried to enter 1.0, 2.8 and etc. Please try with this code.

Note : Please enter number one by one, on separate lines. I mean, enter 2.7, press enter and then enter second number (e.g. 6.7).

Evaluate list.contains string in JSTL

If you are using Spring Framework, you can use Spring TagLib and SpEL:

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
---
<spring:eval var="containsValue" expression="mylist.contains(myValue)" />
<c:if test="${containsValue}">style='display:none;'</c:if>

How to print environment variables to the console in PowerShell?

Prefix the variable name with env:

$env:path

For example, if you want to print the value of environment value "MINISHIFT_USERNAME", then command will be:

$env:MINISHIFT_USERNAME

You can also enumerate all variables via the env drive:

Get-ChildItem env:

ClassNotFoundException: org.slf4j.LoggerFactory

I had the same on Android. This is how i fixed it:

including ONLY the file:

slf4j-api-1.7.6.jar

in my libs/ folder

Having any additional slf4j* file, caused the NoClassDefFoundError.

Obviously, the rest of the libs can be there (android-support-v4, etc)

Versions: Eclipse Kepler 2013 06 14 - 02 29 ADT 22.3 Android SDK: 4.4.2

Hope someone saves the time i wasted thanks to this!

How to get current language code with Swift?

swift 3

let preferredLanguage = Locale.preferredLanguages[0] as String
print (preferredLanguage) //en-US

let arr = preferredLanguage.components(separatedBy: "-")
let deviceLanguage = arr.first
print (deviceLanguage) //en

Java SE 6 vs. JRE 1.6 vs. JDK 1.6 - What do these mean?

A Brief and Maybe Incorrect History of Java Versions

  • Java is a platform. It consists of two products - the software development kit, and the runtime environment.

  • When Java was first released, it was apparently just called Java. If you were a developer, you also knew the version, which was a normal "1.0" and later a "1.1". The two products that were part of the platform were also given names:

    • JDK - "Java Development Kit"
    • JRE - "Java Runtime Environment"
  • Apparently the changes in version 1.2 so significant that they started calling the platform as Java 2.

    • The default "distribution" of the platform was given the moniker "standard" to contrast it with its siblings. So you had three platforms:

      • "Java 2 Standard Edition (J2SE)"
      • "Java 2 Enterprise Edition (J2EE)"
      • "Java 2 Mobile Edition (J2ME)"
    • The JDK was officially renamed to "Java 2 Software Development Kit".

  • When version 1.5 came out, the suits decided that they needed to "rebrand" the product. So the Java platform got two versions - the product version "5" and the developer version "1.5" (Yes, the rule is explicitly mentioned -- "drop the '1.'). However, the "2" was retained in the name. So now the platform is officially called "Java 2 Platform Standard Edition 5.0 (J2SE 5.0)".

    • The suits also realized that the development community was not picking up their renaming of the JDK. But instead of reverting their change, they just decide to drop the "2" from the name of the individual products, which now get be "J2SE Development Kit 5.0 (JDK 5.0)" and "J2SE Runtime Environment 5.0 (JRE 5.0)".
  • When version 1.6 come out, someone realized that having two numbers in the name was weird. So they decide to completely drop the 2 (and the ".0" suffix), and we end up with the "Java Platform, Standard Edition 6 (Java SE 6)" containing the "Java SE Development Kit 6 (JDK 6)" and the "Java SE Runtime Environment 6 (JRE 6)".

  • Version 1.7 did not do anything stupid. If I had to guess, the next big change would be dropping the "SE", so that the cycle completes and the JDK again gets to be called the "Java Development Kit".

Notes

  • For simplicity, a bunch of trademark signs were omitted. So assume Java™, JDK™ and JRE™.

  • SO seems to have trouble rendering nested lists.

References

Epilogue

Just drop the "1." from versions printed by javac -version and java -version and you're good to go.

ASP.Net which user account running Web Service on IIS 7?

Look at the Identity of the Application Pool that's running your application. By default it will be the Network Service account, but you can change this.

At least that's how it works on 2003 server, don't know if some details have changed for 2008 server.

How to count number of files in each directory?

THis could be another way to browse through the directory structures and provide depth results.

find . -type d  | awk '{print "echo -n \""$0"  \";ls -l "$0" | grep -v total | wc -l" }' | sh 

Ignore cells on Excel line graph

Not for blanks in the middle of a range, but this works for a complex chart from a start date until infinity (ie no need to adjust the chart's data source each time informatiom is added), without showing any lines for dates that have not yet been entered. As you add dates and data to the spreadsheet, the chart expands. Without it, the chart has a brain hemorrhage.

So, to count a complex range of conditions over an extended period of time but only if the date of the events is not blank :

=IF($B6<>"",(COUNTIF($O6:$O6,Q$5)),"") returns “#N/A” if there is no date in column B.

In other words, "count apples or oranges or whatever in column O (as determined by what is in Q5) but only if column B (the dates) is not blank". By returning “#N/A”, the chart will skip the "blank" rows (blank as in a zero value or rather "#N/A").

From that table of returned values you can make a chart from a date in the past to infinity

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

\usepackage{tabularx}
% ...    
\begin{document}
% ...

\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF &  simulation & jsp\\
\hline
\end{tabularx}

How to open a new form from another form

Use this.Hide() instead of this.Close()

Convert Int to String in Swift

Converting Int to String:

let x : Int = 42
var myString = String(x)

And the other way around - converting String to Int:

let myString : String = "42"
let x: Int? = myString.toInt()

if (x != nil) {
    // Successfully converted String to Int
}

Or if you're using Swift 2 or 3:

let x: Int? = Int(myString)

Show tables, describe tables equivalent in redshift

Or simply:

\dt to show tables

\d+ <table name> to describe a table

Edit: Works using the psql command line client

No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

it looks like nobody mentioned first checking if System.Data.SqlClient is installed in the system and if a reference is made to it.

i solved my issue by installing System.Data.SqlClient and adding in a new provider in app.Config

<provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6"/>

MySQL Fire Trigger for both Insert and Update

You have to create two triggers, but you can move the common code into a procedure and have them both call the procedure.

(HTML) Download a PDF file instead of opening them in browser when clicked

If you are using HTML5 (and i guess now a days everyone uses that), there is an attribute called download.

ex. <a href="somepathto.pdf" download="filename">

here filename is optional, but if provided, it will take this name for downloaded file.

How can I disable a button in a jQuery dialog from a function?

jQuery Solution works for me.

$('.ui-button').addClass("ui-state-disabled");$('.ui-button').attr("aria-disabled",'true');$('.ui-button').prop('disabled', true);

What processes are using which ports on unix?

Which process uses port in unix;

1. netstat -Aan | grep port

root> netstat -Aan | grep 3872

output> f1000e000bb5c3b8 tcp 0 0 *.3872 . LISTEN

2. rmsock f1000e000bb5c3b8 tcpcb

output> The socket 0xf1000e000bb5c008 is being held by proccess 13959354 (java).

3. ps -ef | grep 13959354

form confirm before submit

HTML

<input type="submit" id="submit" name="submit" value="save" />

JQUERY

$(document).ready(function() {
    $("#submit").click(function(event) {
        if( !confirm('Are you sure that you want to submit the form') ){
            event.preventDefault();
        } 

    });
});

Can't create a docker image for COPY failed: stat /var/lib/docker/tmp/docker-builder error

I had such error while trying to build a docker image and push to the container registry. Inside my docker file I tried to copy a jar file from target folder and try to execute it with java -jar command.

I was solving the issue by removing .jar file and target folder from .gitignore file.

How do I open workbook programmatically as read-only?

Does this work?

Workbooks.Open Filename:=filepath, ReadOnly:=True

Or, as pointed out in a comment, to keep a reference to the opened workbook:

Dim book As Workbook
Set book = Workbooks.Open(Filename:=filepath, ReadOnly:=True)

Does Notepad++ show all hidden characters?

In newer versions of Notepad++ (currently 5.9), this option is under:

View->Show Symbol->Show All Characters

or

View->Show Symbol->Show White Space and Tab

Display help message with python argparse when script is called without any arguments

With argparse you could do:

parser.argparse.ArgumentParser()
#parser.add_args here

#sys.argv includes a list of elements starting with the program
if len(sys.argv) < 2:
    parser.print_usage()
    sys.exit(1)

How to insert current datetime in postgresql insert query

For current datetime, you can use now() function in postgresql insert query.

You can also refer following link.

insert statement in postgres for data type timestamp without time zone NOT NULL,.

Style input element to fill remaining width of its container

I suggest using Flexbox:

Be sure to add the proper vendor prefixes though!

_x000D_
_x000D_
form {_x000D_
  width: 400px;_x000D_
  border: 1px solid black;_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
input {_x000D_
  flex: 2;_x000D_
}_x000D_
_x000D_
input, label {_x000D_
  margin: 5px;_x000D_
}
_x000D_
<form method="post">_x000D_
  <label for="myInput">Sample label</label>_x000D_
  <input type="text" id="myInput" placeholder="Sample Input"/>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to add Headers on RESTful call using Jersey Client API

I use the header(name, value) method and give the return to webResource var:

Client client = Client.create();
WebResource webResource = client.resource("uri");

MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("json", js); //set parametes for request

appKey = "Bearer " + appKey; // appKey is unique number

//Get response from RESTful Server get(ClientResponse.class);
ClientResponse response = webResource.queryParams(queryParams)
    .header("Content-Type", "application/json;charset=UTF-8")
    .header("Authorization", appKey)
    .get(ClientResponse.class);

String jsonStr = response.getEntity(String.class);

How to link to apps on the app store

Apple just announced the appstore.com urls.

https://developer.apple.com/library/ios/qa/qa1633/_index.html

There are three types of App Store Short Links, in two forms, one for iOS apps, another for Mac Apps:

Company Name

iOS: http://appstore.com/ for example, http://appstore.com/apple

Mac: http://appstore.com/mac/ for example, http://appstore.com/mac/apple

App Name

iOS: http://appstore.com/ for example, http://appstore.com/keynote

Mac: http://appstore.com/mac/ for example, http://appstore.com/mac/keynote

App by Company

iOS: http://appstore.com// for example, http://appstore.com/apple/keynote

Mac: http://appstore.com/mac// for example, http://appstore.com/mac/apple/keynote

Most companies and apps have a canonical App Store Short Link. This canonical URL is created by changing or removing certain characters (many of which are illegal or have special meaning in a URL (for example, "&")).

To create an App Store Short Link, apply the following rules to your company or app name:

Remove all whitespace

Convert all characters to lower-case

Remove all copyright (©), trademark (™) and registered mark (®) symbols

Replace ampersands ("&") with "and"

Remove most punctuation (See Listing 2 for the set)

Replace accented and other "decorated" characters (ü, å, etc.) with their elemental character (u, a, etc.)

Leave all other characters as-is.

Listing 2 Punctuation characters that must be removed.

!¡"#$%'()*+,-./:;<=>¿?@[]^_`{|}~

Below are some examples to demonstrate the conversion that takes place.

App Store

Company Name examples

Gameloft => http://appstore.com/gameloft

Activision Publishing, Inc. => http://appstore.com/activisionpublishinginc

Chen's Photography & Software => http://appstore.com/chensphotographyandsoftware

App Name examples

Ocarina => http://appstore.com/ocarina

Where’s My Perry? => http://appstore.com/wheresmyperry

Brain Challenge™ => http://appstore.com/brainchallenge

How can I make my string property nullable?

Strings are nullable in C# anyway because they are reference types. You can just use public string CMName { get; set; } and you'll be able to set it to null.

What is the reason behind "non-static method cannot be referenced from a static context"?

The simple reason behind this is that Static data members of parent class can be accessed (only if they are not overridden) but for instance(non-static) data members or methods we need their reference and so they can only be called through an object.

Check if a file exists in jenkins pipeline

You need to use brackets when using the fileExists step in an if condition or assign the returned value to a variable

Using variable:

def exists = fileExists 'file'

if (exists) {
    echo 'Yes'
} else {
    echo 'No'
}

Using brackets:

if (fileExists('file')) {
    echo 'Yes'
} else {
    echo 'No'
}

Convert object of any type to JObject with Json.NET

This will work:

var cycles = cycleSource.AllCycles();

var settings = new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};

var vm = new JArray();

foreach (var cycle in cycles)
{
    var cycleJson = JObject.FromObject(cycle);
    // extend cycleJson ......
    vm.Add(cycleJson);
}

return vm;

How can I view all historical changes to a file in SVN

You could use git-svn to import the repository into a Git repository, then use git log -p filename. This shows each log entry for the file followed by the corresponding diff.

How to grant all privileges to root user in MySQL 8.0

Well, I just had the same problem. Even if route had '%' could not connect remotely. Now, having a look at my.ini file (config file in windows) the bind-address statement was missed.

So... I putted this bind-address = * after [mysqld] and restarted the service. Now it works!

What can be the reasons of connection refused errors?

In Ubuntu, Try sudo ufw allow <port_number> to allow firewall access to both of your server and db.

Styles.Render in MVC4

Set this to False on your web.config

<compilation debug="false" targetFramework="4.6.1" />