Programs & Examples On #Tfilestream

Handling optional parameters in javascript

Are you saying you can have calls like these: getData(id, parameters); getData(id, callback)?

In this case you can't obviously rely on position and you have to rely on analysing the type: getType() and then if necessary getTypeName()

Check if the parameter in question is an array or a function.

how to toggle attr() in jquery

For what it's worth.

$('.js-toggle-edit').on('click', function (e) {
    var bool = $('.js-editable').prop('readonly');
    $('.js-editable').prop('readonly', ! bool);
})

Keep in mind you can pass a closure to .prop(), and do a per element check. But in this case it doesn't matter, it's just a mass toggle.

Simple Deadlock Examples

Here's a code example from the computer science department of a university in Taiwan showing a simple java example with resource locking. That's very "real-life" relevant to me. Code below:

/**
 * Adapted from The Java Tutorial
 * Second Edition by Campione, M. and
 * Walrath, K.Addison-Wesley 1998
 */

/**
 * This is a demonstration of how NOT to write multi-threaded programs.
 * It is a program that purposely causes deadlock between two threads that
 * are both trying to acquire locks for the same two resources.
 * To avoid this sort of deadlock when locking multiple resources, all threads
 * should always acquire their locks in the same order.
 **/
public class Deadlock {
  public static void main(String[] args){
    //These are the two resource objects 
    //we'll try to get locks for
    final Object resource1 = "resource1";
    final Object resource2 = "resource2";
    //Here's the first thread.
    //It tries to lock resource1 then resource2
    Thread t1 = new Thread() {
      public void run() {
        //Lock resource 1
        synchronized(resource1){
          System.out.println("Thread 1: locked resource 1");
          //Pause for a bit, simulating some file I/O or 
          //something. Basically, we just want to give the 
          //other thread a chance to run. Threads and deadlock
          //are asynchronous things, but we're trying to force 
          //deadlock to happen here...
          try{ 
            Thread.sleep(50); 
          } catch (InterruptedException e) {}

          //Now wait 'till we can get a lock on resource 2
          synchronized(resource2){
            System.out.println("Thread 1: locked resource 2");
          }
        }
      }
    };

    //Here's the second thread.  
    //It tries to lock resource2 then resource1
    Thread t2 = new Thread(){
      public void run(){
        //This thread locks resource 2 right away
        synchronized(resource2){
          System.out.println("Thread 2: locked resource 2");
          //Then it pauses, for the same reason as the first 
          //thread does
          try{
            Thread.sleep(50); 
          } catch (InterruptedException e){}

          //Then it tries to lock resource1.  
          //But wait!  Thread 1 locked resource1, and 
          //won't release it till it gets a lock on resource2.  
          //This thread holds the lock on resource2, and won't
          //release it till it gets resource1.  
          //We're at an impasse. Neither thread can run, 
          //and the program freezes up.
          synchronized(resource1){
            System.out.println("Thread 2: locked resource 1");
          }
        }
      }
    };

    //Start the two threads. 
    //If all goes as planned, deadlock will occur, 
    //and the program will never exit.
    t1.start(); 
    t2.start();
  }
}

Best way to store password in database

As a key-hardened salted hash, using a secure algorithm such as sha-512.

Matplotlib different size subplots

Probably the simplest way is using subplot2grid, described in Customizing Location of Subplot Using GridSpec.

ax = plt.subplot2grid((2, 2), (0, 0))

is equal to

import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(2, 2)
ax = plt.subplot(gs[0, 0])

so bmu's example becomes:

import numpy as np
import matplotlib.pyplot as plt

# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# plot it
fig = plt.figure(figsize=(8, 6))
ax0 = plt.subplot2grid((1, 3), (0, 0), colspan=2)
ax0.plot(x, y)
ax1 = plt.subplot2grid((1, 3), (0, 2))
ax1.plot(y, x)

plt.tight_layout()
plt.savefig('grid_figure.pdf')

Check if an apt-get package is installed and then install it if it's not on Linux

UpAndAdam wrote:

However you can't simply rely on return codes here for scripting

In my experience you can rely on dkpg's exit codes.

The return code of dpkg -s is 0 if the package is installed and 1 if it's not, so the simplest solution I found was:

dpkg -s <pkg-name> 2>/dev/null >/dev/null || sudo apt-get -y install <pkg-name>

Works fine for me...

Opening Android Settings programmatically

You can make another class for doing this kind of activities.

public class Go {

   public void Setting(Context context)
    {
        Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}

Calling a method inside another method in same class

Recursion is a method that call itself. In this case it is a recursion. However it will be overloading until you put a restriction inside the method to stop the loop (if-condition).

How to use placeholder as default value in select2 framework

Put this in your script file:

$('select').select2({
    minimumResultsForSearch: -1,
    placeholder: function(){
        $(this).data('placeholder');
    }
});

And then in HTML, add the following code:

<select data-placeholder="Your Placeholder" multiple>
    <option></option> <------ this is where your placeholder data will appear
    <option>Value 1</option>
    <option>Value 2</option>
    <option>Value 3</option>
    <option>Value 4</option>
    <option>Value 5</option>
</select>

There can be only one auto column

CREATE TABLE book (
   id INT AUTO_INCREMENT primary key NOT NULL,
   accepted_terms BIT(1) NOT NULL,
   accepted_privacy BIT(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1

Name [jdbc/mydb] is not bound in this Context

For those who use Tomcat with Bitronix, this will fix the problem:

The error indicates that no handler could be found for your datasource 'jdbc/mydb', so you'll need to make sure your tomcat server refers to your bitronix configuration files as needed.

In case you're using btm-config.properties and resources.properties files to configure the datasource, specify these two JVM arguments in tomcat:

(if you already used them, make sure your references are correct):

  • btm.root
  • bitronix.tm.configuration

e.g.

-Dbtm.root="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59" 
-Dbitronix.tm.configuration="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59\conf\btm-config.properties" 

Now, restart your server and check the log.

htons() function in socket programing

the htons() function converts values between host and network byte orders. There is a difference between big-endian and little-endian and network byte order depending on your machine and network protocol in use.

Creating temporary files in Android

Do it in simple. According to documentation https://developer.android.com/training/data-storage/files

String imageName = "IMG_" + String.valueOf(System.currentTimeMillis()) +".jpg";
        picFile = new File(ProfileActivity.this.getCacheDir(),imageName);

and delete it after usage

picFile.delete()

Apache is "Unable to initialize module" because of module's and PHP's API don't match after changing the PHP configuration

I had a similar issue after upgrading from PHP 5.5 to PHP 5.6. The phpize and php-config libraries being used to compile the phalcon extension were still the ones from PHP 5.5. I had to run the command below:

sudo apt-get install php5.6-dev

There will be a long stacktrace, the key information I saw was this:

update-alternatives: using /usr/bin/php-config5.6 to provide /usr/bin/php-config (php-config) in auto mode
update-alternatives: using /usr/bin/phpize5.6 to provide /usr/bin/phpize (phpize) in auto mode

I hope this helps someone.

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

I had this same issue and wondered why it didn't happen with a bitbucket repo that was cloned with https. Looking into it a bit I found that the config for the BB repo had a URL that included my username. So I manually edited the config for my GH repo like so and voila, no more username prompt. I'm on Windows.

Edit your_repo_dir/.git/config (remember: .git folder is hidden)

Change:

https://github.com/WEMP/project-slideshow.git

to:

https://*username*@github.com/WEMP/project-slideshow.git

Save the file. Do a git pull to test it.

The proper way to do this is probably by using git bash commands to edit the setting, but editing the file directly didn't seem to be a problem.

List of All Locales and Their Short Codes?

The accepted answer misses some rather significant locales. For example, the Chinese locales don't distinguish between the different scriptures (simplified han, traditional han). What's a main-land Chinese citizen who wants traditional han supposed to use - the Hong Kong setting?

I've taken this list of iOS locales, removed the strange POSIX entry, formatted it as Javascript and sorted it by value (so if you use an ordered object implementation and create a list by going through the keys and returning the value, it will show the human readable text in correct order). Also, this list both contains a main entry per language as well as all the region specific variants - this way you always have a designated fallback option, say if your interface has only defined the 'en' option - you wouldn't otherwise know on what to fall back on reliably.

var LANGUAGE_BY_LOCALE = {
    af_NA: "Afrikaans (Namibia)",
    af_ZA: "Afrikaans (South Africa)",
    af: "Afrikaans",
    ak_GH: "Akan (Ghana)",
    ak: "Akan",
    sq_AL: "Albanian (Albania)",
    sq: "Albanian",
    am_ET: "Amharic (Ethiopia)",
    am: "Amharic",
    ar_DZ: "Arabic (Algeria)",
    ar_BH: "Arabic (Bahrain)",
    ar_EG: "Arabic (Egypt)",
    ar_IQ: "Arabic (Iraq)",
    ar_JO: "Arabic (Jordan)",
    ar_KW: "Arabic (Kuwait)",
    ar_LB: "Arabic (Lebanon)",
    ar_LY: "Arabic (Libya)",
    ar_MA: "Arabic (Morocco)",
    ar_OM: "Arabic (Oman)",
    ar_QA: "Arabic (Qatar)",
    ar_SA: "Arabic (Saudi Arabia)",
    ar_SD: "Arabic (Sudan)",
    ar_SY: "Arabic (Syria)",
    ar_TN: "Arabic (Tunisia)",
    ar_AE: "Arabic (United Arab Emirates)",
    ar_YE: "Arabic (Yemen)",
    ar: "Arabic",
    hy_AM: "Armenian (Armenia)",
    hy: "Armenian",
    as_IN: "Assamese (India)",
    as: "Assamese",
    asa_TZ: "Asu (Tanzania)",
    asa: "Asu",
    az_Cyrl: "Azerbaijani (Cyrillic)",
    az_Cyrl_AZ: "Azerbaijani (Cyrillic, Azerbaijan)",
    az_Latn: "Azerbaijani (Latin)",
    az_Latn_AZ: "Azerbaijani (Latin, Azerbaijan)",
    az: "Azerbaijani",
    bm_ML: "Bambara (Mali)",
    bm: "Bambara",
    eu_ES: "Basque (Spain)",
    eu: "Basque",
    be_BY: "Belarusian (Belarus)",
    be: "Belarusian",
    bem_ZM: "Bemba (Zambia)",
    bem: "Bemba",
    bez_TZ: "Bena (Tanzania)",
    bez: "Bena",
    bn_BD: "Bengali (Bangladesh)",
    bn_IN: "Bengali (India)",
    bn: "Bengali",
    bs_BA: "Bosnian (Bosnia and Herzegovina)",
    bs: "Bosnian",
    bg_BG: "Bulgarian (Bulgaria)",
    bg: "Bulgarian",
    my_MM: "Burmese (Myanmar [Burma])",
    my: "Burmese",
    yue_Hant_HK: "Cantonese (Traditional, Hong Kong SAR China)",
    ca_ES: "Catalan (Spain)",
    ca: "Catalan",
    tzm_Latn: "Central Morocco Tamazight (Latin)",
    tzm_Latn_MA: "Central Morocco Tamazight (Latin, Morocco)",
    tzm: "Central Morocco Tamazight",
    chr_US: "Cherokee (United States)",
    chr: "Cherokee",
    cgg_UG: "Chiga (Uganda)",
    cgg: "Chiga",
    zh_Hans: "Chinese (Simplified Han)",
    zh_Hans_CN: "Chinese (Simplified Han, China)",
    zh_Hans_HK: "Chinese (Simplified Han, Hong Kong SAR China)",
    zh_Hans_MO: "Chinese (Simplified Han, Macau SAR China)",
    zh_Hans_SG: "Chinese (Simplified Han, Singapore)",
    zh_Hant: "Chinese (Traditional Han)",
    zh_Hant_HK: "Chinese (Traditional Han, Hong Kong SAR China)",
    zh_Hant_MO: "Chinese (Traditional Han, Macau SAR China)",
    zh_Hant_TW: "Chinese (Traditional Han, Taiwan)",
    zh: "Chinese",
    kw_GB: "Cornish (United Kingdom)",
    kw: "Cornish",
    hr_HR: "Croatian (Croatia)",
    hr: "Croatian",
    cs_CZ: "Czech (Czech Republic)",
    cs: "Czech",
    da_DK: "Danish (Denmark)",
    da: "Danish",
    nl_BE: "Dutch (Belgium)",
    nl_NL: "Dutch (Netherlands)",
    nl: "Dutch",
    ebu_KE: "Embu (Kenya)",
    ebu: "Embu",
    en_AS: "English (American Samoa)",
    en_AU: "English (Australia)",
    en_BE: "English (Belgium)",
    en_BZ: "English (Belize)",
    en_BW: "English (Botswana)",
    en_CA: "English (Canada)",
    en_GU: "English (Guam)",
    en_HK: "English (Hong Kong SAR China)",
    en_IN: "English (India)",
    en_IE: "English (Ireland)",
    en_IL: "English (Israel)",
    en_JM: "English (Jamaica)",
    en_MT: "English (Malta)",
    en_MH: "English (Marshall Islands)",
    en_MU: "English (Mauritius)",
    en_NA: "English (Namibia)",
    en_NZ: "English (New Zealand)",
    en_MP: "English (Northern Mariana Islands)",
    en_PK: "English (Pakistan)",
    en_PH: "English (Philippines)",
    en_SG: "English (Singapore)",
    en_ZA: "English (South Africa)",
    en_TT: "English (Trinidad and Tobago)",
    en_UM: "English (U.S. Minor Outlying Islands)",
    en_VI: "English (U.S. Virgin Islands)",
    en_GB: "English (United Kingdom)",
    en_US: "English (United States)",
    en_ZW: "English (Zimbabwe)",
    en: "English",
    eo: "Esperanto",
    et_EE: "Estonian (Estonia)",
    et: "Estonian",
    ee_GH: "Ewe (Ghana)",
    ee_TG: "Ewe (Togo)",
    ee: "Ewe",
    fo_FO: "Faroese (Faroe Islands)",
    fo: "Faroese",
    fil_PH: "Filipino (Philippines)",
    fil: "Filipino",
    fi_FI: "Finnish (Finland)",
    fi: "Finnish",
    fr_BE: "French (Belgium)",
    fr_BJ: "French (Benin)",
    fr_BF: "French (Burkina Faso)",
    fr_BI: "French (Burundi)",
    fr_CM: "French (Cameroon)",
    fr_CA: "French (Canada)",
    fr_CF: "French (Central African Republic)",
    fr_TD: "French (Chad)",
    fr_KM: "French (Comoros)",
    fr_CG: "French (Congo - Brazzaville)",
    fr_CD: "French (Congo - Kinshasa)",
    fr_CI: "French (Côte d’Ivoire)",
    fr_DJ: "French (Djibouti)",
    fr_GQ: "French (Equatorial Guinea)",
    fr_FR: "French (France)",
    fr_GA: "French (Gabon)",
    fr_GP: "French (Guadeloupe)",
    fr_GN: "French (Guinea)",
    fr_LU: "French (Luxembourg)",
    fr_MG: "French (Madagascar)",
    fr_ML: "French (Mali)",
    fr_MQ: "French (Martinique)",
    fr_MC: "French (Monaco)",
    fr_NE: "French (Niger)",
    fr_RW: "French (Rwanda)",
    fr_RE: "French (Réunion)",
    fr_BL: "French (Saint Barthélemy)",
    fr_MF: "French (Saint Martin)",
    fr_SN: "French (Senegal)",
    fr_CH: "French (Switzerland)",
    fr_TG: "French (Togo)",
    fr: "French",
    ff_SN: "Fulah (Senegal)",
    ff: "Fulah",
    gl_ES: "Galician (Spain)",
    gl: "Galician",
    lg_UG: "Ganda (Uganda)",
    lg: "Ganda",
    ka_GE: "Georgian (Georgia)",
    ka: "Georgian",
    de_AT: "German (Austria)",
    de_BE: "German (Belgium)",
    de_DE: "German (Germany)",
    de_LI: "German (Liechtenstein)",
    de_LU: "German (Luxembourg)",
    de_CH: "German (Switzerland)",
    de: "German",
    el_CY: "Greek (Cyprus)",
    el_GR: "Greek (Greece)",
    el: "Greek",
    gu_IN: "Gujarati (India)",
    gu: "Gujarati",
    guz_KE: "Gusii (Kenya)",
    guz: "Gusii",
    ha_Latn: "Hausa (Latin)",
    ha_Latn_GH: "Hausa (Latin, Ghana)",
    ha_Latn_NE: "Hausa (Latin, Niger)",
    ha_Latn_NG: "Hausa (Latin, Nigeria)",
    ha: "Hausa",
    haw_US: "Hawaiian (United States)",
    haw: "Hawaiian",
    he_IL: "Hebrew (Israel)",
    he: "Hebrew",
    hi_IN: "Hindi (India)",
    hi: "Hindi",
    hu_HU: "Hungarian (Hungary)",
    hu: "Hungarian",
    is_IS: "Icelandic (Iceland)",
    is: "Icelandic",
    ig_NG: "Igbo (Nigeria)",
    ig: "Igbo",
    id_ID: "Indonesian (Indonesia)",
    id: "Indonesian",
    ga_IE: "Irish (Ireland)",
    ga: "Irish",
    it_IT: "Italian (Italy)",
    it_CH: "Italian (Switzerland)",
    it: "Italian",
    ja_JP: "Japanese (Japan)",
    ja: "Japanese",
    kea_CV: "Kabuverdianu (Cape Verde)",
    kea: "Kabuverdianu",
    kab_DZ: "Kabyle (Algeria)",
    kab: "Kabyle",
    kl_GL: "Kalaallisut (Greenland)",
    kl: "Kalaallisut",
    kln_KE: "Kalenjin (Kenya)",
    kln: "Kalenjin",
    kam_KE: "Kamba (Kenya)",
    kam: "Kamba",
    kn_IN: "Kannada (India)",
    kn: "Kannada",
    kk_Cyrl: "Kazakh (Cyrillic)",
    kk_Cyrl_KZ: "Kazakh (Cyrillic, Kazakhstan)",
    kk: "Kazakh",
    km_KH: "Khmer (Cambodia)",
    km: "Khmer",
    ki_KE: "Kikuyu (Kenya)",
    ki: "Kikuyu",
    rw_RW: "Kinyarwanda (Rwanda)",
    rw: "Kinyarwanda",
    kok_IN: "Konkani (India)",
    kok: "Konkani",
    ko_KR: "Korean (South Korea)",
    ko: "Korean",
    khq_ML: "Koyra Chiini (Mali)",
    khq: "Koyra Chiini",
    ses_ML: "Koyraboro Senni (Mali)",
    ses: "Koyraboro Senni",
    lag_TZ: "Langi (Tanzania)",
    lag: "Langi",
    lv_LV: "Latvian (Latvia)",
    lv: "Latvian",
    lt_LT: "Lithuanian (Lithuania)",
    lt: "Lithuanian",
    luo_KE: "Luo (Kenya)",
    luo: "Luo",
    luy_KE: "Luyia (Kenya)",
    luy: "Luyia",
    mk_MK: "Macedonian (Macedonia)",
    mk: "Macedonian",
    jmc_TZ: "Machame (Tanzania)",
    jmc: "Machame",
    kde_TZ: "Makonde (Tanzania)",
    kde: "Makonde",
    mg_MG: "Malagasy (Madagascar)",
    mg: "Malagasy",
    ms_BN: "Malay (Brunei)",
    ms_MY: "Malay (Malaysia)",
    ms: "Malay",
    ml_IN: "Malayalam (India)",
    ml: "Malayalam",
    mt_MT: "Maltese (Malta)",
    mt: "Maltese",
    gv_GB: "Manx (United Kingdom)",
    gv: "Manx",
    mr_IN: "Marathi (India)",
    mr: "Marathi",
    mas_KE: "Masai (Kenya)",
    mas_TZ: "Masai (Tanzania)",
    mas: "Masai",
    mer_KE: "Meru (Kenya)",
    mer: "Meru",
    mfe_MU: "Morisyen (Mauritius)",
    mfe: "Morisyen",
    naq_NA: "Nama (Namibia)",
    naq: "Nama",
    ne_IN: "Nepali (India)",
    ne_NP: "Nepali (Nepal)",
    ne: "Nepali",
    nd_ZW: "North Ndebele (Zimbabwe)",
    nd: "North Ndebele",
    nb_NO: "Norwegian Bokmål (Norway)",
    nb: "Norwegian Bokmål",
    nn_NO: "Norwegian Nynorsk (Norway)",
    nn: "Norwegian Nynorsk",
    nyn_UG: "Nyankole (Uganda)",
    nyn: "Nyankole",
    or_IN: "Oriya (India)",
    or: "Oriya",
    om_ET: "Oromo (Ethiopia)",
    om_KE: "Oromo (Kenya)",
    om: "Oromo",
    ps_AF: "Pashto (Afghanistan)",
    ps: "Pashto",
    fa_AF: "Persian (Afghanistan)",
    fa_IR: "Persian (Iran)",
    fa: "Persian",
    pl_PL: "Polish (Poland)",
    pl: "Polish",
    pt_BR: "Portuguese (Brazil)",
    pt_GW: "Portuguese (Guinea-Bissau)",
    pt_MZ: "Portuguese (Mozambique)",
    pt_PT: "Portuguese (Portugal)",
    pt: "Portuguese",
    pa_Arab: "Punjabi (Arabic)",
    pa_Arab_PK: "Punjabi (Arabic, Pakistan)",
    pa_Guru: "Punjabi (Gurmukhi)",
    pa_Guru_IN: "Punjabi (Gurmukhi, India)",
    pa: "Punjabi",
    ro_MD: "Romanian (Moldova)",
    ro_RO: "Romanian (Romania)",
    ro: "Romanian",
    rm_CH: "Romansh (Switzerland)",
    rm: "Romansh",
    rof_TZ: "Rombo (Tanzania)",
    rof: "Rombo",
    ru_MD: "Russian (Moldova)",
    ru_RU: "Russian (Russia)",
    ru_UA: "Russian (Ukraine)",
    ru: "Russian",
    rwk_TZ: "Rwa (Tanzania)",
    rwk: "Rwa",
    saq_KE: "Samburu (Kenya)",
    saq: "Samburu",
    sg_CF: "Sango (Central African Republic)",
    sg: "Sango",
    seh_MZ: "Sena (Mozambique)",
    seh: "Sena",
    sr_Cyrl: "Serbian (Cyrillic)",
    sr_Cyrl_BA: "Serbian (Cyrillic, Bosnia and Herzegovina)",
    sr_Cyrl_ME: "Serbian (Cyrillic, Montenegro)",
    sr_Cyrl_RS: "Serbian (Cyrillic, Serbia)",
    sr_Latn: "Serbian (Latin)",
    sr_Latn_BA: "Serbian (Latin, Bosnia and Herzegovina)",
    sr_Latn_ME: "Serbian (Latin, Montenegro)",
    sr_Latn_RS: "Serbian (Latin, Serbia)",
    sr: "Serbian",
    sn_ZW: "Shona (Zimbabwe)",
    sn: "Shona",
    ii_CN: "Sichuan Yi (China)",
    ii: "Sichuan Yi",
    si_LK: "Sinhala (Sri Lanka)",
    si: "Sinhala",
    sk_SK: "Slovak (Slovakia)",
    sk: "Slovak",
    sl_SI: "Slovenian (Slovenia)",
    sl: "Slovenian",
    xog_UG: "Soga (Uganda)",
    xog: "Soga",
    so_DJ: "Somali (Djibouti)",
    so_ET: "Somali (Ethiopia)",
    so_KE: "Somali (Kenya)",
    so_SO: "Somali (Somalia)",
    so: "Somali",
    es_AR: "Spanish (Argentina)",
    es_BO: "Spanish (Bolivia)",
    es_CL: "Spanish (Chile)",
    es_CO: "Spanish (Colombia)",
    es_CR: "Spanish (Costa Rica)",
    es_DO: "Spanish (Dominican Republic)",
    es_EC: "Spanish (Ecuador)",
    es_SV: "Spanish (El Salvador)",
    es_GQ: "Spanish (Equatorial Guinea)",
    es_GT: "Spanish (Guatemala)",
    es_HN: "Spanish (Honduras)",
    es_419: "Spanish (Latin America)",
    es_MX: "Spanish (Mexico)",
    es_NI: "Spanish (Nicaragua)",
    es_PA: "Spanish (Panama)",
    es_PY: "Spanish (Paraguay)",
    es_PE: "Spanish (Peru)",
    es_PR: "Spanish (Puerto Rico)",
    es_ES: "Spanish (Spain)",
    es_US: "Spanish (United States)",
    es_UY: "Spanish (Uruguay)",
    es_VE: "Spanish (Venezuela)",
    es: "Spanish",
    sw_KE: "Swahili (Kenya)",
    sw_TZ: "Swahili (Tanzania)",
    sw: "Swahili",
    sv_FI: "Swedish (Finland)",
    sv_SE: "Swedish (Sweden)",
    sv: "Swedish",
    gsw_CH: "Swiss German (Switzerland)",
    gsw: "Swiss German",
    shi_Latn: "Tachelhit (Latin)",
    shi_Latn_MA: "Tachelhit (Latin, Morocco)",
    shi_Tfng: "Tachelhit (Tifinagh)",
    shi_Tfng_MA: "Tachelhit (Tifinagh, Morocco)",
    shi: "Tachelhit",
    dav_KE: "Taita (Kenya)",
    dav: "Taita",
    ta_IN: "Tamil (India)",
    ta_LK: "Tamil (Sri Lanka)",
    ta: "Tamil",
    te_IN: "Telugu (India)",
    te: "Telugu",
    teo_KE: "Teso (Kenya)",
    teo_UG: "Teso (Uganda)",
    teo: "Teso",
    th_TH: "Thai (Thailand)",
    th: "Thai",
    bo_CN: "Tibetan (China)",
    bo_IN: "Tibetan (India)",
    bo: "Tibetan",
    ti_ER: "Tigrinya (Eritrea)",
    ti_ET: "Tigrinya (Ethiopia)",
    ti: "Tigrinya",
    to_TO: "Tonga (Tonga)",
    to: "Tonga",
    tr_TR: "Turkish (Turkey)",
    tr: "Turkish",
    uk_UA: "Ukrainian (Ukraine)",
    uk: "Ukrainian",
    ur_IN: "Urdu (India)",
    ur_PK: "Urdu (Pakistan)",
    ur: "Urdu",
    uz_Arab: "Uzbek (Arabic)",
    uz_Arab_AF: "Uzbek (Arabic, Afghanistan)",
    uz_Cyrl: "Uzbek (Cyrillic)",
    uz_Cyrl_UZ: "Uzbek (Cyrillic, Uzbekistan)",
    uz_Latn: "Uzbek (Latin)",
    uz_Latn_UZ: "Uzbek (Latin, Uzbekistan)",
    uz: "Uzbek",
    vi_VN: "Vietnamese (Vietnam)",
    vi: "Vietnamese",
    vun_TZ: "Vunjo (Tanzania)",
    vun: "Vunjo",
    cy_GB: "Welsh (United Kingdom)",
    cy: "Welsh",
    yo_NG: "Yoruba (Nigeria)",
    yo: "Yoruba",
    zu_ZA: "Zulu (South Africa)",
    zu: "Zulu"
}

set pythonpath before import statements

This will add a path to your Python process / instance (i.e. the running executable). The path will not be modified for any other Python processes. Another running Python program will not have its path modified, and if you exit your program and run again the path will not include what you added before. What are you are doing is generally correct.

set.py:

import sys
sys.path.append("/tmp/TEST")

loop.py

import sys
import time
while True:
  print sys.path
  time.sleep(1)

run: python loop.py &

This will run loop.py, connected to your STDOUT, and it will continue to run in the background. You can then run python set.py. Each has a different set of environment variables. Observe that the output from loop.py does not change because set.py does not change loop.py's environment.

A note on importing

Python imports are dynamic, like the rest of the language. There is no static linking going on. The import is an executable line, just like sys.path.append....

Python 3 sort a dict by its values

from collections import OrderedDict
from operator import itemgetter    

d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
print(OrderedDict(sorted(d.items(), key = itemgetter(1), reverse = True)))

prints

OrderedDict([('bb', 4), ('aa', 3), ('cc', 2), ('dd', 1)])

Though from your last sentence, it appears that a list of tuples would work just fine, e.g.

from operator import itemgetter  

d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
for key, value in sorted(d.items(), key = itemgetter(1), reverse = True):
    print(key, value)

which prints

bb 4
aa 3
cc 2
dd 1

WCF timeout exception detailed investigation

If you havn't tried it already - encapsulate your Server-side WCF Operations in try/finally blocks, and add logging to ensure they are actually returning.

If those show that the Operations are completing, then my next step would be to go to a lower level, and look at the actual transport layer.

Wireshark or another similar packet capturing tool can be quite helpful at this point. I'm assuming this is running over HTTP on standard port 80.

Run Wireshark on the client. In the Options when you start the capture, set the capture filter to tcp http and host service.example.com - this will reduce the amount of irrelevant traffic.

If you can, modify your client to notify you the exact start time of the call, and the time when the timeout occurred. Or just monitor it closely.

When you get an error, then you can trawl through the Wireshark logs to find the start of the call. Right click on the first packet that has your client calling out on it (Should be something like GET /service.svc or POST /service.svc) and select Follow TCP Stream.

Wireshark will decode the entire HTTP Conversation, so you can ensure that WCF is actually sending back responses.

jQuery loop over JSON result from AJAX Success?

you can remove the outer loop and replace this with data.data:

$.each(data.data, function(k, v) {
    /// do stuff
});

You were close:

$.each(data, function() {
  $.each(this, function(k, v) {
    /// do stuff
  });
});

You have an array of objects/maps so the outer loop iterates over those. The inner loop iterates over the properties on each object element.

Difference between 2 dates in SQLite

Just a note for writing timeclock functions. For those looking for hours worked, a very simple change of this gets the hours plus the minutes are shown as a percentage of 60 as most payroll companies want it.

CAST ((julianday(clockOUT) - julianday(clockIN)) * 24 AS REAL) AS HoursWorked

Clock In            Clock Out           HoursWorked
2016-08-07 11:56    2016-08-07 18:46    6.83333332836628

anaconda - graphviz - can't import after installation

The graphviz conda package is no Python package. It simply puts the graphviz files into your virtual env's Library/ directory. Look e.g. for dot.exe in the Library/bin/ directory.

To install the `graphviz` **Python package**, you can use `pip`: `conda install pip` and `pip install graphviz`. Always prefer conda packages if they are available over pip packages. Search for the package you need (`conda search pkgxy`) and then install it (`conda install pkgxy`). If it is not available, you can always build your own conda packages or you can try anaconda.org for user-built packages.

Update: There exists now a python-graphviz package at Anaconda.org which contains the Python interface for the graphviz tool. Simply install it with conda install python-graphviz.
(Thanks to wedran and g-kaklam for posting this solution and to endolith for notifying me).

Changing default shell in Linux

You can change the passwd file directly for the particular user or use the below command

chsh -s /usr/local/bin/bash username

Then log out and log in

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

How do I pass along variables with XMLHTTPRequest

If you want to pass variables to the server using GET that would be the way yes. Remember to escape (urlencode) them properly!

It is also possible to use POST, if you dont want your variables to be visible.

A complete sample would be:

var url = "bla.php";
var params = "somevariable=somevalue&anothervariable=anothervalue";
var http = new XMLHttpRequest();

http.open("GET", url+"?"+params, true);
http.onreadystatechange = function()
{
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(null);

To test this, (using PHP) you could var_dump $_GET to see what you retrieve.

Check If only numeric values were entered in input. (jQuery)

for future visitors, you can add this functon that allow user to enter only numbers: you will only have to add jquery and the class name to the input check that into http://jsfiddle.net/celia/dvnL9has/2/

$('.phone_number').keypress(function(event){
var numero= String.fromCharCode(event.keyCode);
 var myArray = ['0','1','2','3','4','5','6','7','8','9',0,1,2,3,4,5,6,7,8,9];
index = myArray.indexOf(numero);// 1
var longeur= $('.phone_number').val().length;
if(window.getSelection){
 text = window.getSelection().toString();
 } if(index>=0&text.length>0){
  }else if(index>=0&longeur<10){
    }else {return false;} });

MySQL order by before group by

Just to recap, the standard solution uses an uncorrelated subquery and looks like this:

SELECT x.*
  FROM my_table x
  JOIN (SELECT grouping_criteria,MAX(ranking_criterion) max_n FROM my_table GROUP BY grouping_criteria) y
    ON y.grouping_criteria = x.grouping_criteria
   AND y.max_n = x.ranking_criterion;

If you're using an ancient version of MySQL, or a fairly small data set, then you can use the following method:

SELECT x.*
  FROM my_table x
  LEFT
  JOIN my_table y
    ON y.joining_criteria = x.joining_criteria
   AND y.ranking_criteria < x.ranking_criteria
 WHERE y.some_non_null_column IS NULL;  

Python: Split a list into sub-lists based on index ranges

In python, it's called slicing. Here is an example of python's slice notation:

>>> list1 = ['a','b','c','d','e','f','g','h', 'i', 'j', 'k', 'l']
>>> print list1[:5]
['a', 'b', 'c', 'd', 'e']
>>> print list1[-7:]
['f', 'g', 'h', 'i', 'j', 'k', 'l']

Note how you can slice either positively or negatively. When you use a negative number, it means we slice from right to left.

How to get URL of current page in PHP

$_SERVER['REQUEST_URI']

For more details on what info is available in the $_SERVER array, see the PHP manual page for it.

If you also need the query string (the bit after the ? in a URL), that part is in this variable:

$_SERVER['QUERY_STRING']

How can I get key's value from dictionary in Swift?

Use subscripting to access the value for a dictionary key. This will return an Optional:

let apple: String? = companies["AAPL"]

or

if let apple = companies["AAPL"] {
    // ...
}

You can also enumerate over all of the keys and values:

var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]

for (key, value) in companies {
    print("\(key) -> \(value)")
}

Or enumerate over all of the values:

for value in Array(companies.values) {
    print("\(value)")
}

What do the result codes in SVN mean?

I usually use svn through a gui, either my IDE or a client. Because of that, I can never remember the codes when I do have to resort to the command line.

I find this cheat sheet a great help: Subversion Cheat Sheet

window.close and self.close do not close the window in Chrome

The below code worked for me -

window.open('location', '_self', '');
window.close();

Tested on Chrome 43.0.2357.81

Change a column type from Date to DateTime during ROR migration

In Rails 3.2 and Rails 4, Benjamin's popular answer has a slightly different syntax.

First in your terminal:

$ rails g migration change_date_format_in_my_table

Then in your migration file:

class ChangeDateFormatInMyTable < ActiveRecord::Migration
  def up
   change_column :my_table, :my_column, :datetime
  end

  def down
   change_column :my_table, :my_column, :date
  end
end

jQuery find file extension (from string)

You can use a combination of substring and lastIndexOf

Sample

var fileName = "test.jpg";
var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1); 

UNC path to a folder on my local computer

I had to:

JQuery .hasClass for multiple values in an if statement

This is in case you need both classes present. For either or logic just use ||

$('el').hasClass('first-class') || $('el').hasClass('second-class')

Feel free to optimize as needed

How to debug an apache virtual host configuration?

Here's a command I think could be of some help :

apachectl -t -D DUMP_VHOSTS

You'll get a list of all the vhosts, you'll know which one is the default one and you'll make sure that your syntax is correct (same as apachectl configtest suggested by yojimbo87).

You'll also know where each vhost is declared. It can be handy if your config files are a mess. ;)

Could not execute menu item (internal error)[Exception] - When changing PHP version from 5.3.1 to 5.2.9

To anyone who is reading this -> don't use php 5.3 anymore, switch to newer versions of php, because php 5.3 is using deprecated functions.

The following is a list of deprecated INI directives. Use of any of these INI directives will cause an E_DEPRECATED error to be thrown at startup, so I advise you to use newer version to develop.

define_syslog_variables
register_globals
register_long_arrays
safe_mode
magic_quotes_gpc
magic_quotes_runtime
magic_quotes_sybase
Comments starting with '#' are now deprecated in .INI files.

Deprecated functions:

call_user_method() (use call_user_func() instead)
call_user_method_array() (use call_user_func_array() instead)
define_syslog_variables()
dl()
ereg() (use preg_match() instead)
ereg_replace() (use preg_replace() instead)
eregi() (use preg_match() with the 'i' modifier instead)
eregi_replace() (use preg_replace() with the 'i' modifier instead)
set_magic_quotes_runtime() and its alias, magic_quotes_runtime()
session_register() (use the $_SESSION superglobal instead)
session_unregister() (use the $_SESSION superglobal instead)
session_is_registered() (use the $_SESSION superglobal instead)
set_socket_blocking() (use stream_set_blocking() instead)
split() (use preg_split() instead)
spliti() (use preg_split() with the 'i' modifier instead)
sql_regcase()
mysql_db_query() (use mysql_select_db() and mysql_query() instead)
mysql_escape_string() (use mysql_real_escape_string() instead)
Passing locale category names as strings is now deprecated. Use the LC_* family of constants instead.
The is_dst parameter to mktime(). Use the new timezone handling functions instead.

Deprecated features:

Assigning the return value of new by reference is now deprecated.
Call-time pass-by-reference is now deprecated.

PostgreSQL DISTINCT ON with different ORDER BY

For anyone using Flask-SQLAlchemy, this worked for me

from app import db
from app.models import Purchases
from sqlalchemy.orm import aliased
from sqlalchemy import desc

stmt = Purchases.query.distinct(Purchases.address_id).subquery('purchases')
alias = aliased(Purchases, stmt)
distinct = db.session.query(alias)
distinct.order_by(desc(alias.purchased_at))

Java: Unresolved compilation problem

you just try to clean maven by command

mvn clean

and after that following command

mvn eclipse:clean eclipse:eclipse

and rebuild your project....

SQL DROP TABLE foreign key constraint

If you want to DROP a table which has been referenced by other table using the foreign key use

DROP TABLE *table_name* CASCADE CONSTRAINTS;
I think it should work for you.

Convert double/float to string

The only exact solution is to perform arbitrary-precision decimal arithmetic for the base conversion, since the exact value can be very long - for 80-bit long double, up to about 10000 decimal places. Fortunately it's "only" up to about 700 places or so for IEEE double.

Rather than working with individual decimal digits, it's helpful to instead work base-1-billion (the highest power of 10 that fits in a 32-bit integer) and then convert these "base-1-billion digits" to 9 decimal digits each at the end of your computation.

I have a very dense (rather hard to read) but efficient implementation here, under LGPL MIT license:

http://git.musl-libc.org/cgit/musl/blob/src/stdio/vfprintf.c?h=v1.1.6

If you strip out all the hex float support, infinity/nan support, %g/%f/%e variation support, rounding (which will never be needed if you only want exact answers), and other things you might not need, the remaining code is rather simple.

If else on WHERE clause

You want to use coalesce():

where coalesce(email, email2) like '%[email protected]%'

If you want to handle empty strings ('') versus NULL, a case works:

where (case when email is NULL or email = '' then email2 else email end) like '%[email protected]%'

And, if you are worried about the string really being just spaces:

where (case when email is NULL or ltrim(email) = '' then email2 else email end) like '%[email protected]%'

As an aside, the sample if statement is really saying "If email starts with a number larger than 0". This is because the comparison is to 0, a number. MySQL implicitly tries to convert the string to a number. So, '[email protected]' would fail, because the string would convert as 0. As would '[email protected]'. But, '[email protected]' and '[email protected]' would succeed.

Selenium and xPath - locating a link by containing text

I think the problem is here:

[contains(text()='Some text')]

To break this down,

  1. The [] are a conditional that operates on each individual node in that node set -- each span node in your case. It matches if any of the individual nodes it operates on match the conditions inside the brackets.
  2. text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.
  3. contains is a function that operates on a string. If it is passed a node set, the node set is converted into a string by returning the string-value of the node in the node-set that is first in document order.

You should try to change this to

[text()[contains(.,'Some text')]]

  1. The outer [] are a conditional that operates on each individual node in that node set text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.

  2. The inner [] are a conditional that operates on each node in that node set.

  3. contains is a function that operates on a string. Here it is passed an individual text node (.).

Saving Excel workbook to constant path with filename from two fields

try

Sub save()
ActiveWorkbook.SaveAS Filename:="C:\-docs\cmat\Desktop\New folder\" & Range("C5").Text & chr(32) & Range("C8").Text &".xls", FileFormat:= _
  xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _
 , CreateBackup:=False
End Sub

If you want to save the workbook with the macros use the below code

Sub save()
ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
    "\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xlsm", FileFormat:= _
    xlOpenXMLWorkbookMacroEnabled, Password:=vbNullString, WriteResPassword:=vbNullString, _
    ReadOnlyRecommended:=False, CreateBackup:=False
End Sub

if you want to save workbook with no macros and no pop-up use this

Sub save()
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
    "\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xls", _
    FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
    Application.DisplayAlerts = True
End Sub

What is a Java String's default initial value?

It's initialized to null if you do nothing, as are all reference types.

How do I format a date in Jinja2?

There is a jinja2 extension you can use just need pip install (https://github.com/hackebrot/jinja2-time)

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

I had the same problem but after deleting the old plugin for org.codehaus.mojo it worked.

I use this

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.2</version>
</plugin>

Permission to write to the SD card

The suggested technique above in Dave's answer is certainly a good design practice, and yes ultimately the required permission must be set in the AndroidManifest.xml file to access the external storage.

However, the Mono-esque way to add most (if not all, not sure) "manifest options" is through the attributes of the class implementing the activity (or service).

The Visual Studio Mono plugin automatically generates the manifest, so its best not to manually tamper with it (I'm sure there are cases where there is no other option).

For example:

[Activity(Label="MonoDroid App", MainLauncher=true, Permission="android.permission.WRITE_EXTERNAL_STORAGE")]
public class MonoActivity : Activity
{
  protected override void OnCreate(Bundle bindle)
  {
    base.OnCreate(bindle);
  }
}

Refresh Excel VBA Function Results

If you include ALL references to the spreadsheet data in the UDF parameter list, Excel will recalculate your function whenever the referenced data changes:

Public Function doubleMe(d As Variant)
    doubleMe = d * 2
End Function

You can also use Application.Volatile, but this has the disadvantage of making your UDF always recalculate - even when it does not need to because the referenced data has not changed.

Public Function doubleMe()
    Application.Volatile
    doubleMe = Worksheets("Fred").Range("A1") * 2
End Function

Excel VBA Automation Error: The object invoked has disconnected from its clients

Couple of things to try...

  1. Comment out the second "Set NewBook" line of code...

  2. You already have an object reference to the workbook.

  3. Do your SaveAs after copying the sheets.

Excel VBA - How to Redim a 2D array?

This isn't exactly intuitive, but you cannot Redim(VB6 Ref) an array if you dimmed it with dimensions. Exact quote from linked page is:

The ReDim statement is used to size or resize a dynamic array that has already been formally declared using a Private, Public, or Dim statement with empty parentheses (without dimension subscripts).

In other words, instead of dim invoices(10,0)

You should use

Dim invoices()
Redim invoices(10,0)

Then when you ReDim, you'll need to use Redim Preserve (10,row)

Warning: When Redimensioning multi-dimensional arrays, if you want to preserve your values, you can only increase the last dimension. I.E. Redim Preserve (11,row) or even (11,0) would fail.

how to clear the screen in python

If you mean the screen where you have that interpreter prompt >>> you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do

import os
os.system('cls')  # on windows

or

os.system('clear')  # on linux / os x

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

For array type Please try this one.

 List<MyStok> myDeserializedObjList = (List<MyStok>)Newtonsoft.Json.JsonConvert.DeserializeObject(sc), typeof(List<MyStok>));

Please See here for details to deserialise Json

Rails 4: before_filter vs. before_action

To figure out what is the difference between before_action and before_filter, we should understand the difference between action and filter.

An action is a method of a controller to which you can route to. For example, your user creation page might be routed to UsersController#new - new is the action in this route.

Filters run in respect to controller actions - before, after or around them. These methods can halt the action processing by redirecting or set up common data to every action in the controller.

Rails 4 –> _action

Rails 3 –> _filter

Embedding Windows Media Player for all browsers

The best way to deploy video on the web is using Flash - it's much easier to embed cleanly into a web page and will play on more or less any browser and platform combination. The only reason to use Windows Media Player is if you're streaming content and you need extraordinarily strong digital rights management, and even then providers are now starting to use Flash even for these. See BBC's iPlayer for a superb example.

I would suggest that you switch to Flash even for internal use. You never know who is going to need to access it in the future, and this will give you the best possible future compatibility.

EDIT - March 20 2013. Interesting how these old questions resurface from time to time! How different the world is today and how dated this all seems. I would not recommend a Flash only route today by any means - best practice these days would probably be to use HTML 5 to embed H264 encoded video, with a Flash fallback as described here: http://diveintohtml5.info/video.html

How do I create dynamic properties in C#?

You might use a dictionary, say

Dictionary<string,object> properties;

I think in most cases where something similar is done, it's done like this.
In any case, you would not gain anything from creating a "real" property with set and get accessors, since it would be created only at run-time and you would not be using it in your code...

Here is an example, showing a possible implementation of filtering and sorting (no error checking):

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1 {

    class ObjectWithProperties {
        Dictionary<string, object> properties = new Dictionary<string,object>();

        public object this[string name] {
            get { 
                if (properties.ContainsKey(name)){
                    return properties[name];
                }
                return null;
            }
            set {
                properties[name] = value;
            }
        }

    }

    class Comparer<T> : IComparer<ObjectWithProperties> where T : IComparable {

        string m_attributeName;

        public Comparer(string attributeName){
            m_attributeName = attributeName;
        }

        public int Compare(ObjectWithProperties x, ObjectWithProperties y) {
            return ((T)x[m_attributeName]).CompareTo((T)y[m_attributeName]);
        }

    }

    class Program {

        static void Main(string[] args) {

            // create some objects and fill a list
            var obj1 = new ObjectWithProperties();
            obj1["test"] = 100;
            var obj2 = new ObjectWithProperties();
            obj2["test"] = 200;
            var obj3 = new ObjectWithProperties();
            obj3["test"] = 150;
            var objects = new List<ObjectWithProperties>(new ObjectWithProperties[]{ obj1, obj2, obj3 });

            // filtering:
            Console.WriteLine("Filtering:");
            var filtered = from obj in objects
                         where (int)obj["test"] >= 150
                         select obj;
            foreach (var obj in filtered){
                Console.WriteLine(obj["test"]);
            }

            // sorting:
            Console.WriteLine("Sorting:");
            Comparer<int> c = new Comparer<int>("test");
            objects.Sort(c);
            foreach (var obj in objects) {
                Console.WriteLine(obj["test"]);
            }
        }

    }
}

Unmount the directory which is mounted by sshfs in Mac

Just as reference let me quote the osxfuse FAQ

4.8. How should I unmount my "FUSE for OS X" file system? I cannot find the fusermount program anywhere.

Just use the standard umount command in OS X. You do not need the Linux-specific fusermount with "FUSE for OS X".

As mentioned above, either diskutil unmount or umount should work

How to get the cookie value in asp.net website

FormsAuthentication.Decrypt takes the actual value of the cookie, not the name of it. You can get the cookie value like

HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value;

and decrypt that.

How to include layout inside layout?

Edit: As in a comment rightly requested here some more information. Use the include tag

<include
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   layout="@layout/yourlayout" />

to include the layout you want to reuse.

Check this link out...

Style jQuery autocomplete in a Bootstrap input field

Try this (demo):

.ui-autocomplete {
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 1000;
  display: none;
  float: left;
  min-width: 160px;
  padding: 5px 0;
  margin: 2px 0 0;
  list-style: none;
  font-size: 14px;
  text-align: left;
  background-color: #ffffff;
  border: 1px solid #cccccc;
  border: 1px solid rgba(0, 0, 0, 0.15);
  border-radius: 4px;
  -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
  background-clip: padding-box;
}

.ui-autocomplete > li > div {
  display: block;
  padding: 3px 20px;
  clear: both;
  font-weight: normal;
  line-height: 1.42857143;
  color: #333333;
  white-space: nowrap;
}

.ui-state-hover,
.ui-state-active,
.ui-state-focus {
  text-decoration: none;
  color: #262626;
  background-color: #f5f5f5;
  cursor: pointer;
}

.ui-helper-hidden-accessible {
  border: 0;
  clip: rect(0 0 0 0);
  height: 1px;
  margin: -1px;
  overflow: hidden;
  padding: 0;
  position: absolute;
  width: 1px;
}

How to remove all line breaks from a string

The simplest solution would be:

let str = '\t\n\r this  \n \t   \r  is \r a   \n test \t  \r \n';
str.replace(/\s+/g, ' ').trim();
console.log(str); // logs: "this is a test"

.replace() with /\s+/g regexp is changing all groups of white-spaces characters to a single space in the whole string then we .trim() the result to remove all exceeding white-spaces before and after the text.

Are considered as white-spaces characters:
[ \f\n\r\t\v?\u00a0\u1680?\u2000?-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]

Are (non-void) self-closing tags valid in HTML5?

  • In HTML 4, <foo / (yes, with no > at all) means <foo> (which leads to <br /> meaning <br>> (i.e. <br>&gt;) and <title/hello/ meaning <title>hello</title>). This is an SGML rule that browsers did a very poor job of supporting, and the spec advises authors to avoid the syntax.

  • In XHTML, <foo /> means <foo></foo>. This is an XML rule that applies to all XML documents. That said, XHTML is often served as text/html which (historically at least) gets processed by browsers using a different parser than documents served as application/xhtml+xml. The W3C provides compatibility guidelines to follow for XHTML as text/html. (Essentially: Only use self-closing tag syntax when the element is defined as EMPTY (and the end tag was forbidden in the HTML spec)).

  • In HTML5, the meaning of <foo /> depends on the type of element.

    • On HTML elements that are designated as void elements (essentially "An element that existed before HTML5 and which was forbidden to have any content"), end tags are simply forbidden. The slash at the end of the start tag is allowed, but has no meaning. It is just syntactic sugar for people (and syntax highlighters) that are addicted to XML.
    • On other HTML elements, the slash is an error, but error recovery will cause browsers to ignore it and treat the tag as a regular start tag. This will usually end up with a missing end tag causing subsequent elements to be children instead of siblings.
    • Foreign elements (imported from XML applications such as SVG) treat it as self-closing syntax.

Javascript Drag and drop for touch devices

For anyone looking to use this and keep the 'click' functionality (as John Landheer mentions in his comment), you can do it with just a couple of modifications:

Add a couple of globals:

var clickms = 100;
var lastTouchDown = -1;

Then modify the switch statement from the original to this:

var d = new Date();
switch(event.type)
{
    case "touchstart": type = "mousedown"; lastTouchDown = d.getTime(); break;
    case "touchmove": type="mousemove"; lastTouchDown = -1; break;        
    case "touchend": if(lastTouchDown > -1 && (d.getTime() - lastTouchDown) < clickms){lastTouchDown = -1; type="click"; break;} type="mouseup"; break;
    default: return;
}

You may want to adjust 'clickms' to your tastes. Basically it's just watching for a 'touchstart' followed quickly by a 'touchend' to simulate a click.

java.security.AccessControlException: Access denied (java.io.FilePermission

Although it is not recommended, but if you really want to let your web application access a folder outside its deployment directory. You need to add following permission in java.policy file (path is as in the reply of Petey B)

permission java.io.FilePermission "your folder path", "write"

In your case it would be

permission java.io.FilePermission "S:/PDSPopulatingProgram/-", "write"

Here /- means any files or sub-folders inside this folder.

Warning: But by doing this, you are inviting some security risk.

How can I use a JavaScript variable as a PHP variable?

PHP runs on the server. It outputs some text (usually). This is then parsed by the client.

During and after the parsing on the client, JavaScript runs. At this stage it is too late for the PHP script to do anything.

If you want to get anything back to PHP you need to make a new HTTP request and include the data in it (either in the query string (GET data) or message body (POST data).

You can do this by:

  • Setting location (GET only)
  • Submitting a form (with the FormElement.submit() method)
  • Using the XMLHttpRequest object (the technique commonly known as Ajax). Various libraries do some of the heavy lifting for you here, e.g. YUI or jQuery.

Which ever option you choose, the PHP is essentially the same. Read from $_GET or $_POST, run your database code, then return some data to the client.

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

I'm loathe to add another answer to this already overcrowded question, but it might be of use to someone.

I found that if a "release" already had a build assigned when I uploaded a new one, clearing the existing build and attempting to select the new one always showed it as "processing".

However, if I removed the old build and saved then refreshed the page, the new build could be selected.

jQuery Button.click() event is triggered twice

This can be caused for following reasons:

  1. You have included the script more than once in the same html file
  2. You have added the event listener twice (eg: using onclick attribute on the element and also with jquery
  3. The event is bubbled up to some parent element. (you may consider using event.stopPropagation).
  4. If you use template inheritance like extends in Django, most probably you have included the script in more than one file which are combined together by include or extend template tags
  5. If you are using Django template, you have wrongly placed a block inside another.

So, you should either find them out and remove the duplicate import. It is the best thing to do.

Another solution is to remove all click event listeners first in the script like:

$("#myId").off().on("click", function(event) {
event.stopPropagation();
});

You can skip event.stopPropagation(); if you are sure that the event is not bubbled.

Difference between sh and bash

Shell is an interface between a user and OS to access to an operating system's services. It can be either GUI or CLI (Command Line interface).

sh (Bourne shell) is a shell command-line interpreter, for Unix/Unix-like operating systems. It provides some built-in commands. In scripting language we denote interpreter as #!/bin/sh. It was one most widely supported by other shells like bash (free/open), kash (not free).

Bash (Bourne again shell) is a shell replacement for the Bourne shell. Bash is superset of sh. Bash supports sh. POSIX is a set of standards defining how POSIX-compliant systems should work. Bash is not actually a POSIX compliant shell. In a scripting language we denote the interpreter as #!/bin/bash.

Analogy:

  • Shell is like an interface or specifications or API.
  • sh is a class which implements the Shell interface.
  • Bash is a subclass of the sh.

enter image description here

Make the current commit the only (initial) commit in a Git repository?

git filter-branch is the major-surgery tool.

git filter-branch --parent-filter true -- @^!

--parent-filter gets the parents on stdin and should print the rewritten parents on stdout; unix true exits successfully and prints nothing, so: no parents. @^! is Git shorthand for "the head commit but not any of its parents". Then delete all the other refs and push at leisure.

This view is not constrained

When creating a layout, it's easier to work with one control at a time, instead of adding them all at once.

From the Layouts Palette, drag a ConstraintLayout to the screen.

Move your desired controls inside the ConstraintLayout.

So the ConstraintLayout will now be the control's parents, and if you switch to the xml code, the controls will be nested under the ConstraintLayout.

Right click on your control, select Constraint from the menu, and select how you want to align it to the parent ConstraintLayout, top, start, etc.

If you need to align two controls relative to each other, select both controls at the same time with the Ctrl key, then right click to open the constrain menu.

More info: https://developer.android.com/training/constraint-layout

enter image description here

enter image description here You can specify the constraint separation distance in the Constraint Layout tab:

enter image description here

Selecting data frame rows based on partial string match in a column

LIKE should work in sqlite:

require(sqldf)
df <- data.frame(name = c('bob','robert','peter'),id=c(1,2,3))
sqldf("select * from df where name LIKE '%er%'")
    name id
1 robert  2
2  peter  3

JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

Some of the previously mentioned solutions did not work for me, even though they are of more general usage. Alternatively I've found this one that did the job on window resize:

$(window).bind('resize', function(e){
    window.resizeEvt;
    $(window).resize(function(){
        clearTimeout(window.resizeEvt);
        window.resizeEvt = setTimeout(function(){
        //code to do after window is resized
        }, 250);
    });
});

Adding Image to xCode by dragging it from File

You can't add image from desktop to UIimageView, you only can add image (dragging) into project folders and then select the name image into UIimageView properties (inspector).

Tutorial on how to do that: http://conecode.com/news/2011/06/ios-tutorial-creating-an-image-view-uiimageview/

Convert normal date to unix timestamp

var datestr = '2012.08.10';
var timestamp = (new Date(datestr.split(".").join("-")).getTime())/1000;

Create component to specific module with Angular-CLI

this is what worked for me :

1 -->  ng g module new-module

2 -->  ng g c new-module/component-test --module=new-module/new-module.module.ts

If you want to generate a component without its directory use --flat flag.

Mockito How to mock only the call of a method of the superclass

The reason is your base class is not public-ed, then Mockito cannot intercept it due to visibility, if you change base class as public, or @Override in sub class (as public), then Mockito can mock it correctly.

public class BaseService{
  public boolean foo(){
    return true;
  }
}

public ChildService extends BaseService{
}

@Test
@Mock ChildService childService;
public void testSave() {
  Mockito.when(childService.foo()).thenReturn(false);

  // When
  assertFalse(childService.foo());
}

How to POST form data with Spring RestTemplate?

here is the full program to make a POST rest call using spring's RestTemplate.

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.ituple.common.dto.ServiceResponse;

   public class PostRequestMain {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
        Map map = new HashMap<String, String>();
        map.put("Content-Type", "application/json");

        headers.setAll(map);

        Map req_payload = new HashMap();
        req_payload.put("name", "piyush");

        HttpEntity<?> request = new HttpEntity<>(req_payload, headers);
        String url = "http://localhost:8080/xxx/xxx/";

        ResponseEntity<?> response = new RestTemplate().postForEntity(url, request, String.class);
        ServiceResponse entityResponse = (ServiceResponse) response.getBody();
        System.out.println(entityResponse.getData());
    }

}

Adding a rule in iptables in debian to open a new port

About your command line:

root@debian:/# sudo iptables -A INPUT -p tcp --dport 3306 --jump ACCEPT
root@debian:/# iptables-save
  • You are already authenticated as root so sudo is redundant there.

  • You are missing the -j or --jump just before the ACCEPT parameter (just tought that was a typo and you are inserting it correctly).

About yout question:

If you are inserting the iptables rule correctly as you pointed it in the question, maybe the issue is related to the hypervisor (virtual machine provider) you are using.

If you provide the hypervisor name (VirtualBox, VMWare?) I can further guide you on this but here are some suggestions you can try first:

check your vmachine network settings and:

  • if it is set to NAT, then you won't be able to connect from your base machine to the vmachine.

  • if it is set to Hosted, you have to configure first its network settings, it is usually to provide them an IP in the range 192.168.56.0/24, since is the default the hypervisors use for this.

  • if it is set to Bridge, same as Hosted but you can configure it whenever IP range makes sense for you configuration.

Hope this helps.

Vagrant error : Failed to mount folders in Linux guest

The plugin vagrant-vbguest GitHub RubyGems solved my problem:

$ vagrant plugin install vagrant-vbguest

Output:

$ vagrant reload
==> default: Attempting graceful shutdown of VM...
...
==> default: Machine booted and ready!
GuestAdditions 4.3.12 running --- OK.
==> default: Checking for guest additions in VM...
==> default: Configuring and enabling network interfaces...
==> default: Exporting NFS shared folders...
==> default: Preparing to edit /etc/exports. Administrator privileges will be required...
==> default: Mounting NFS shared folders...
==> default: VM already provisioned. Run `vagrant provision` or use `--provision` to force it

Just make sure you are running the latest version of VirtualBox

Why would $_FILES be empty when uploading files to PHP?

Here's a check-list for file uploading in PHP:

  1. Check php.ini for:
    file_uploads = On
    post_max_size = 100M
    upload_max_filesize = 100M

    • You might need to use .htaccess or .user.ini if you are on shared hosting and don't have access to php.ini.
    • Make sure you’re editing the correct ini file – use the phpinfo() function to verify your settings are actually being applied.
    • Also make sure you don’t misspell the sizes - it should be 100M not 100MB.
  2. Make sure your <form> tag has the enctype="multipart/form-data" attribute. No other tag will work, it has to be your FORM tag. Double check that it is spelled correctly. Double check that multipart/form-data is surrounded by STRAIGHT QUOTES, not smart quotes pasted in from Word OR from a website blog (WordPress converts straight quotes to angle quotes!). If you have multiple forms on the page, make sure they both have this attribute. Type them in manually, or try straight single quotes typed in manually.

  3. Make sure you do not have two input file fields with the same name attribute. If you need to support multiple, put square brackets at the end of the name:

    <input type="file" name="files[]">
    <input type="file" name="files[]">
    
  4. Make sure your tmp and upload directories have the correct read+write permissions set. The temporary upload folder is specified in PHP settings as upload_tmp_dir.

  5. Make sure your file destination and tmp/upload directories do not have spaces in them.

  6. Make sure all <form>'s on your page have </form> close tags.

  7. Make sure your FORM tag has method="POST". GET requests do not support multipart/form-data uploads.

  8. Make sure your file input tag has a NAME attribute. An ID attribute is NOT sufficient! ID attributes are for use in the DOM, not for POST payloads.

  9. Make sure you are not using Javascript to disable your <input type="file"> field on submission

  10. Make sure you're not nesting forms like <form><form></form></form>

  11. Check your HTML structure for invalid/overlapping tags like <div><form></div></form>

  12. Also make sure that the file you are uploading does not have any non-alphanumeric characters in it.

  13. Once, I just spent hours trying to figure out why this was happening to me all of a sudden. It turned out that I had modified some of the PHP settings in .htaccess, and one of them (not sure which yet) was causing the upload to fail and $_FILES to be empty.

  14. You could potentially try avoiding underscores (_) in the name="" attribute of the <input> tag

  15. Try uploading very small files to narrow down whether it's a file-size issue.

  16. Check your available disk space. Although very rare, it is mentioned in this PHP Manual page comment:

    If the $_FILES array suddenly goes mysteriously empty, even though your form seems correct, you should check the disk space available for your temporary folder partition. In my installation, all file uploads failed without warning. After much gnashing of teeth, I tried freeing up additional space, after which file uploads suddenly worked again.

  17. Be sure that you're not submitting the form through an AJAX POST request instead of a normal POST request that causes a page to reload. I went through each and every point in the list above, and finally found out that the reason due to which my $_FILES variable was empty was that I was submitting the form using an AJAX POST request. I know that there are methods to upload files using ajax too, but this could be a valid reason why your $_FILES array is empty.

Source for some of these points:
http://getluky.net/2004/10/04/apachephp-_files-array-mysteriously-empty/

Complex CSS selector for parent of active child

Unfortunately, there's no way to do that with CSS.

It's not very difficult with JavaScript though:

// JavaScript code:
document.getElementsByClassName("active")[0].parentNode;

// jQuery code:
$('.active').parent().get(0); // This would be the <a>'s parent <li>.

What techniques can be used to define a class in JavaScript, and what are their trade-offs?

ES2015 Classes

In the ES2015 specification, you can use the class syntax which is just sugar over the prototype system.

class Person {
  constructor(name) {
    this.name = name;
  }
  toString() {
    return `My name is ${ this.name }.`;
  }
}

class Employee extends Person {
  constructor(name, hours) {
    super(name);
    this.hours = hours;
  }
  toString() {
    return `${ super.toString() } I work ${ this.hours } hours.`;
  }
}

Benefits

The main benefit is that static analysis tools find it easier to target this syntax. It is also easier for others coming from class-based languages to use the language as a polyglot.

Caveats

Be wary of its current limitations. To achieve private properties, one must resort to using Symbols or WeakMaps. In future releases, classes will most likely be expanded to include these missing features.

Support

Browser support isn't very good at the moment (supported by nearly everyone except IE), but you can use these features now with a transpiler like Babel.

Resources

How to read a config file using python

This looks like valid Python code, so if the file is on your project's classpath (and not in some other directory or in arbitrary places) one way would be just to rename the file to "abc.py" and import it as a module, using import abc. You can even update the values using the reload function later. Then access the values as abc.path1 etc.

Of course, this can be dangerous in case the file contains other code that will be executed. I would not use it in any real, professional project, but for a small script or in interactive mode this seems to be the simplest solution.

Just put the abc.py into the same directory as your script, or the directory where you open the interactive shell, and do import abc or from abc import *.

Saving excel worksheet to CSV files with filename+worksheet name using VB

I had a similar problem. Data in a worksheet I needed to save as a separate CSV file.

Here's my code behind a command button


Private Sub cmdSave()
    Dim sFileName As String
    Dim WB As Workbook

    Application.DisplayAlerts = False

    sFileName = "MyFileName.csv"
    'Copy the contents of required sheet ready to paste into the new CSV
    Sheets(1).Range("A1:T85").Copy 'Define your own range

    'Open a new XLS workbook, save it as the file name
    Set WB = Workbooks.Add
    With WB
        .Title = "MyTitle"
        .Subject = "MySubject"
        .Sheets(1).Select
        ActiveSheet.Paste
        .SaveAs "MyDirectory\" & sFileName, xlCSV
        .Close
    End With

    Application.DisplayAlerts = True
End Sub

This works for me :-)

Select rows from a data frame based on values in a vector

Another option would be to use a keyed data.table:

library(data.table)
setDT(dt, key = 'fct')[J(vc)]  # or: setDT(dt, key = 'fct')[.(vc)]

which results in:

   fct X
1:   a 2
2:   a 7
3:   a 1
4:   c 3
5:   c 5
6:   c 9
7:   c 2
8:   c 4

What this does:

  • setDT(dt, key = 'fct') transforms the data.frame to a data.table (which is an enhanced form of a data.frame) with the fct column set as key.
  • Next you can just subset with the vc vector with [J(vc)].

NOTE: when the key is a factor/character variable, you can also use setDT(dt, key = 'fct')[vc] but that won't work when vc is a numeric vector. When vc is a numeric vector and is not wrapped in J() or .(), vc will work as a rowindex.

A more detailed explanation of the concept of keys and subsetting can be found in the vignette Keys and fast binary search based subset.

An alternative as suggested by @Frank in the comments:

setDT(dt)[J(vc), on=.(fct)]

When vc contains values that are not present in dt, you'll need to add nomatch = 0:

setDT(dt, key = 'fct')[J(vc), nomatch = 0]

or:

setDT(dt)[J(vc), on=.(fct), nomatch = 0]

In Angular, What is 'pathmatch: full' and what effect does it have?

pathMatch = 'full' results in a route hit when the remaining, unmatched segments of the URL match is the prefix path

pathMatch = 'prefix' tells the router to match the redirect route when the remaining URL begins with the redirect route's prefix path.

Ref: https://angular.io/guide/router#set-up-redirects

pathMatch: 'full' means, that the whole URL path needs to match and is consumed by the route matching algorithm.

pathMatch: 'prefix' means, the first route where the path matches the start of the URL is chosen, but then the route matching algorithm is continuing searching for matching child routes where the rest of the URL matches.

Why do we use web.xml?

It says all the requests to go through WicketFilter


Also, if you use wicket WicketApplication for application level settings. Like URL patterns and things that are true at app level


This is what you need really, http://wicket.apache.org/learn/examples/helloworld.html

Matplotlib scatter plot with different text at each data point

You may also use pyplot.text (see here).

def plot_embeddings(M_reduced, word2Ind, words):
    """ 
        Plot in a scatterplot the embeddings of the words specified in the list "words".
        Include a label next to each point.
    """
    for word in words:
        x, y = M_reduced[word2Ind[word]]
        plt.scatter(x, y, marker='x', color='red')
        plt.text(x+.03, y+.03, word, fontsize=9)
    plt.show()

M_reduced_plot_test = np.array([[1, 1], [-1, -1], [1, -1], [-1, 1], [0, 0]])
word2Ind_plot_test = {'test1': 0, 'test2': 1, 'test3': 2, 'test4': 3, 'test5': 4}
words = ['test1', 'test2', 'test3', 'test4', 'test5']
plot_embeddings(M_reduced_plot_test, word2Ind_plot_test, words)

enter image description here

TypeError: list indices must be integers or slices, not str

I had same error and the mistake was that I had added list and dictionary into the same list (object) and when I used to iterate over the list of dictionaries and use to hit a list (type) object then I used to get this error.

Its was a code error and made sure that I only added dictionary objects to that list and list typed object into the list, this solved my issue as well.

How to get main div container to align to centre?

You can text-align: center the body to center the container. Then text-align: left the container to get all the text, etc. to align left.

wait process until all subprocess finish?

A Popen object has a .wait() method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status).

If you use this method, you'll prevent that the process zombies are lying around for too long.

(Alternatively, you can use subprocess.call() or subprocess.check_call() for calling and waiting. If you don't need IO with the process, that might be enough. But probably this is not an option, because your if the two subprocesses seem to be supposed to run in parallel, which they won't with (check_)call().)

If you have several subprocesses to wait for, you can do

exit_codes = [p.wait() for p in p1, p2]

which returns as soon as all subprocesses have finished. You then have a list of return codes which you maybe can evaluate.

What is a good naming convention for vars, methods, etc in C++?

consistency and readability (self-documenting code) are important. some clues (such as case) can and should be used to avoid collisions, and to indicate whether an instance is required.

one of the best practices i got into was the use of code formatters (astyle and uncrustify are 2 examples). code formatters can destroy your code formatting - configure the formatter, and let it do its job. seriously, forget about manual formatting and get into the practice of using them. they will save a ton of time.

as mentioned, be very descriptive with naming. also, be very specific with scoping (class types/data/namespaces/anonymous namespaces). in general, i really like much of java's common written form - that is a good reference and similar to c++.

as for specific appearance/naming, this is a small sample similar to what i use (variables/arguments are lowerCamel and this only demonstrates a portion of the language's features):

/** MYC_BEGIN_FILE_ID::FD_Directory_nanotimer_FN_nanotimer_hpp_::MYC_BEGIN_FILE_DIR::Directory/nanotimer::MYC_BEGIN_FILE_FILE::nanotimer.hpp::Copyright... */
#ifndef FD_Directory_nanotimer_FN_nanotimer_hpp_
#define FD_Directory_nanotimer_FN_nanotimer_hpp_

/* typical commentary omitted -- comments detail notations/conventions. also, no defines/macros other than header guards */

namespace NamespaceName {

/* types prefixed with 't_' */
class t_nanotimer : public t_base_timer {
    /* private types */
    class t_thing {
        /*...*/
    };
public:
    /* public types */
    typedef uint64_t t_nanosecond;

    /* factory initializers -- UpperCamel */
    t_nanotimer* WithFloat(const float& arg);
    /* public/protected class interface -- UpperCamel */
    static float Uptime();
protected:
    /* static class data -- UpperCamel -- accessors, if needed, use Get/Set prefix */
    static const t_spoke Spoke;
public:
    /* enums in interface are labeled as static class data */
    enum { Granularity = 4 };
public:
    /* construction/destruction -- always use proper initialization list */
    explicit t_nanotimer(t_init);
    explicit t_nanotimer(const float& arg);

    virtual ~t_nanotimer();

    /*
       public and protected instance methods -- lowercaseCamel()
       - booleans prefer is/has
       - accessors use the form: getVariable() setVariable().
       const-correctness is important
     */
    const void* address() const;
    virtual uint64_t hashCode() const;
protected:
    /* interfaces/implementation of base pure virtuals (assume this was pure virtual in t_base_timer) */
    virtual bool hasExpired() const;
private:
    /* private methods and private static data */
    void invalidate();
private:
    /*
       instance variables
       - i tend to use underscore suffix, but d_ (for example) is another good alternative
       - note redundancy in visibility
     */
    t_thing ivar_;
private:
    /* prohibited stuff */
    explicit t_nanotimer();
    explicit t_nanotimer(const int&);
};
} /* << NamespaceName */
/* i often add a multiple include else block here, preferring package-style inclusions */    
#endif /* MYC_END_FILE::FD_Directory_nanotimer_FN_nanotimer_hpp_ */

With MySQL, how can I generate a column containing the record index in a table?

SELECT @i:=@i+1 AS iterator, t.*
FROM tablename t,(SELECT @i:=0) foo

OracleCommand SQL Parameters Binding

Remove single quotes around @username, and with respect to oracle use : with parameter name instead of @, like:

OracleCommand oraCommand = new OracleCommand("SELECT fullname FROM sup_sys.user_profile
                           WHERE domain_user_name = :userName", db);
oraCommand.Parameters.Add(new OracleParameter("userName", domainUser));

Source: Using Parameters

CSS ''background-color" attribute not working on checkbox inside <div>

A checkbox does not have background color.

But to add the effect, you may wrap each checkbox with a div that has color:

<div class="evenRow">
    <input type="checkbox" />
</div>
<div class="oddRow">
    <input type="checkbox" />
</div>
<div class="evenRow">
    <input type="checkbox" />
</div>
<div class="oddRow">
    <input type="checkbox" />
</div>

ImportError: No module named site on Windows

First uninstall python and again install the latest version during installation use custom install and mark all user checkbox and set the installation path C:\Python 3.9 and make PYTHON_HOME value C:\Python 3.9 in the Environmental variable it works for me

Getting "java.nio.file.AccessDeniedException" when trying to write to a folder

I was getting the same error when trying to copy a file. Closing a channel associated with the target file solved the problem.

Path destFile = Paths.get("dest file");
SeekableByteChannel destFileChannel = Files.newByteChannel(destFile);
//...
destFileChannel.close();  //removing this will throw java.nio.file.AccessDeniedException:
Files.copy(Paths.get("source file"), destFile);

TypeScript: casting HTMLElement

To end up with:

  • an actual Array object (not a NodeList dressed up as an Array)
  • a list that is guaranteed to only include HTMLElements, not Nodes force-casted to HTMLElements
  • a warm fuzzy feeling to do The Right Thing

Try this:

let nodeList : NodeList = document.getElementsByTagName('script');
let elementList : Array<HTMLElement> = [];

if (nodeList) {
    for (let i = 0; i < nodeList.length; i++) {
        let node : Node = nodeList[i];

        // Make sure it's really an Element
        if (node.nodeType == Node.ELEMENT_NODE) {
            elementList.push(node as HTMLElement);
        }
    }
}

Enjoy.

Select n random rows from SQL Server table

If you (unlike the OP) need a specific number of records (which makes the CHECKSUM approach difficult) and desire a more random sample than TABLESAMPLE provides by itself, and also want better speed than CHECKSUM, you may make do with a merger of the TABLESAMPLE and NEWID() methods, like this:

DECLARE @sampleCount int = 50
SET STATISTICS TIME ON

SELECT TOP (@sampleCount) * 
FROM [yourtable] TABLESAMPLE(10 PERCENT)
ORDER BY NEWID()

SET STATISTICS TIME OFF

In my case this is the most straightforward compromise between randomness (it's not really, I know) and speed. Vary the TABLESAMPLE percentage (or rows) as appropriate - the higher the percentage, the more random the sample, but expect a linear drop off in speed. (Note that TABLESAMPLE will not accept a variable)

Spring Boot default H2 jdbc connection (and H2 console)

I had made a very stupid mistake when I had this same problem. I had added H2 DB for running unit test cases and hence I had set the scope to test in pom.xml. While running the application using mvn spring:run I removed the scope and it works fine now.

How to turn a string formula into a "real" formula

Say, let we have column E filled by formulas that returns string, like:

= " = " & D7

where D7 cell consist more complicated formula, that composes final desired result, say:

= 3.02 * 1024 * 1024 * 1024

And so in all huge qty of rows that are.

When rows are a little - it just enough to copy desired cells as values (by RMB)
to nearest column, say G, and press F2 with following Enter in each of rows.
However, in case of huge qty of rows it's impossible ...

So, No VBA. No extra formulas. No F&R

No mistakes, no typo, but stupid mechanical actions instead only,

Like on a Ford conveyor. And in just a few seconds only:

  1. [Assume, all of involved columns are in "General" format.]
  2. Open Notepad++
  3. Select entire column D
  4. Ctrl+C
  5. Ctrl+V in NPP
  6. Ctrl+A in NPP
  7. Select cell in the first row of desired column G1
  8. Ctrl+V
  9. Enjoy :) .

How To Change DataType of a DataColumn in a DataTable?

DataTable DT = ...
// Rename column to OLD:
DT.Columns["ID"].ColumnName = "ID_OLD";
// Add column with new type:
DT.Columns.Add( "ID", typeof(int) );
// copy data from old column to new column with new type:
foreach( DataRow DR in DT.Rows )
{ DR["ID"] = Convert.ToInt32( DR["ID_OLD"] ); }
// remove "OLD" column
DT.Columns.Remove( "ID_OLD" );

How do you get the Git repository's name in some Git repository?

This approach using git-remote worked well for me for HTTPS remotes:

$ git remote -v | grep "(fetch)" | sed 's/.*\/\([^ ]*\)\/.*/\1/'
                                                |  |        | |
                                                |  |        | +---------------+
                                                |  |        | Extract capture |
                                                |  +--------------------+-----+
                                                |Repository name capture|
                                                +-----------------------+

Example

Loop through an array php

Ok, I know there is an accepted answer but… for more special cases you also could use this one:

array_map(function($n) { echo $n['filename']; echo $n['filepath'];},$array);

Or in a more un-complex way:

function printItem($n){
    echo $n['filename'];
    echo $n['filepath'];
}

array_map('printItem', $array);

This will allow you to manipulate the data in an easier way.

Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative

If you have two lists that have the predicted and actual values; as it appears you do, you can pass them to a function that will calculate TP, FP, TN, FN with something like this:

def perf_measure(y_actual, y_hat):
    TP = 0
    FP = 0
    TN = 0
    FN = 0

    for i in range(len(y_hat)): 
        if y_actual[i]==y_hat[i]==1:
           TP += 1
        if y_hat[i]==1 and y_actual[i]!=y_hat[i]:
           FP += 1
        if y_actual[i]==y_hat[i]==0:
           TN += 1
        if y_hat[i]==0 and y_actual[i]!=y_hat[i]:
           FN += 1

    return(TP, FP, TN, FN)

From here I think you will be able to calculate rates of interest to you, and other performance measure like specificity and sensitivity.

How do I fix MSB3073 error in my post-build event?

In my case, the dll I was creating by building the project was still in use in the background. I killed the application and then xcopy worked fine as expected.

Mixing C# & VB In The Same Project

Walkthrough: Using Multiple Programming Languages in a Web Site Project http://msdn.microsoft.com/en-us/library/ms366714.aspx

By default, the App_Code folder does not allow multiple programming languages. However, in a Web site project you can modify your folder structure and configuration settings to support multiple programming languages such as Visual Basic and C#. This allows ASP.NET to create multiple assemblies, one for each language. For more information, see Shared Code Folders in ASP.NET Web Projects. Developers commonly include multiple programming languages in Web applications to support multiple development teams that operate independently and prefer different programming languages.

Store text file content line by line into array

Just use Apache Commons IO

List<String> lines = IOUtils.readLines(new FileInputStream("path/of/text"));

Install pdo for postgres Ubuntu

If you're using the wonderful ondrej/php ubuntu repository with php7.0:

sudo apt-get install php7.0-pgsql

For ondrej/php Ubuntu repository with php7.1:

sudo apt-get install php7.1-pgsql

Same repository, but for php5.6:

sudo apt-get install php5.6-pgsql

Concise and easy to remember. I love this repository.

Download all stock symbol list of a market

This may be old, but... if you change the link in google stock list as below:

https://www.google.com/finance?q=%5B(exchange%20%3D%3D%20%22NASDAQ%22)%5D&restype=company&noIL=1&num=30000

  • note for the noIL=1&num=30000

It means, starting for row 1 to 30000. It shows all results in one page.

You may automate it using any language or just export the table to excel.

Hope it helps.

Check if a row exists using old mysql_* API

This ought to do the trick: just limit the result to 1 row; if a row comes back the $lectureName is Assigned, otherwise it's Available.

function checkLectureStatus($lectureName)
{
    $con = connectvar();
    mysql_select_db("mydatabase", $con);
    $result = mysql_query(
        "SELECT * FROM preditors_assigned WHERE lecture_name='$lectureName' LIMIT 1");

    if(mysql_fetch_array($result) !== false)
        return 'Assigned';
    return 'Available';
}

How to delete a cookie?

Some of the other solutions might not work if you created the cookie manually.

Here's a quick way to delete a cookie:

document.cookie = 'COOKIE_NAME=; Max-Age=0; path=/; domain=' + location.host;

Get the Year/Month/Day from a datetime in php?

Check out the manual: http://www.php.net/manual/en/datetime.format.php

<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>

Will output: 2000-01-01 00:00:00

Fatal Error :1:1: Content is not allowed in prolog

Someone should mark Johannes Weiß's comment as the answer to this question. That is exactly why xml documents can't just be loaded in a DOM Document class.

http://en.wikipedia.org/wiki/Byte_order_mark

How to grant remote access to MySQL for a whole subnet?

MySQL 8.0.23 onwards now support CIDR notation also.

So, basically:

-- CIDR Notation
GRANT ... TO 'user'@'192.168.1.0/24' IDENTIFIED BY ...

-- Netmask Notation
GRANT ... TO 'user'@'192.168.1.0/255.255.255.0' IDENTIFIED BY ...

Failed to load c++ bson extension

A common problem is that node-gyp requires Python 2.x and if your system's python points to 3.x, it will fail to compile bson, without warning. You can fix this by setting a python global key in your npm config that points to the 2.x executable on your system. For example, on Arch Linux:

npm config -g set python "/usr/bin/python2"

lambda expression join multiple tables with select and where clause

If I understand your questions correctly, all you need to do is add the .Where(m => m.r.u.UserId == 1):

    var UserInRole = db.UserProfiles.
        Join(db.UsersInRoles, u => u.UserId, uir => uir.UserId,
        (u, uir) => new { u, uir }).
        Join(db.Roles, r => r.uir.RoleId, ro => ro.RoleId, (r, ro) => new { r, ro })
        .Where(m => m.r.u.UserId == 1)
        .Select (m => new AddUserToRole
        {
            UserName = m.r.u.UserName,
            RoleName = m.ro.RoleName
        });

Hope that helps.

Export MySQL database using PHP only

Try the following.

Execute a database backup query from PHP file. Below is an example of using SELECT INTO OUTFILE query for creating table backup:

<?php
$DB_HOST = "localhost";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$DB_NAME = "xxx";

$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
  die('Connection failed [' . $con->connect_error . ']');
}

$tableName  = 'yourtable';
$backupFile = 'backup/yourtable.sql';
$query      = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName";
$result = mysqli_query($con,$query);
?>

To restore the backup you just need to run LOAD DATA INFILE query like this:

<?php
$DB_HOST = "localhost";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$DB_NAME = "xxx";

$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
  die('Connection failed [' . $con->connect_error . ']');
}

$tableName  = 'yourtable';
$backupFile = 'yourtable.sql';
$query      = "LOAD DATA INFILE 'backupFile' INTO TABLE $tableName";
$result = mysqli_query($con,$query);
?>

EXCEL VBA Check if entry is empty or not 'space'

Here is the code to check whether value is present or not.

If Trim(textbox1.text) <> "" Then
     'Your code goes here
Else
     'Nothing
End If

I think this will help.

Limiting Powershell Get-ChildItem by File Creation Date Range

Fixed it...

Get-ChildItem C:\Windows\ -recurse -include @("*.txt*","*.pdf") |
Where-Object {$_.CreationTime -gt "01/01/2013" -and $_.CreationTime -lt "12/02/2014"} | 
Select-Object FullName, CreationTime, @{Name="Mbytes";Expression={$_.Length/1Kb}}, @{Name="Age";Expression={(((Get-Date) - $_.CreationTime).Days)}} | 
Export-Csv C:\search_TXT-and-PDF_files_01012013-to-12022014_sort.txt

Render partial from different folder (not shared)

If you are using this other path a lot of the time you can fix this permanently without having to specify the path all of the time. By default, it is checking for partial views in the View folder and in the Shared folder. But say you want to add one.

Add a class to your Models folder:

public class NewViewEngine : RazorViewEngine {

   private static readonly string[] NEW_PARTIAL_VIEW_FORMATS = new[] {
      "~/Views/Foo/{0}.cshtml",
      "~/Views/Shared/Bar/{0}.cshtml"
   };

   public NewViewEngine() {
      // Keep existing locations in sync
      base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(NEW_PARTIAL_VIEW_FORMATS).ToArray();
   }
}

Then in your Global.asax.cs file, add the following line:

ViewEngines.Engines.Add(new NewViewEngine());

How do I make my string comparison case insensitive?

In the default Java API you have:

String.CASE_INSENSITIVE_ORDER

So you do not need to rewrite a comparator if you were to use strings with Sorted data structures.

String s = "some text here";
s.equalsIgnoreCase("Some text here");

Is what you want for pure equality checks in your own code.

Just to further informations about anything pertaining to equality of Strings in Java. The hashCode() function of the java.lang.String class "is case sensitive":

public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}

So if you want to use an Hashtable/HashMap with Strings as keys, and have keys like "SomeKey", "SOMEKEY" and "somekey" be seen as equal, then you will have to wrap your string in another class (you cannot extend String since it is a final class). For example :

private static class HashWrap {
    private final String value;
    private final int hash;

    public String get() {
        return value;
    }

    private HashWrap(String value) {
        this.value = value;
        String lc = value.toLowerCase();
        this.hash = lc.hashCode();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o instanceof HashWrap) {
            HashWrap that = (HashWrap) o;
            return value.equalsIgnoreCase(that.value);
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return this.hash;
    }
}

and then use it as such:

HashMap<HashWrap, Object> map = new HashMap<HashWrap, Object>();

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

I take no credit for this answer, as it's merely a combination of the best two answers above: that of X. Wo Satuk and that of Sébastien Helbert: ThresholdFilter is lovely but you can't configure it to have an upper level as well as a lower level*, but combining it with two LevelFilters set to "DENY" WARN and ERROR works a treat.

Very important: do not forget the <target>System.err</target> tag in the STDERR appender: my omission of it had me frustrated for a few minutes.

<configuration>
    <timestamp key="byDay" datePattern="yyyyMMdd'T'HHmmss" />
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>WARN</level>
            <onMatch>DENY</onMatch>
        </filter>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>DENY</onMatch>
        </filter>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\)
                - %msg%n
            </pattern>
        </encoder>
    </appender>

    <appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>WARN</level>
        </filter>
        <target>System.err</target>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\)
                - %msg%n
            </pattern>
        </encoder>
    </appender>

    <root level="debug">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="STDERR" />
    </root>
</configuration>

* it does however have a method decide in the API but I haven't a clue how you'd use it in this context.

Printing chars and their ASCII-code in C

#include<stdio.h>
 void main()
{
char a;
scanf("%c",&a);
printf("%d",a);
}

Warning: push.default is unset; its implicit value is changing in Git 2.0

It's explained in great detail in the docs, but I'll try to summarize:

  • matching means git push will push all your local branches to the ones with the same name on the remote. This makes it easy to accidentally push a branch you didn't intend to.

  • simple means git push will push only the current branch to the one that git pull would pull from, and also checks that their names match. This is a more intuitive behavior, which is why the default is getting changed to this.

This setting only affects the behavior of your local client, and can be overridden by explicitly specifying which branches you want to push on the command line. Other clients can have different settings, it only affects what happens when you don't specify which branches you want to push.

Get all dates between two dates in SQL Server

I listed dates of 2 Weeks later. You can use variable @period OR function datediff(dd, @date_start, @date_end)

declare @period INT, @date_start datetime, @date_end datetime, @i int;

set @period = 14
set @date_start = convert(date,DATEADD(D, -@period, curent_timestamp))
set @date_end = convert(date,current_timestamp)
set @i = 1

create table #datesList(dts datetime)
insert into #datesList values (@date_start)
while @i <= @period
    Begin
        insert into #datesList values (dateadd(d,@i,@date_start))
        set @i = @i + 1
    end
select cast(dts as DATE) from #datesList
Drop Table #datesList

Display List in a View MVC

Your action method considers model type asList<string>. But, in your view you are waiting for IEnumerable<Standings.Models.Teams>. You can solve this problem with changing the model in your view to List<string>.

But, the best approach would be to return IEnumerable<Standings.Models.Teams> as a model from your action method. Then you haven't to change model type in your view.

But, in my opinion your models are not correctly implemented. I suggest you to change it as:

public class Team
{
    public int Position { get; set; }
    public string HomeGround {get; set;}
    public string NickName {get; set;}
    public int Founded { get; set; }
    public string Name { get; set; }
}

Then you must change your action method as:

public ActionResult Index()
{
    var model = new List<Team>();

    model.Add(new Team { Name = "MU"});
    model.Add(new Team { Name = "Chelsea"});
    ...

    return View(model);
}

And, your view:

@model IEnumerable<Standings.Models.Team>

@{
     ViewBag.Title = "Standings";
}

@foreach (var item in Model)
{
    <div>
        @item.Name
        <hr />
    </div>
}

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

I recommend using the combination of

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

How to disable JavaScript in Chrome Developer Tools?

Official documentation: Disable JavaScript With Chrome DevTools

There's now a command menu built into DevTools that makes it easier to disable JavaScript. This has been around as of April 2016 or so.

  1. Open DevTools.
  2. Press Command+Shift+P (Mac) or Control+Shift+P (Windows, Linux) to open the Command Menu. Make sure that your cursor's focus is on the DevTools window, not your browser viewport.
  3. Type Disable JavaScript (or some version of that... it's a fuzzy search) and then press Enter.

Use the Enable JavaScript command when you want to turn it back on.

disabling js via command menu

How to send password securely over HTTP?

If your webhost allows it, or you will need to deal with sensitive data, then use HTTPS, period. (It's often required by the law afaik).

Otherwise if you want to do something over HTTP. I would do something like this.

  1. The server embeds its public key into the login page.
  2. The client populates the login form and clicks submit.
  3. An AJAX request gets the current timestamp from the server.
  4. Client side script concatenates the credentials, the timestamp and a salt (hashed from analog data eg. mouse movements, key press events), encrypts it using the public key.
  5. Submits the resulting hash.
  6. Server decrypts the hash
  7. Checks if the timestamp is recent enough (allows a short 5-10 second window only). Rejects the login if the timestamp is too old.
  8. Stores the hash for 20 seconds. Rejects the same hash for login during this interval.
  9. Authenticates the user.

So this way the password is protected and the same authentication hash cannot be replayed.

About the security of the session token. That's a bit harder. But it's possible to make reusing a stolen session token a bit harder.

  1. The server sets an extra session cookie which contains a random string.
  2. The browser sends back this cookie on the next request.
  3. The server checks the value in the cookie, if it's different then it destroys the session, otherwise all is okay.
  4. The server sets the cookie again with different text.

So if the session token got stolen, and a request is sent up by someone else, then on the original user's next request the session will be destroyed. So if the user actively browsing the site, clicking on links often, then the thief won't go far with the stolen token. This scheme can be fortified by requiring another authentication for the sensitive operations (like account deletion).

EDIT: Please note this doesn't prevent MITM attacks if the attacker sets up their own page with a different public key and proxies requests to the server. To protect against this the public key must be pinned in the browser's local storage or within the app to detect these kind of tricks.

About the implementation: RSA is probably to most known algorithm, but it's quite slow for long keys. I don't know how fast a PHP or Javascript implementation of would be. But probably there are a faster algorithms.

Populate unique values into a VBA array from Excel

The old school method was my favourite option. Thank you. And it was indeed fast. But I didn't use redim. Here though is my real world example where I accumulate values for each unique "key" found in a column and move it into a array (say for an employee and values are hours worked per day). Then I put each key with its final values into a totals area on the active sheet. I've commented extensively for anyone who wants painful detail on what is happening here. Limited error checking is done by this code.

Sub GetActualTotals()
'
' GetActualTotals Macro
'
' This macro accumulates values for each unique employee from the active
' spreadsheet.
'
' History
' October 2016 - Version 1
'
' Invocation
' I created a button labeled "Get Totals" on the Active Sheet that invokes
' this macro.
'
Dim ResourceName As String
Dim TotalHours As Double
Dim TotalPercent As Double
Dim IsUnique As Boolean
Dim FirstRow, LastRow, LastColumn, LastResource, nUnique As Long
Dim CurResource, CurrentRow, i, j As Integer
Dim Resource(1000, 2) As Variant
Dim Rng, r As Range
'
' INITIALIZATIONS
'
' These are index numbers for the Resource array
'
Const RName = 0
Const TotHours = 1
Const TotPercent = 2
'
' Set the maximum number of resources we'll
' process.
'
Const ResourceLimit = 1000
'
' We are counting on there being no unintended data
' in the spreadsheet.
'
' It won't matter if the cells are empty though. It just
' may take longer to run the macro.
' But if there is data where this macro does not expect it,
' assume unpredictable results.
'
' There are some hardcoded values used.
' This macro just happens to expect the names to be in Column C (or 3).
'
' Get the last row in the spreadsheet:
'
LastRow = Cells.Find(What:="*", _
                After:=Range("C1"), _
                LookAt:=xlPart, _
                LookIn:=xlFormulas, _
                SearchOrder:=xlByRows, _
                SearchDirection:=xlPrevious, _
                MatchCase:=False).Row
'
'  Furthermore, this macro banks on the first actual name to be in C6.
'  so if the last row is row 65, the range we'll work with 
'  will evaluate to "C6:C65"
'
FirstRow = 6
Rng = "C" & FirstRow & ":C" & LastRow
Set r = Range(Rng)
'
' Initialize the resource array to be empty (even though we don't really
' need to but I'm old school).  
'
For CurResource = 0 To ResourceLimit
    Resource(CurResource, RName) = ""
    Resource(CurResource, TotHours) = 0
    Resource(CurResource, TotPercent) = 0
Next CurResource
'
' Start the resource counter at 0.  The counter will represent the number of
' unique entries. 
'
 nUnique = 0
'
' LET'S GO
'
' Loop from the first relative row and the last relative row
' to process all the cells in the spreadsheet we are interested in
'
For i = 1 To LastRow - FirstRow
'
' Loop here for all unique entries. For any
' new unique entry, that array element will be
' initialized in the second if statement.
'
    IsUnique = True
    For j = 1 To nUnique
'
' If the current row element has a resource name and is already
' in the resource array, then accumulate the totals for that
' Resource Name. We then have to set IsUnique to false and
' exit the for loop to make sure we don't populate
' a new array element in the next if statement.
'
        If r.Cells(i, 1).Value = Resource(j, RName) Then
            IsUnique = False
            Resource(j, TotHours) = Resource(j, TotHours) + _
            r.Cells(i, 4).Value
            Resource(j, TotPercent) = Resource(j, TotPercent) + _
            r.Cells(i,5).Value
            Exit For
        End If
     Next j
'
' If the resource name is unique then copy the initial
' values we find into the next resource array element.
' I ignore any null cells.   (If the cell has a blank you might
' want to add a Trim to the cell).   Not much error checking for 
' the numerical values either.
'
    If ((IsUnique) And (r.Cells(i, 1).Value <> "")) Then
        nUnique = nUnique + 1
        Resource(nUnique, RName) = r.Cells(i, 1).Value
        Resource(nUnique, TotHours) = Resource(nUnique, TotHours) + _ 
        r.Cells(i, 4).Value
        Resource(nUnique, TotPercent) = Resource(nUnique, TotPercent) + _
        r.Cells(i, 5).Value
    End If                  
Next i
'
' Done processing all rows
'
' (For readability) Set the last resource counter to the last value of
' nUnique.
' Set the current row to the first relative row in the range (r=the range).
'
LastResource = nUnique
CurrentRow = 1
'
' Populate the destination cells with the accumulated values for
' each unique resource name.
'
For CurResource = 1 To LastResource
    r.Cells(CurrentRow, 7).Value = Resource(CurResource, RName)
    r.Cells(CurrentRow, 8).Value = Resource(CurResource, TotHours)
    r.Cells(CurrentRow, 9).Value = Resource(CurResource, TotPercent)
    CurrentRow = CurrentRow + 1
Next CurResource

End Sub

How to implement linear interpolation?

Instead of extrapolating off the ends, you could return the extents of the y_list. Most of the time your application is well behaved, and the Interpolate[x] will be in the x_list. The (presumably) linear affects of extrapolating off the ends may mislead you to believe that your data is well behaved.

  • Returning a non-linear result (bounded by the contents of x_list and y_list) your program's behavior may alert you to an issue for values greatly outside x_list. (Linear behavior goes bananas when given non-linear inputs!)

  • Returning the extents of the y_list for Interpolate[x] outside of x_list also means you know the range of your output value. If you extrapolate based on x much, much less than x_list[0] or x much, much greater than x_list[-1], your return result could be outside of the range of values you expected.

    def __getitem__(self, x):
        if x <= self.x_list[0]:
            return self.y_list[0]
        elif x >= self.x_list[-1]:
            return self.y_list[-1]
        else:
            i = bisect_left(self.x_list, x) - 1
            return self.y_list[i] + self.slopes[i] * (x - self.x_list[i])
    

Difference between natural join and inner join

Natural Join: It is combination or combined result of all the columns in the two tables. It will return all rows of the first table with respect to the second table.

Inner Join: This join will work unless if any of the column name shall be sxame in two tables

ASP.NET Bundles how to disable minification

If you set the following property to false then it will disable both bundling and minification.

In Global.asax.cs file, add the line as mentioned below

protected void Application_Start()
{
    System.Web.Optimization.BundleTable.EnableOptimizations = false;
}

How to make <label> and <input> appear on the same line on an HTML form?

aaa##HTML I would suggest you wrap them in a div, since you will likely end up floating them in certain contexts.

<div class="input-w">
    <label for="your-input">Your label</label>
    <input type="text" id="your-input" />
</div>

CSS

Then within that div, you can make each piece inline-block so that you can use vertical-align to center them - or set baseline etc. (your labels and input might change sizes in the future...

.input-w label, .input-w input {
    float: none; /* if you had floats before? otherwise inline-block will behave differently */
    display: inline-block;
    vertical-align: middle;    
}

jsFiddle

UPDATE: mid 2016 + with mobile-first media queries and flex-box

This is how I do things these days.

HTML

<label class='input-w' for='this-input-name'>
  <span class='label'>Your label</span>
  <input class='input' type='text' id='this-input-name' placeholder='hello'>
</label>

<label class='input-w' for='this-other-input-name'>
  <span class='label'>Your label</span>
  <input class='input' type='text' id='this-other-input-name' placeholder='again'>
</label>

SCSS

html { // https://www.paulirish.com/2012/box-sizing-border-box-ftw/
  box-sizing: border-box;
  *, *:before, *:after {
    box-sizing: inherit;
  }
} // if you don't already reset your box-model, read about it

.input-w {
  display: block;
  width: 100%; // should be contained by a form or something
  margin-bottom: 1rem;
  @media (min-width: 500px) {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
  .label, .input {
    display: block;
    width: 100%;
    border: 1px solid rgba(0,0,0,.1);
    @media (min-width: 500px) {
      width: auto;
      display: flex;
    }
  }
  .label {
    font-size: 13px;
    @media (min-width: 500px) {
      /* margin-right: 1rem; */
      min-width: 100px; // maybe to match many?
    }
  }
  .input {
    padding: .5rem;
    font-size: 16px;
    @media (min-width: 500px) {
      flex-grow: 1;
      max-width: 450px; // arbitrary
    }
  }
}

jsFiddle

How to run an external program, e.g. notepad, using hyperlink?

I've wrote a small extension to do so.

Since you are creating the page using C# you may want to implement this:

https://github.com/felix-d-git/DesktopAppLink

Basically u are creating some registry entries to parse the links you click in your html page.

The browser will then ask to open the specified app.

C#:

DesktopAppLink.CreateLink("applink.sample", "\"<path to exe>\"", "");

HTML:

<a href="applink.sample:">Run Desktop App</a>

Result:

enter image description here

How to use GROUP BY to concatenate strings in SQL Server?

Another option using Sql Server 2005 and above

---- test data
declare @t table (OUTPUTID int, SCHME varchar(10), DESCR varchar(10))
insert @t select 1125439       ,'CKT','Approved'
insert @t select 1125439       ,'RENO','Approved'
insert @t select 1134691       ,'CKT','Approved'
insert @t select 1134691       ,'RENO','Approved'
insert @t select 1134691       ,'pn','Approved'

---- actual query
;with cte(outputid,combined,rn)
as
(
  select outputid, SCHME + ' ('+DESCR+')', rn=ROW_NUMBER() over (PARTITION by outputid order by schme, descr)
  from @t
)
,cte2(outputid,finalstatus,rn)
as
(
select OUTPUTID, convert(varchar(max),combined), 1 from cte where rn=1
union all
select cte2.outputid, convert(varchar(max),cte2.finalstatus+', '+cte.combined), cte2.rn+1
from cte2
inner join cte on cte.OUTPUTID = cte2.outputid and cte.rn=cte2.rn+1
)
select outputid, MAX(finalstatus) from cte2 group by outputid

REST API Token-based Authentication

A pure RESTful API should use the underlying protocol standard features:

  1. For HTTP, the RESTful API should comply with existing HTTP standard headers. Adding a new HTTP header violates the REST principles. Do not re-invent the wheel, use all the standard features in HTTP/1.1 standards - including status response codes, headers, and so on. RESTFul web services should leverage and rely upon the HTTP standards.

  2. RESTful services MUST be STATELESS. Any tricks, such as token based authentication that attempts to remember the state of previous REST requests on the server violates the REST principles. Again, this is a MUST; that is, if you web server saves any request/response context related information on the server in attempt to establish any sort of session on the server, then your web service is NOT Stateless. And if it is NOT stateless it is NOT RESTFul.

Bottom-line: For authentication/authorization purposes you should use HTTP standard authorization header. That is, you should add the HTTP authorization / authentication header in each subsequent request that needs to be authenticated. The REST API should follow the HTTP Authentication Scheme standards.The specifics of how this header should be formatted are defined in the RFC 2616 HTTP 1.1 standards – section 14.8 Authorization of RFC 2616, and in the RFC 2617 HTTP Authentication: Basic and Digest Access Authentication.

I have developed a RESTful service for the Cisco Prime Performance Manager application. Search Google for the REST API document that I wrote for that application for more details about RESTFul API compliance here. In that implementation, I have chosen to use HTTP "Basic" Authorization scheme. - check out version 1.5 or above of that REST API document, and search for authorization in the document.

What is an MvcHtmlString and when should I use it?

You would use an MvcHtmlString if you want to pass raw HTML to an MVC helper method and you don't want the helper method to encode the HTML.

How to make a HTML list appear horizontally instead of vertically using CSS only?

Using display: inline-flex

_x000D_
_x000D_
#menu ul {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  display: inline-flex_x000D_
}
_x000D_
<div id="menu">_x000D_
  <ul>_x000D_
    <li>1 menu item</li>_x000D_
    <li>2 menu item</li>_x000D_
    <li>3 menu item</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using display: inline-block

_x000D_
_x000D_
#menu ul {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
#menu li {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div id="menu">_x000D_
  <ul>_x000D_
    <li>1 menu item</li>_x000D_
    <li>2 menu item</li>_x000D_
    <li>3 menu item</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Creating a copy of an object in C#

There's already a question about this, you could perhaps read it

Deep cloning objects

There's no Clone() method as it exists in Java for example, but you could include a copy constructor in your clases, that's another good approach.

class A
{
  private int attr

  public int Attr
  {
     get { return attr; }
     set { attr = value }
  }

  public A()
  {
  }

  public A(A p)
  {
     this.attr = p.Attr;
  }  
}

This would be an example, copying the member 'Attr' when building the new object.

How to check if a file is empty in Bash?

While the other answers are correct, using the "-s" option will also show the file is empty even if the file does not exist.
By adding this additional check "-f" to see if the file exists first, we ensure the result is correct.

if [ -f diff.txt ]
then
  if [ -s diff.txt ]
  then
    rm -f empty.txt
    touch full.txt
  else
    rm -f full.txt
    touch empty.txt
  fi
else
  echo "File diff.txt does not exist"
fi

getting the X/Y coordinates of a mouse click on an image with jQuery

Here is a better script:

$('#mainimage').click(function(e)
{   
    var offset_t = $(this).offset().top - $(window).scrollTop();
    var offset_l = $(this).offset().left - $(window).scrollLeft();

    var left = Math.round( (e.clientX - offset_l) );
    var top = Math.round( (e.clientY - offset_t) );

    alert("Left: " + left + " Top: " + top);

});

HTML img align="middle" doesn't align an image

remove float: left from image css and add text-align: center property in parent element body

_x000D_
_x000D_
        <!DOCTYPE html>_x000D_
<html>_x000D_
<body style="text-align: center;">_x000D_
_x000D_
    <img_x000D_
        src="http://icons.iconarchive.com/icons/rokey/popo-emotions/128/big-smile-icon.png"_x000D_
        width="42" height="42"_x000D_
        align="middle"_x000D_
        style="_x000D_
          _x000D_
          display: block;_x000D_
          margin-left: auto;_x000D_
          margin-right: auto;_x000D_
          z-index: 1;"_x000D_
        >_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Echo tab characters in bash script

Put your string between double quotes:

echo "[$res]"

Default visibility for C# classes and members (fields, methods, etc.)?

By default, the access modifier for a class is internal. That means to say, a class is accessible within the same assembly. But if we want the class to be accessed from other assemblies then it has to be made public.

oracle sql: update if exists else insert

merge into MY_TABLE tgt
using (select [expressions]
         from dual ) src
   on (src.key_condition = tgt.key_condition)
when matched then 
     update tgt
        set tgt.column1 = src.column1 [,...]
when not matched then 
     insert into tgt
        ([list of columns])
     values
        (src.column1 [,...]);

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

How to make a website secured with https

Try making a boot directory in PHP, as in

<?PHP
$ip = $_SERVER['REMOTE_ADDR'];
$privacy = ['BOOTSTRAP_CONFIG'];
$shell   = ['BOOTSTRAP_OUTPUT'];
enter code here
if $ip == $privacy {
function $privacy int $ip = "https://";
} endif {
echo $shell
}
?>

Thats mainly it!

Printing long int value in C

You must use %ld to print a long int, and %lld to print a long long int.

Note that only long long int is guaranteed to be large enough to store the result of that calculation (or, indeed, the input values you're using).

You will also need to ensure that you use your compiler in a C99-compatible mode (for example, using the -std=gnu99 option to gcc). This is because the long long int type was not introduced until C99; and although many compilers implement long long int in C90 mode as an extension, the constant 2147483648 may have a type of unsigned int or unsigned long in C90. If this is the case in your implementation, then the value of -2147483648 will also have unsigned type and will therefore be positive, and the overall result will be not what you expect.

How to Logout of an Application Where I Used OAuth2 To Login With Google?

For me, it works (java - android)

void RevokeAcess()
{
    try{
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/revoke?token="+ACCESS_TOKEN);
    org.apache.http.HttpResponse response = client.execute(post);
    }
    catch(IOException e)
    {
    }
    CookieManager.getInstance().removeAllCookie(); // this is clear the cookies which tends to same user in android web view
}

You have to call this function in AsyncTask in android

Disabling radio buttons with jQuery

I just built a sandbox environment with your code and it worked for me. Here is what I used:

<html>
  <head>
    <title>test</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  </head>
  <body>
    <form id="chatTickets" method="post" action="/admin/index.cfm/">
      <input id="ticketID1" type="radio" checked="checked" value="myvalue1" name="ticketID"/>
      <input id="ticketID2" type="radio" checked="checked" value="myvalue2" name="ticketID"/>
    </form>
    <a href="#" title="Load ActiveChat" id="loadActive">Load Active</a>

    <script>
      jQuery("#loadActive").click(function() {
        //I have other code in here that runs before this function call
        writeData();
      });
      function writeData() {
        jQuery("input[name='ticketID']").each(function(i) {
            jQuery(this).attr('disabled', 'disabled');
        });
      }
    </script>
  </body>
</html>

I tested in FF3.5, moving to IE8 now. And it works fine in IE8 too. What browser are you using?

Tracking the script execution time in PHP

Just to contribute to this conversation:

  • what happens if the measurement targets two points A and B in different php files?

  • what if we need different measurements like time based, code execution duration, external resource access duration?

  • what if we need to organize our measurements in categories where every one has a different starting point?

As you suspect we need some global variables to be accessed by a class object or a static method: I choose the 2nd approach and here it is:

namespace g3;

class Utils {
   public function __construct() {}

   public static $UtilsDtStart = [];
   public static $UtilsDtStats = [];

   public static function dt() {
      global $UtilsDtStart, $UtilsDtStats;
      $obj = new \stdClass();
      $obj->start = function(int $ndx = 0) use (&$UtilsDtStart) {
         $UtilsDtStart[$ndx] = \microtime(true) * 1000;
      };
      $obj->codeStart = function(int $ndx = 0) use (&$UtilsDtStart) {
         $use = \getrusage();
         $UtilsDtStart[$ndx] = ($use["ru_utime.tv_sec"] * 1000) + ($use["ru_utime.tv_usec"] / 1000);
      };
      $obj->resourceStart = function(int $ndx = 0) use (&$UtilsDtStart) {
         $use = \getrusage();
         $UtilsDtStart[$ndx] = $use["ru_stime.tv_usec"] / 1000;
      };
      $obj->end = function(int $ndx = 0) use (&$UtilsDtStart, &$UtilsDtStats) {
         $t = @$UtilsDtStart[$ndx];
         if($t === null)
            return false;
         $end = \microtime(true) * 1000;
         $dt = $end - $t;
         $UtilsDtStats[$ndx][] = $dt;
         return $dt;
      };
      $obj->codeEnd = function(int $ndx = 0) use (&$UtilsDtStart, &$UtilsDtStats) {
         $t = @$UtilsDtStart[$ndx];
         if($t === null)
            return false;
         $use = \getrusage();
         $dt = ($use["ru_utime.tv_sec"] * 1000) + ($use["ru_utime.tv_usec"] / 1000) - $t;
         $UtilsDtStats[$ndx][] = $dt;
         return $dt;
      };
      $obj->resourceEnd = function(int $ndx = 0) use (&$UtilsDtStart, &$UtilsDtStats) {
         $t = @$UtilsDtStart[$ndx];
         if($t === null)
            return false;
         $use = \getrusage();
         $dt = ($use["ru_stime.tv_usec"] / 1000) - $t;
         $UtilsDtStats[$ndx][] = $dt;
         return $dt;
      };
      $obj->stats = function(int $ndx = 0) use (&$UtilsDtStats) {
         $s = @$UtilsDtStats[$ndx];
         if($s !== null)
            $s = \array_slice($s, 0);
         else
            $s = false;
         return $s;
      };
      $obj->statsLength = function() use (&$UtilsDtStats) {
         return \count($UtilsDtStats);
      };
      return $obj;
   }
}

Now all you have is to call the method that belongs to the specific category with the index that denotes it's unique group:

File A
------
\call_user_func_array(\g3\Utils::dt()->start, [0]);   // point A
...
File B
------
$dt = \call_user_func_array(\g3\Utils::dt()->end, [0]);  // point B

Value $dt contains the milliseconds of wall clock duration between points A and B.

To estimate the time took for php code to run:

File A
------
\call_user_func_array(\g3\Utils::dt()->codeStart, [1]);   // point A
...
File B
------
$dt = \call_user_func_array(\g3\Utils::dt()->codeEnd, [1]);  // point B

Notice how we changed the index that we pass at the methods.

The code is based on the closure effect that happens when we return an object/function from a function (see that \g3\Utils::dt() repeated at the examples).

I tested with php unit and between different test methods at the same test file it behaves fine so far!

Hope that helps someone!

Chrome/jQuery Uncaught RangeError: Maximum call stack size exceeded

You can also get this error when you have an infinite loop. Make sure that you don't have any unending, recursive self references.

sql query to find the duplicate records

select distinct title, (
               select count(title) 
               from kmovies as sub 
               where sub.title=kmovies.title) as cnt 
from kmovies 
group by title 
order by cnt desc

How to get a random number in Ruby

range = 10..50

rand(range)

or

range.to_a.sample

or

range.to_a.shuffle(this will shuffle whole array and you can pick a random number by first or last or any from this array to pick random one)

How to prevent page scrolling when scrolling a DIV element?

Here is my solution I've used in applications.

I disabled the body overflow and placed the entire website html inside container div's. The website containers have overflow and therefore the user may scroll the page as expected.

I then created a sibling div (#Prevent) with a higher z-index that covers the entire website. Since #Prevent has a higher z-index, it overlaps the website container. When #Prevent is visible the mouse is no longer hovering the website containers, so scrolling isn't possible.

You may of course place another div, such as your modal, with a higher z-index than #Prevent in the markup. This allows you to create pop-up windows that don't suffer from scrolling issues.

This solution is better because it doesn't hide the scrollbars (jumping affect). It doesn't require event listeners and it's easy to implement. It works in all browsers, although with IE7 & 8 you have to play around (depends on your specific code).

html

<body>
  <div id="YourModal" style="display:none;"></div>
  <div id="Prevent" style="display:none;"></div>
  <div id="WebsiteContainer">
     <div id="Website">
     website goes here...
     </div>
  </div>
</body>

css

body { overflow: hidden; }

#YourModal {
 z-index:200;
 /* modal styles here */
}

#Prevent {
 z-index:100;
 position:absolute;
 left:0px;
 height:100%;
 width:100%;
 background:transparent;
}

#WebsiteContainer {
  z-index:50;
  overflow:auto;
  position: absolute;
  height:100%;
  width:100%;
}
#Website {
  position:relative;
}

jquery/js

function PreventScroll(A) { 
  switch (A) {
    case 'on': $('#Prevent').show(); break;
    case 'off': $('#Prevent').hide(); break;
  }
}

disable/enable the scroll

PreventScroll('on'); // prevent scrolling
PreventScroll('off'); // allow scrolling

Chrome DevTools Devices does not detect device when plugged in

Samsung phone + PC with Windows

First of all you need to turn on USB debugging on your phone:

  1. Settings / About phone / Software information / Build number (tap it 7 times to turn on developer mode)
  2. Settings / Developer options / USB debugging (turn it on)

Then on your PC:

  1. Install Samsung USB driver https://developer.samsung.com/mobile/android-usb-driver.html
  2. Install ADB https://forum.xda-developers.com/showthread.php?t=2317790 (in the forum scroll down to the section "Downloads" to get the newest version of ADB)
  3. After ADB installation CMD should pop up -> start ADB with command "adb devices" (for example "C:\Program Files (x86)\Minimal ADB and Fastboot> adb devices")
  4. Connect your phone to your PC with USB cable
  5. Alert about the connection should pop up on your phone (allow it)
  6. In Chrome on your PC open Developer tools / More tools / Remote devices and you should finally see your phone being detected

How to get a path to the desktop for current user in C#?

// Environment.GetFolderPath
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // Current User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); // All User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles); // Program Files
Environment.GetFolderPath(Environment.SpecialFolder.Cookies); // Internet Cookie
Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Logical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); // Physical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.Favorites); // Favorites
Environment.GetFolderPath(Environment.SpecialFolder.History); // Internet History
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache); // Internet Cache
Environment.GetFolderPath(Environment.SpecialFolder.MyComputer); // "My Computer" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // "My Documents" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic); // "My Music" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); // "My Pictures" Folder
Environment.GetFolderPath(Environment.SpecialFolder.Personal); // "My Document" Folder
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); // Program files Folder
Environment.GetFolderPath(Environment.SpecialFolder.Programs); // Programs Folder
Environment.GetFolderPath(Environment.SpecialFolder.Recent); // Recent Folder
Environment.GetFolderPath(Environment.SpecialFolder.SendTo); // "Sent to" Folder
Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); // Start Menu
Environment.GetFolderPath(Environment.SpecialFolder.Startup); // Startup
Environment.GetFolderPath(Environment.SpecialFolder.System); // System Folder
Environment.GetFolderPath(Environment.SpecialFolder.Templates); // Document Templates

Can't perform a React state update on an unmounted component

I know that you're not using history, but in my case I was using the useHistory hook from React Router DOM, which unmounts the component before the state is persisted in my React Context Provider.

To fix this problem I have used the hook withRouter nesting the component, in my case export default withRouter(Login), and inside the component const Login = props => { ...; props.history.push("/dashboard"); .... I have also removed the other props.history.push from the component, e.g, if(authorization.token) return props.history.push('/dashboard') because this causes a loop, because the authorization state.

An alternative to push a new item to history.

Python: how can I check whether an object is of type datetime.date?

right way is

import datetime
isinstance(x, datetime.date)

When I try this on my machine it works fine. You need to look into why datetime.date is not a class. Are you perhaps masking it with something else? or not referencing it correctly for your import?

Maven plugins can not be found in IntelliJ

Tried invalidating cache, reimporting the project, removing .m2 folder partially and as a whole, and switching to the Idea bundled Maven. Nothing worked, and I've finally broken Maven completely: when it would build the project in the console, now it stopped. Had to reinstall Maven, and it helped!

What EXACTLY is meant by "de-referencing a NULL pointer"?

A NULL pointer points to memory that doesn't exist, and will raise Segmentation fault. There's an easier way to de-reference a NULL pointer, take a look.

int main(int argc, char const *argv[])
{
    *(int *)0 = 0; // Segmentation fault (core dumped)
    return 0;
}

Since 0 is never a valid pointer value, a fault occurs.

SIGSEGV {si_signo=SIGSEGV, si_code=SEGV_MAPERR, si_addr=NULL}

Run Button is Disabled in Android Studio

Just click the dropdown button on left side of RUN button (in your image the dropdown which is in red box) select 'app' option from that and RUN button will be enabled.

Please refer below screenshot.

enter image description here

to call onChange event after pressing Enter key

You can use event.key

_x000D_
_x000D_
function Input({onKeyPress}) {_x000D_
  return (_x000D_
    <div>_x000D_
      <h2>Input</h2>_x000D_
      <input type="text" onKeyPress={onKeyPress}/>_x000D_
    </div>_x000D_
  )_x000D_
}_x000D_
_x000D_
class Form extends React.Component {_x000D_
  state = {value:""}_x000D_
_x000D_
  handleKeyPress = (e) => {_x000D_
    if (e.key === 'Enter') {_x000D_
      this.setState({value:e.target.value})_x000D_
    }_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <section>_x000D_
        <Input onKeyPress={this.handleKeyPress}/>_x000D_
        <br/>_x000D_
        <output>{this.state.value}</output>_x000D_
      </section>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
  <Form />,_x000D_
  document.getElementById("react")_x000D_
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>_x000D_
<div id="react"></div>
_x000D_
_x000D_
_x000D_

What is the easiest way to disable/enable buttons and links (jQuery + Bootstrap)

I know I'm late to the party, but to specifically answer the two questions:

"I just want to disable specific clicky-things so that:

  • They stop clicking
  • They look disabled

How hard can this be?"

They stop clicking

1.  For buttons like <button> or <input type="button"> you add the attribute: disabled.

<button type="submit" disabled>Register</button>
<input type="button" value="Register" disabled>

2.  For links, ANY link... actually, any HTML element, you can use CSS3 pointer events.

.selector { pointer-events:none; }

Browser support for pointer events is awesome by today's state of the art (5/12/14). But we usually have to support legacy browsers in the IE realm, so IE10 and below DO NOT support pointer events: http://caniuse.com/pointer-events. So using one of the JavaScript solutions mentioned by others here may be the way to go for legacy browsers.

More info about pointer events:

They look disabled

Obviously this a CSS answer, so:

1.  For buttons like <button> or <input type="button"> use the [attribute] selector:

button[disabled] { ... }

input[type=button][disabled] { ... }

--

Here's a basic demo with the stuff I mentioned here: http://jsfiddle.net/bXm5B/4/

Hope this helps.

How to dynamically create CSS class in JavaScript and apply?

Using google closure:

you can just use the ccsom module:

goog.require('goog.cssom');
var css_node = goog.cssom.addCssText('.cssClass { color: #F00; }');

The javascript code attempts to be cross browser when putting the css node into the document head.

CSS On hover show another element

It is indeed possible with the following code

 <div href="#" id='a'>
     Hover me
 </div>

<div id='b'>
    Show me
</div>

and css

#a {
  display: block;
}

#a:hover + #b {
  display:block;
}

#b {
  display:none;
  }

Now by hovering on element #a shows element #b.

What is JSONP, and why was it created?

It's actually not too complicated...

Say you're on domain example.com, and you want to make a request to domain example.net. To do so, you need to cross domain boundaries, a no-no in most of browserland.

The one item that bypasses this limitation is <script> tags. When you use a script tag, the domain limitation is ignored, but under normal circumstances, you can't really do anything with the results, the script just gets evaluated.

Enter JSONP. When you make your request to a server that is JSONP enabled, you pass a special parameter that tells the server a little bit about your page. That way, the server is able to nicely wrap up its response in a way that your page can handle.

For example, say the server expects a parameter called callback to enable its JSONP capabilities. Then your request would look like:

http://www.example.net/sample.aspx?callback=mycallback

Without JSONP, this might return some basic JavaScript object, like so:

{ foo: 'bar' }

However, with JSONP, when the server receives the "callback" parameter, it wraps up the result a little differently, returning something like this:

mycallback({ foo: 'bar' });

As you can see, it will now invoke the method you specified. So, in your page, you define the callback function:

mycallback = function(data){
  alert(data.foo);
};

And now, when the script is loaded, it'll be evaluated, and your function will be executed. Voila, cross-domain requests!

It's also worth noting the one major issue with JSONP: you lose a lot of control of the request. For example, there is no "nice" way to get proper failure codes back. As a result, you end up using timers to monitor the request, etc, which is always a bit suspect. The proposition for JSONRequest is a great solution to allowing cross domain scripting, maintaining security, and allowing proper control of the request.

These days (2015), CORS is the recommended approach vs. JSONRequest. JSONP is still useful for older browser support, but given the security implications, unless you have no choice CORS is the better choice.

Using isKindOfClass with Swift

Another approach using the new Swift 2 syntax is to use guard and nest it all in one conditional.

guard let touch = object.AnyObject() as? UITouch, let picker = touch.view as? UIPickerView else {
    return //Do Nothing
}
//Do something with picker

Get everything after the dash in a string in JavaScript

How I would do this:

// function you can use:
function getSecondPart(str) {
    return str.split('-')[1];
}
// use the function:
alert(getSecondPart("sometext-20202"));

C compile error: "Variable-sized object may not be initialized"

This gives error:

int len;
scanf("%d",&len);
char str[len]="";

This also gives error:

int len=5;
char str[len]="";

But this works fine:

int len=5;
char str[len]; //so the problem lies with assignment not declaration

You need to put value in the following way:

str[0]='a';
str[1]='b'; //like that; and not like str="ab";

Unable to copy ~/.ssh/id_rsa.pub

add by user root this command : ssh user_to_acces@hostName -X

user_to_acces = user hostName = hostname machine

How to determine whether code is running in DEBUG / RELEASE build?

Not sure if I answered you question, maybe you could try these code:

#ifdef DEBUG
#define DLOG(xx, ...)  NSLog( \
    @"%s(%d): " \
    xx, __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__ \  
    )
#else
#define DLOG(xx, ...)  ((void)0)
#endif 

read subprocess stdout line by line

The following modification of Rômulo's answer works for me on Python 2 and 3 (2.7.12 and 3.6.1):

import os
import subprocess

process = subprocess.Popen(command, stdout=subprocess.PIPE)
while True:
  line = process.stdout.readline()
  if line != '':
    os.write(1, line)
  else:
    break

How can I declare optional function parameters in JavaScript?

Update

With ES6, this is possible in exactly the manner you have described; a detailed description can be found in the documentation.

Old answer

Default parameters in JavaScript can be implemented in mainly two ways:

function myfunc(a, b)
{
    // use this if you specifically want to know if b was passed
    if (b === undefined) {
        // b was not passed
    }
    // use this if you know that a truthy value comparison will be enough
    if (b) {
        // b was passed and has truthy value
    } else {
        // b was not passed or has falsy value
    }
    // use this to set b to a default value (using truthy comparison)
    b = b || "default value";
}

The expression b || "default value" evaluates the value AND existence of b and returns the value of "default value" if b either doesn't exist or is falsy.

Alternative declaration:

function myfunc(a)
{
    var b;

    // use this to determine whether b was passed or not
    if (arguments.length == 1) {
        // b was not passed
    } else {
        b = arguments[1]; // take second argument
    }
}

The special "array" arguments is available inside the function; it contains all the arguments, starting from index 0 to N - 1 (where N is the number of arguments passed).

This is typically used to support an unknown number of optional parameters (of the same type); however, stating the expected arguments is preferred!

Further considerations

Although undefined is not writable since ES5, some browsers are known to not enforce this. There are two alternatives you could use if you're worried about this:

b === void 0;
typeof b === 'undefined'; // also works for undeclared variables

How to get a shell environment variable in a makefile?

for those who want some official document to confirm the behavior

Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment. (If the ‘-e’ flag is specified, then values from the environment override assignments in the makefile.

https://www.gnu.org/software/make/manual/html_node/Environment.html

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

This is file permission problem. Check disk permissions and repair.

Osx => Cmd+Space => Disk Utilty => Verify Disk Permissions.

Verify completed after Repair Disk Permissions. mysql.server start command is worked succesfuly.

How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

I have written a string extension for replacement of 'String: subString:'

extension String {
    
    func sliceByCharacter(from: Character, to: Character) -> String? {
        let fromIndex = self.index(self.index(of: from)!, offsetBy: 1)
        let toIndex = self.index(self.index(of: to)!, offsetBy: -1)
        return String(self[fromIndex...toIndex])
    }
    
    func sliceByString(from:String, to:String) -> String? {
        //From - startIndex
        var range = self.range(of: from)
        let subString = String(self[range!.upperBound...])
        
        //To - endIndex
        range = subString.range(of: to)
        return String(subString[..<range!.lowerBound])
    }
    
}

Usage : "Date(1511508780012+0530)".sliceByString(from: "(", to: "+")

Example Result : "1511508780012"

PS: Optionals are forced to unwrap. Please add Type safety check wherever necessary.

How can I catch all the exceptions that will be thrown through reading and writing a file?

It is bad practice to catch Exception -- it's just too broad, and you may miss something like a NullPointerException in your own code.

For most file operations, IOException is the root exception. Better to catch that, instead.

Difference Between Select and SelectMany

It's more clear when the query return a string (an array of char):

For example if the list 'Fruits' contains 'apple'

'Select' returns the string:

Fruits.Select(s=>s) 

[0]: "apple"

'SelectMany' flattens the string:

Fruits.SelectMany(s=>s)

[0]: 97  'a'
[1]: 112 'p'
[2]: 112 'p'
[3]: 108 'l'
[4]: 101 'e'

What is difference between monolithic and micro kernel?

1.Monolithic Kernel (Pure Monolithic) :all

  • All Kernel Services From single component

    (-) addition/removal is not possible, less/Zero flexible

    (+) inter Component Communication is better

e.g. :- Traditional Unix

2.Micro Kernel :few

  • few services(Memory management ,CPU management,IPC etc) from core kernel, other services(File management,I/O management. etc.) from different layers/component

  • Split Approach [Some services is in privileged(kernel) mode and some are in Normal(user) mode]

    (+)flexible for changes/up-gradations

    (-)communication overhead

e.g.:- QNX etc.

3.Modular kernel(Modular Monolithic) :most

  • Combination of Micro and Monolithic kernel

  • Collection of Modules -- modules can be --> Static + Dynamic

  • Drivers come in the form of Modules

e.g. :- Linux Modern OS

How do Python functions handle the types of the parameters that you pass in?

To effectively use the typing module (new in Python 3.5) include all (*).

from typing import *

And you will be ready to use:

List, Tuple, Set, Map - for list, tuple, set and map respectively.
Iterable - useful for generators.
Any - when it could be anything.
Union - when it could be anything within a specified set of types, as opposed to Any.
Optional - when it might be None. Shorthand for Union[T, None].
TypeVar - used with generics.
Callable - used primarily for functions, but could be used for other callables.

However, still you can use type names like int, list, dict,...

What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

Instead of explicitly defining the path to the interpreter as in /usr/bin/bash/, by using the env command, the interpreter is searched for and launched from wherever it is first found. This has both upsides and downsides

How do I name the "row names" column in r

It sounds like you want to convert the rownames to a proper column of the data.frame. eg:

# add the rownames as a proper column
myDF <- cbind(Row.Names = rownames(myDF), myDF)
myDF

#           Row.Names id val vr2
# row_one     row_one  A   1  23
# row_two     row_two  A   2  24
# row_three row_three  B   3  25
# row_four   row_four  C   4  26

If you want to then remove the original rownames:

rownames(myDF) <- NULL
myDF
#   Row.Names id val vr2
# 1   row_one  A   1  23
# 2   row_two  A   2  24
# 3 row_three  B   3  25
# 4  row_four  C   4  26


Alternatively, if all of your data is of the same class (ie, all numeric, or all string), you can convert to Matrix and name the dimnames

myMat <- as.matrix(myDF)
names(dimnames(myMat)) <- c("Names.of.Rows", "")
myMat

# Names.of.Rows id  val vr2 
#   row_one   "A" "1" "23"
#   row_two   "A" "2" "24"
#   row_three "B" "3" "25"
#   row_four  "C" "4" "26"

Can jQuery read/write cookies to a browser?

I have managed to write a script allowing the user to choose his/her language, using the cookie script from Klaus Hartl. It took me a few hours work, and I hope I can help others.

How to enable support of CPU virtualization on Macbook Pro?

CPU Virtualization is enabled by default on all MacBooks with compatible CPUs (i7 is compatible). You can try to reset PRAM if you think it was disabled somehow, but I doubt it.

I think the issue might be in the old version of OS. If your MacBook is i7, then you better upgrade OS to something newer.

Using setTimeout to delay timing of jQuery actions

You can also use jQuery's delay() method instead of setTimeout(). It'll give you much more readable code. Here's an example from the docs:

$( "#foo" ).slideUp( 300 ).delay( 800 ).fadeIn( 400 );

The only limitation (that I'm aware of) is that it doesn't give you a way to clear the timeout. If you need to do that then you're better off sticking with all the nested callbacks that setTimeout thrusts upon you.

How to stop/cancel 'git log' command in terminal?

You can hit the key q (for quit) and it should take you to the prompt.

Please see this link.

Normalizing images in OpenCV

If you want to change the range to [0, 1], make sure the output data type is float.

image = cv2.imread("lenacolor512.tiff", cv2.IMREAD_COLOR)  # uint8 image
norm_image = cv2.normalize(image, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)

Correct location of openssl.cnf file

/usr/local/ssl/openssl.cnf

is soft link of

/etc/ssl/openssl.cnf

You can see that using long list (ls -l) on the /usr/local/ssl/ directory where you will find

lrwxrwxrwx 1 root root 20 Mar 1 05:15 openssl.cnf -> /etc/ssl/openssl.cnf

jQuery get input value after keypress

please use this code for input text

$('#search').on("input",function (e) {});

if you use .on("change",function (e) {}); then you need to blur input

if you use .on("keyup",function (e) {}); then you get value before the last character you typed

Split string into individual words Java

you can use Apache commons' StringUtils class

    String[] partsOfString = StringUtils.split("I want to walk my dog",StringUtils.SPACE)

PHP salt and hash SHA256 for login password

According to php.net the Salt option has been deprecated as of PHP 7.0.0, so you should use the salt that is generated by default and is far more simpler

Example for store the password:

$hashPassword = password_hash("password", PASSWORD_BCRYPT);

Example to verify the password:

$passwordCorrect = password_verify("password", $hashPassword);