Programs & Examples On #Wxwidgets

wxWidgets is a cross-platform GUI framework. It is written in C++ and has bindings for Python, Perl, Ruby, PHP, Erlang and even .Net. It also supports several mobile platforms including Windows Mobile, iPhone SDK and embedded GTK+.

Python ImportError: No module named wx

If you do not have wx installed on windows you can use :

 pip install wx

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

OpenGL. It WILL be hard and possibly rewriting the wheel, though. Keep in mind that OpenGL is a general 3D library, and not a specific plot library, but you can implement plotting based on it.

Best/Most Comprehensive API for Stocks/Financial Data

Markit On Demand provides a set of free financial APIs for playing around with. Looks like there is a stock quote API, a stock ticker/company search and a charting API available. Look at http://dev.markitondemand.com

Cast object to interface in TypeScript

If it helps anyone, I was having an issue where I wanted to treat an object as another type with a similar interface. I attempted the following:

Didn't pass linting

const x = new Obj(a as b);

The linter was complaining that a was missing properties that existed on b. In other words, a had some properties and methods of b, but not all. To work around this, I followed VS Code's suggestion:

Passed linting and testing

const x = new Obj(a as unknown as b);

Note that if your code attempts to call one of the properties that exists on type b that is not implemented on type a, you should realize a runtime fault.

In a URL, should spaces be encoded using %20 or +?

It shouldn't matter, any more than if you encoded the letter A as %41.

However, if you're dealing with a system that doesn't recognize one form, it seems like you're just going to have to give it what it expects regardless of what the "spec" says.

How to convert from Hex to ASCII in JavaScript?

_x000D_
_x000D_
console.log(_x000D_
_x000D_
"68656c6c6f20776f726c6421".match(/.{1,2}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")_x000D_
_x000D_
)
_x000D_
_x000D_
_x000D_

Add numpy array as column to Pandas data frame

df = pd.DataFrame(np.arange(1,10).reshape(3,3))
df['newcol'] = pd.Series(your_2d_numpy_array)

PHP remove special character from string

See example.

/**
 * nv_get_plaintext()
 *
 * @param mixed $string
 * @return
 */
function nv_get_plaintext( $string, $keep_image = false, $keep_link = false )
{
    // Get image tags
    if( $keep_image )
    {
        if( preg_match_all( "/\<img[^\>]*src=\"([^\"]*)\"[^\>]*\>/is", $string, $match ) )
        {
            foreach( $match[0] as $key => $_m )
            {
                $textimg = '';
                if( strpos( $match[1][$key], 'data:image/png;base64' ) === false )
                {
                    $textimg = " " . $match[1][$key];
                }
                if( preg_match_all( "/\<img[^\>]*alt=\"([^\"]+)\"[^\>]*\>/is", $_m, $m_alt ) )
                {
                    $textimg .= " " . $m_alt[1][0];
                }
                $string = str_replace( $_m, $textimg, $string );
            }
        }
    }

    // Get link tags
    if( $keep_link )
    {
        if( preg_match_all( "/\<a[^\>]*href=\"([^\"]+)\"[^\>]*\>(.*)\<\/a\>/isU", $string, $match ) )
        {
            foreach( $match[0] as $key => $_m )
            {
                $string = str_replace( $_m, $match[1][$key] . " " . $match[2][$key], $string );
            }
        }
    }

    $string = str_replace( ' ', ' ', strip_tags( $string ) );
    return preg_replace( '/[ ]+/', ' ', $string );
}

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

This is example:

$.ajax({
  url: "test.html",
  async: false
}).done(function(data) {
   // Todo something..
}).fail(function(xhr)  {
   // Todo something..
});

Running shell command and capturing the output

I had the same problem but figured out a very simple way of doing this:

import subprocess
output = subprocess.getoutput("ls -l")
print(output)

Hope it helps out

Note: This solution is Python3 specific as subprocess.getoutput() doesn't work in Python2

Postgres error on insert - ERROR: invalid byte sequence for encoding "UTF8": 0x00

PostgreSQL doesn't support storing NULL (\0x00) characters in text fields (this is obviously different from the database NULL value, which is fully supported).

Source: http://www.postgresql.org/docs/9.1/static/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS-UESCAPE

If you need to store the NULL character, you must use a bytea field - which should store anything you want, but won't support text operations on it.

Given that PostgreSQL doesn't support it in text values, there's no good way to get it to remove it. You could import your data into bytea and later convert it to text using a special function (in perl or something, maybe?), but it's likely going to be easier to do that in preprocessing before you load it.

How to join (merge) data frames (inner, outer, left, right)

Update join. One other important SQL-style join is an "update join" where columns in one table are updated (or created) using another table.

Modifying the OP's example tables...

sales = data.frame(
  CustomerId = c(1, 1, 1, 3, 4, 6), 
  Year = 2000:2005,
  Product = c(rep("Toaster", 3), rep("Radio", 3))
)
cust = data.frame(
  CustomerId = c(1, 1, 4, 6), 
  Year = c(2001L, 2002L, 2002L, 2002L),
  State = state.name[1:4]
)

sales
# CustomerId Year Product
#          1 2000 Toaster
#          1 2001 Toaster
#          1 2002 Toaster
#          3 2003   Radio
#          4 2004   Radio
#          6 2005   Radio

cust
# CustomerId Year    State
#          1 2001  Alabama
#          1 2002   Alaska
#          4 2002  Arizona
#          6 2002 Arkansas

Suppose we want to add the customer's state from cust to the purchases table, sales, ignoring the year column. With base R, we can identify matching rows and then copy values over:

sales$State <- cust$State[ match(sales$CustomerId, cust$CustomerId) ]

# CustomerId Year Product    State
#          1 2000 Toaster  Alabama
#          1 2001 Toaster  Alabama
#          1 2002 Toaster  Alabama
#          3 2003   Radio     <NA>
#          4 2004   Radio  Arizona
#          6 2005   Radio Arkansas

# cleanup for the next example
sales$State <- NULL

As can be seen here, match selects the first matching row from the customer table.


Update join with multiple columns. The approach above works well when we are joining on only a single column and are satisfied with the first match. Suppose we want the year of measurement in the customer table to match the year of sale.

As @bgoldst's answer mentions, match with interaction might be an option for this case. More straightforwardly, one could use data.table:

library(data.table)
setDT(sales); setDT(cust)

sales[, State := cust[sales, on=.(CustomerId, Year), x.State]]

#    CustomerId Year Product   State
# 1:          1 2000 Toaster    <NA>
# 2:          1 2001 Toaster Alabama
# 3:          1 2002 Toaster  Alaska
# 4:          3 2003   Radio    <NA>
# 5:          4 2004   Radio    <NA>
# 6:          6 2005   Radio    <NA>

# cleanup for next example
sales[, State := NULL]

Rolling update join. Alternately, we may want to take the last state the customer was found in:

sales[, State := cust[sales, on=.(CustomerId, Year), roll=TRUE, x.State]]

#    CustomerId Year Product    State
# 1:          1 2000 Toaster     <NA>
# 2:          1 2001 Toaster  Alabama
# 3:          1 2002 Toaster   Alaska
# 4:          3 2003   Radio     <NA>
# 5:          4 2004   Radio  Arizona
# 6:          6 2005   Radio Arkansas

The three examples above all focus on creating/adding a new column. See the related R FAQ for an example of updating/modifying an existing column.

Convert an integer to a byte array

Check out the "encoding/binary" package. Particularly the Read and Write functions:

binary.Write(a, binary.LittleEndian, myInt)

Check mySQL version on Mac 10.8.5

You should be able to open terminal and just type

mysql -v

Hosting ASP.NET in IIS7 gives Access is denied?

I gave access to "IIS_IUser" but instead it should be "IUSR". That solved the problem.

How to keep a git branch in sync with master

Yeah I agree with your approach. To merge mobiledevicesupport into master you can use

git checkout master
git pull origin master //Get all latest commits of master branch
git merge mobiledevicesupport

Similarly you can also merge master in mobiledevicesupport.

Q. If cross merging is an issue or not.

A. Well it depends upon the commits made in mobile* branch and master branch from the last time they were synced. Take this example: After last sync, following commits happen to these branches

Master branch: A -> B -> C [where A,B,C are commits]
Mobile branch: D -> E

Now, suppose commit B made some changes to file a.txt and commit D also made some changes to a.txt. Let us have a look at the impact of each operation of merging now,

git checkout master //Switches to master branch
git pull // Get the commits you don't have. May be your fellow workers have made them.
git merge mobiledevicesupport // It will try to add D and E in master branch.

Now, there are two types of merging possible

  1. Fast forward merge
  2. True merge (Requires manual effort)

Git will first try to make FF merge and if it finds any conflicts are not resolvable by git. It fails the merge and asks you to merge. In this case, a new commit will occur which is responsible for resolving conflicts in a.txt.

So Bottom line is Cross merging is not an issue and ultimately you have to do it and that is what syncing means. Make sure you dirty your hands in merging branches before doing anything in production.

Where is Maven's settings.xml located on Mac OS?

I installed mavaen using sdkman because of which the other proposed solution didn't work, as they are applicable if the installation is done via Homebrew or as a standalone binary.

for my solution I did "which mvn" in the terminal which returned: "/Users/samkaz/.sdkman/candidates/maven/current/bin/mvn"

Then after opening the path in a finder and looking around the above directory I found settings.xml in the below folder. "/Users/samkaz/.sdkman/candidates/maven/3.6.3/conf"

Modular multiplicative inverse function in Python

Python 3.8+

y = pow(x, -1, p)

Python 3.7 and earlier

Maybe someone will find this useful (from wikibooks):

def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, y, x = egcd(b % a, a)
        return (g, x - (b // a) * y, y)

def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        raise Exception('modular inverse does not exist')
    else:
        return x % m

How do I initialise all entries of a matrix with a specific value?

It is easy to assign repeated values to an array:

x(1:10) = 5;

If you want to generate the array of elements inline in a statement try something like this:

ones(1,10) * 5

or with repmat

repmat(5, 1, 10)

ImportError: No module named dateutil.parser

On Ubuntu you may need to install the package manager pip first:

sudo apt-get install python-pip

Then install the python-dateutil package with:

sudo pip install python-dateutil

GitHub: invalid username or password

When using the https:// URL to connect to your remote repository, then Git will not use SSH as authentication but will instead try a basic authentication over HTTPS. Usually, you would just use the URL without a username, e.g. https://github.com/username/repository.git, and Git would then prompt you to enter both a username (your GitHub username) and your password.

If you use https://[email protected]/username/repository.git, then you have preset the username Git will use for authentication: something. Since you used https://[email protected], Git will try to log in using the git username for which your password of course doesn’t work. So you will have to use your username instead.

The alternative is actually to use SSH for authentication. That way you will avoid having to type your password all the time; and since it already seems to work, that’s what you should be using.

To do that, you need to change your remote URL though, so Git knows that it needs to connect via SSH. The format is then this: [email protected]:username/repository. To update your URL use this command:

git remote set-url origin [email protected]:username/repository

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

You're probably trying to run Python 3 file with Python 2 interpreter. Currently (as of 2019), python command defaults to Python 2 when both versions are installed, on Windows and most Linux distributions.

But in case you're indeed working on a Python 2 script, a not yet mentioned on this page solution is to resave the file in UTF-8+BOM encoding, that will add three special bytes to the start of the file, they will explicitly inform the Python interpreter (and your text editor) about the file encoding.

Get SSID when WIFI is connected

Starting with Android 8.1 (API 27), apps must be granted the ACCESS_COARSE_LOCATION (or ACCESS_FINE_LOCATION) permission in order to obtain results from WifiInfo.getSSID() or WifiInfo.getBSSID(). Apps that target API 29 or higher (Android 10) must be granted ACCESS_FINE_LOCATION.

This permission is also needed to obtain results from WifiManager.getConnectionInfo() and WifiManager.getScanResults() although it is not clear if this is new in 8.1 or was required previously.

Source: "BSSID/SSID can be used to deduce location, so require the same location permissions for access to these WifiInfo fields requested using WifiManager.getConnectionInfo() as for WifiManager.getScanResults()."

raw vs. html_safe vs. h to unescape html

In Simple Rails terms:

h remove html tags into number characters so that rendering won't break your html

html_safe sets a boolean in string so that the string is considered as html save

raw It converts to html_safe to string

How to Set focus to first text input in a bootstrap modal after shown

if you're looking for a snippet that would work for all your modals, and search automatically for the 1st input text in the opened one, you should use this:

$('.modal').on('shown.bs.modal', function () {
    $(this).find( 'input:visible:first').focus();
});

If your modal is loaded using ajax, use this instead:

$(document).on('shown.bs.modal', '.modal', function() {
    $(this).find('input:visible:first').focus();
});

How to solve "The specified service has been marked for deletion" error

I had the same problem, finally I decide to kill service process.

for it try below steps:

  • get process id of service with

    sc queryex <service name>

  • kill process with

    taskkill /F /PID <Service PID>

What is the list of supported languages/locales on Android?

List of locales supported as of API 22 (Android 5.1). Obtained from a Nexus 5 with locale set to "English (United States)" (locale affects the DisplayName output).

for (Locale locale : Locale.getAvailableLocales()) {
    Log.d("LOCALES", locale.getLanguage() + "_" + locale.getCountry() + " [" + locale.getDisplayName() + "]");
}


    af_ [Afrikaans]
    af_NA [Afrikaans (Namibia)]
    af_ZA [Afrikaans (South Africa)]
    agq_ [Aghem]
    agq_CM [Aghem (Cameroon)]
    ak_ [Akan]
    ak_GH [Akan (Ghana)]
    am_ [Amharic]
    am_ET [Amharic (Ethiopia)]
    ar_ [Arabic]
    ar_001 [Arabic (World)]
    ar_AE [Arabic (United Arab Emirates)]
    ar_BH [Arabic (Bahrain)]
    ar_DJ [Arabic (Djibouti)]
    ar_DZ [Arabic (Algeria)]
    ar_EG [Arabic (Egypt)]
    ar_EH [Arabic (Western Sahara)]
    ar_ER [Arabic (Eritrea)]
    ar_IL [Arabic (Israel)]
    ar_IQ [Arabic (Iraq)]
    ar_JO [Arabic (Jordan)]
    ar_KM [Arabic (Comoros)]
    ar_KW [Arabic (Kuwait)]
    ar_LB [Arabic (Lebanon)]
    ar_LY [Arabic (Libya)]
    ar_MA [Arabic (Morocco)]
    ar_MR [Arabic (Mauritania)]
    ar_OM [Arabic (Oman)]
    ar_PS [Arabic (Palestine)]
    ar_QA [Arabic (Qatar)]
    ar_SA [Arabic (Saudi Arabia)]
    ar_SD [Arabic (Sudan)]
    ar_SO [Arabic (Somalia)]
    ar_SS [Arabic (South Sudan)]
    ar_SY [Arabic (Syria)]
    ar_TD [Arabic (Chad)]
    ar_TN [Arabic (Tunisia)]
    ar_YE [Arabic (Yemen)]
    as_ [Assamese]
    as_IN [Assamese (India)]
    asa_ [Asu]
    asa_TZ [Asu (Tanzania)]
    az_ [Azerbaijani]
    az_ [Azerbaijani (Cyrillic)]
    az_AZ [Azerbaijani (Cyrillic,Azerbaijan)]
    az_ [Azerbaijani (Latin)]
    az_AZ [Azerbaijani (Latin,Azerbaijan)]
    bas_ [Basaa]
    bas_CM [Basaa (Cameroon)]
    be_ [Belarusian]
    be_BY [Belarusian (Belarus)]
    bem_ [Bemba]
    bem_ZM [Bemba (Zambia)]
    bez_ [Bena]
    bez_TZ [Bena (Tanzania)]
    bg_ [Bulgarian]
    bg_BG [Bulgarian (Bulgaria)]
    bm_ [Bambara]
    bm_ML [Bambara (Mali)]
    bn_ [Bengali]
    bn_BD [Bengali (Bangladesh)]
    bn_IN [Bengali (India)]
    bo_ [Tibetan]
    bo_CN [Tibetan (China)]
    bo_IN [Tibetan (India)]
    br_ [Breton]
    br_FR [Breton (France)]
    brx_ [Bodo]
    brx_IN [Bodo (India)]
    bs_ [Bosnian]
    bs_ [Bosnian (Cyrillic)]
    bs_BA [Bosnian (Cyrillic,Bosnia and Herzegovina)]
    bs_ [Bosnian (Latin)]
    bs_BA [Bosnian (Latin,Bosnia and Herzegovina)]
    ca_ [Catalan]
    ca_AD [Catalan (Andorra)]
    ca_ES [Catalan (Spain)]
    ca_FR [Catalan (France)]
    ca_IT [Catalan (Italy)]
    cgg_ [Chiga]
    cgg_UG [Chiga (Uganda)]
    chr_ [Cherokee]
    chr_US [Cherokee (United States)]
    cs_ [Czech]
    cs_CZ [Czech (Czech Republic)]
    cy_ [Welsh]
    cy_GB [Welsh (United Kingdom)]
    da_ [Danish]
    da_DK [Danish (Denmark)]
    da_GL [Danish (Greenland)]
    dav_ [Taita]
    dav_KE [Taita (Kenya)]
    de_ [German]
    de_AT [German (Austria)]
    de_BE [German (Belgium)]
    de_CH [German (Switzerland)]
    de_DE [German (Germany)]
    de_LI [German (Liechtenstein)]
    de_LU [German (Luxembourg)]
    dje_ [Zarma]
    dje_NE [Zarma (Niger)]
    dua_ [Duala]
    dua_CM [Duala (Cameroon)]
    dyo_ [Jola-Fonyi]
    dyo_SN [Jola-Fonyi (Senegal)]
    dz_ [Dzongkha]
    dz_BT [Dzongkha (Bhutan)]
    ebu_ [Embu]
    ebu_KE [Embu (Kenya)]
    ee_ [Ewe]
    ee_GH [Ewe (Ghana)]
    ee_TG [Ewe (Togo)]
    el_ [Greek]
    el_CY [Greek (Cyprus)]
    el_GR [Greek (Greece)]
    en_ [English]
    en_001 [English (World)]
    en_150 [English (Europe)]
    en_AG [English (Antigua and Barbuda)]
    en_AI [English (Anguilla)]
    en_AS [English (American Samoa)]
    en_AU [English (Australia)]
    en_BB [English (Barbados)]
    en_BE [English (Belgium)]
    en_BM [English (Bermuda)]
    en_BS [English (Bahamas)]
    en_BW [English (Botswana)]
    en_BZ [English (Belize)]
    en_CA [English (Canada)]
    en_CC [English (Cocos (Keeling) Islands)]
    en_CK [English (Cook Islands)]
    en_CM [English (Cameroon)]
    en_CX [English (Christmas Island)]
    en_DG [English (Diego Garcia)]
    en_DM [English (Dominica)]
    en_ER [English (Eritrea)]
    en_FJ [English (Fiji)]
    en_FK [English (Falkland Islands (Islas Malvinas))]
    en_FM [English (Micronesia)]
    en_GB [English (United Kingdom)]
    en_GD [English (Grenada)]
    en_GG [English (Guernsey)]
    en_GH [English (Ghana)]
    en_GI [English (Gibraltar)]
    en_GM [English (Gambia)]
    en_GU [English (Guam)]
    en_GY [English (Guyana)]
    en_HK [English (Hong Kong)]
    en_IE [English (Ireland)]
    en_IM [English (Isle of Man)]
    en_IN [English (India)]
    en_IO [English (British Indian Ocean Territory)]
    en_JE [English (Jersey)]
    en_JM [English (Jamaica)]
    en_KE [English (Kenya)]
    en_KI [English (Kiribati)]
    en_KN [English (Saint Kitts and Nevis)]
    en_KY [English (Cayman Islands)]
    en_LC [English (Saint Lucia)]
    en_LR [English (Liberia)]
    en_LS [English (Lesotho)]
    en_MG [English (Madagascar)]
    en_MH [English (Marshall Islands)]
    en_MO [English (Macau)]
    en_MP [English (Northern Mariana Islands)]
    en_MS [English (Montserrat)]
    en_MT [English (Malta)]
    en_MU [English (Mauritius)]
    en_MW [English (Malawi)]
    en_NA [English (Namibia)]
    en_NF [English (Norfolk Island)]
    en_NG [English (Nigeria)]
    en_NR [English (Nauru)]
    en_NU [English (Niue)]
    en_NZ [English (New Zealand)]
    en_PG [English (Papua New Guinea)]
    en_PH [English (Philippines)]
    en_PK [English (Pakistan)]
    en_PN [English (Pitcairn Islands)]
    en_PR [English (Puerto Rico)]
    en_PW [English (Palau)]
    en_RW [English (Rwanda)]
    en_SB [English (Solomon Islands)]
    en_SC [English (Seychelles)]
    en_SD [English (Sudan)]
    en_SG [English (Singapore)]
    en_SH [English (Saint Helena)]
    en_SL [English (Sierra Leone)]
    en_SS [English (South Sudan)]
    en_SX [English (Sint Maarten)]
    en_SZ [English (Swaziland)]
    en_TC [English (Turks and Caicos Islands)]
    en_TK [English (Tokelau)]
    en_TO [English (Tonga)]
    en_TT [English (Trinidad and Tobago)]
    en_TV [English (Tuvalu)]
    en_TZ [English (Tanzania)]
    en_UG [English (Uganda)]
    en_UM [English (U.S. Outlying Islands)]
    en_US [English (United States)]
    en_US [English (United States,Computer)]
    en_VC [English (St. Vincent & Grenadines)]
    en_VG [English (British Virgin Islands)]
    en_VI [English (U.S. Virgin Islands)]
    en_VU [English (Vanuatu)]
    en_WS [English (Samoa)]
    en_ZA [English (South Africa)]
    en_ZM [English (Zambia)]
    en_ZW [English (Zimbabwe)]
    eo_ [Esperanto]
    es_ [Spanish]
    es_419 [Spanish (Latin America)]
    es_AR [Spanish (Argentina)]
    es_BO [Spanish (Bolivia)]
    es_CL [Spanish (Chile)]
    es_CO [Spanish (Colombia)]
    es_CR [Spanish (Costa Rica)]
    es_CU [Spanish (Cuba)]
    es_DO [Spanish (Dominican Republic)]
    es_EA [Spanish (Ceuta and Melilla)]
    es_EC [Spanish (Ecuador)]
    es_ES [Spanish (Spain)]
    es_GQ [Spanish (Equatorial Guinea)]
    es_GT [Spanish (Guatemala)]
    es_HN [Spanish (Honduras)]
    es_IC [Spanish (Canary Islands)]
    es_MX [Spanish (Mexico)]
    es_NI [Spanish (Nicaragua)]
    es_PA [Spanish (Panama)]
    es_PE [Spanish (Peru)]
    es_PH [Spanish (Philippines)]
    es_PR [Spanish (Puerto Rico)]
    es_PY [Spanish (Paraguay)]
    es_SV [Spanish (El Salvador)]
    es_US [Spanish (United States)]
    es_UY [Spanish (Uruguay)]
    es_VE [Spanish (Venezuela)]
    et_ [Estonian]
    et_EE [Estonian (Estonia)]
    eu_ [Basque]
    eu_ES [Basque (Spain)]
    ewo_ [Ewondo]
    ewo_CM [Ewondo (Cameroon)]
    fa_ [Persian]
    fa_AF [Persian (Afghanistan)]
    fa_IR [Persian (Iran)]
    ff_ [Fulah]
    ff_SN [Fulah (Senegal)]
    fi_ [Finnish]
    fi_FI [Finnish (Finland)]
    fil_ [Filipino]
    fil_PH [Filipino (Philippines)]
    fo_ [Faroese]
    fo_FO [Faroese (Faroe Islands)]
    fr_ [French]
    fr_BE [French (Belgium)]
    fr_BF [French (Burkina Faso)]
    fr_BI [French (Burundi)]
    fr_BJ [French (Benin)]
    fr_BL [French (Saint Barthélemy)]
    fr_CA [French (Canada)]
    fr_CD [French (Congo (DRC))]
    fr_CF [French (Central African Republic)]
    fr_CG [French (Congo (Republic))]
    fr_CH [French (Switzerland)]
    fr_CI [French (Côte d’Ivoire)]
    fr_CM [French (Cameroon)]
    fr_DJ [French (Djibouti)]
    fr_DZ [French (Algeria)]
    fr_FR [French (France)]
    fr_GA [French (Gabon)]
    fr_GF [French (French Guiana)]
    fr_GN [French (Guinea)]
    fr_GP [French (Guadeloupe)]
    fr_GQ [French (Equatorial Guinea)]
    fr_HT [French (Haiti)]
    fr_KM [French (Comoros)]
    fr_LU [French (Luxembourg)]
    fr_MA [French (Morocco)]
    fr_MC [French (Monaco)]
    fr_MF [French (Saint Martin)]
    fr_MG [French (Madagascar)]
    fr_ML [French (Mali)]
    fr_MQ [French (Martinique)]
    fr_MR [French (Mauritania)]
    fr_MU [French (Mauritius)]
    fr_NC [French (New Caledonia)]
    fr_NE [French (Niger)]
    fr_PF [French (French Polynesia)]
    fr_PM [French (Saint Pierre and Miquelon)]
    fr_RE [French (Réunion)]
    fr_RW [French (Rwanda)]
    fr_SC [French (Seychelles)]
    fr_SN [French (Senegal)]
    fr_SY [French (Syria)]
    fr_TD [French (Chad)]
    fr_TG [French (Togo)]
    fr_TN [French (Tunisia)]
    fr_VU [French (Vanuatu)]
    fr_WF [French (Wallis and Futuna)]
    fr_YT [French (Mayotte)]
    ga_ [Irish]
    ga_IE [Irish (Ireland)]
    gl_ [Galician]
    gl_ES [Galician (Spain)]
    gsw_ [Swiss German]
    gsw_CH [Swiss German (Switzerland)]
    gsw_LI [Swiss German (Liechtenstein)]
    gu_ [Gujarati]
    gu_IN [Gujarati (India)]
    guz_ [Gusii]
    guz_KE [Gusii (Kenya)]
    gv_ [Manx]
    gv_IM [Manx (Isle of Man)]
    ha_ [Hausa]
    ha_ [Hausa (Latin)]
    ha_GH [Hausa (Latin,Ghana)]
    ha_NE [Hausa (Latin,Niger)]
    ha_NG [Hausa (Latin,Nigeria)]
    haw_ [Hawaiian]
    haw_US [Hawaiian (United States)]
    iw_ [Hebrew]
    iw_IL [Hebrew (Israel)]
    hi_ [Hindi]
    hi_IN [Hindi (India)]
    hr_ [Croatian]
    hr_BA [Croatian (Bosnia and Herzegovina)]
    hr_HR [Croatian (Croatia)]
    hu_ [Hungarian]
    hu_HU [Hungarian (Hungary)]
    hy_ [Armenian]
    hy_AM [Armenian (Armenia)]
    in_ [Indonesian]
    in_ID [Indonesian (Indonesia)]
    ig_ [Igbo]
    ig_NG [Igbo (Nigeria)]
    ii_ [Sichuan Yi]
    ii_CN [Sichuan Yi (China)]
    is_ [Icelandic]
    is_IS [Icelandic (Iceland)]
    it_ [Italian]
    it_CH [Italian (Switzerland)]
    it_IT [Italian (Italy)]
    it_SM [Italian (San Marino)]
    ja_ [Japanese]
    ja_JP [Japanese (Japan)]
    jgo_ [Ngomba]
    jgo_CM [Ngomba (Cameroon)]
    jmc_ [Machame]
    jmc_TZ [Machame (Tanzania)]
    ka_ [Georgian]
    ka_GE [Georgian (Georgia)]
    kab_ [Kabyle]
    kab_DZ [Kabyle (Algeria)]
    kam_ [Kamba]
    kam_KE [Kamba (Kenya)]
    kde_ [Makonde]
    kde_TZ [Makonde (Tanzania)]
    kea_ [Kabuverdianu]
    kea_CV [Kabuverdianu (Cape Verde)]
    khq_ [Koyra Chiini]
    khq_ML [Koyra Chiini (Mali)]
    ki_ [Kikuyu]
    ki_KE [Kikuyu (Kenya)]
    kk_ [Kazakh]
    kk_ [Kazakh (Cyrillic)]
    kk_KZ [Kazakh (Cyrillic,Kazakhstan)]
    kkj_ [Kako]
    kkj_CM [Kako (Cameroon)]
    kl_ [Kalaallisut]
    kl_GL [Kalaallisut (Greenland)]
    kln_ [Kalenjin]
    kln_KE [Kalenjin (Kenya)]
    km_ [Khmer]
    km_KH [Khmer (Cambodia)]
    kn_ [Kannada]
    kn_IN [Kannada (India)]
    ko_ [Korean]
    ko_KP [Korean (North Korea)]
    ko_KR [Korean (South Korea)]
    kok_ [Konkani]
    kok_IN [Konkani (India)]
    ks_ [Kashmiri]
    ks_ [Kashmiri (Arabic)]
    ks_IN [Kashmiri (Arabic,India)]
    ksb_ [Shambala]
    ksb_TZ [Shambala (Tanzania)]
    ksf_ [Bafia]
    ksf_CM [Bafia (Cameroon)]
    kw_ [Cornish]
    kw_GB [Cornish (United Kingdom)]
    ky_ [Kyrgyz]
    ky_ [Kyrgyz (Cyrillic)]
    ky_KG [Kyrgyz (Cyrillic,Kyrgyzstan)]
    lag_ [Langi]
    lag_TZ [Langi (Tanzania)]
    lg_ [Ganda]
    lg_UG [Ganda (Uganda)]
    lkt_ [Lakota]
    lkt_US [Lakota (United States)]
    ln_ [Lingala]
    ln_AO [Lingala (Angola)]
    ln_CD [Lingala (Congo (DRC))]
    ln_CF [Lingala (Central African Republic)]
    ln_CG [Lingala (Congo (Republic))]
    lo_ [Lao]
    lo_LA [Lao (Laos)]
    lt_ [Lithuanian]
    lt_LT [Lithuanian (Lithuania)]
    lu_ [Luba-Katanga]
    lu_CD [Luba-Katanga (Congo (DRC))]
    luo_ [Luo]
    luo_KE [Luo (Kenya)]
    luy_ [Luyia]
    luy_KE [Luyia (Kenya)]
    lv_ [Latvian]
    lv_LV [Latvian (Latvia)]
    mas_ [Masai]
    mas_KE [Masai (Kenya)]
    mas_TZ [Masai (Tanzania)]
    mer_ [Meru]
    mer_KE [Meru (Kenya)]
    mfe_ [Morisyen]
    mfe_MU [Morisyen (Mauritius)]
    mg_ [Malagasy]
    mg_MG [Malagasy (Madagascar)]
    mgh_ [Makhuwa-Meetto]
    mgh_MZ [Makhuwa-Meetto (Mozambique)]
    mgo_ [Meta']
    mgo_CM [Meta' (Cameroon)]
    mk_ [Macedonian]
    mk_MK [Macedonian (Macedonia (FYROM))]
    ml_ [Malayalam]
    ml_IN [Malayalam (India)]
    mn_ [Mongolian]
    mn_ [Mongolian (Cyrillic)]
    mn_MN [Mongolian (Cyrillic,Mongolia)]
    mr_ [Marathi]
    mr_IN [Marathi (India)]
    ms_ [Malay]
    ms_ [Malay (Latin)]
    ms_BN [Malay (Latin,Brunei)]
    ms_MY [Malay (Latin,Malaysia)]
    ms_SG [Malay (Latin,Singapore)]
    mt_ [Maltese]
    mt_MT [Maltese (Malta)]
    mua_ [Mundang]
    mua_CM [Mundang (Cameroon)]
    my_ [Burmese]
    my_MM [Burmese (Myanmar (Burma))]
    naq_ [Nama]
    naq_NA [Nama (Namibia)]
    nb_ [Norwegian Bokmål]
    nb_NO [Norwegian Bokmål (Norway)]
    nb_SJ [Norwegian Bokmål (Svalbard and Jan Mayen)]
    nd_ [North Ndebele]
    nd_ZW [North Ndebele (Zimbabwe)]
    ne_ [Nepali]
    ne_IN [Nepali (India)]
    ne_NP [Nepali (Nepal)]
    nl_ [Dutch]
    nl_AW [Dutch (Aruba)]
    nl_BE [Dutch (Belgium)]
    nl_BQ [Dutch (Caribbean Netherlands)]
    nl_CW [Dutch (Curaçao)]
    nl_NL [Dutch (Netherlands)]
    nl_SR [Dutch (Suriname)]
    nl_SX [Dutch (Sint Maarten)]
    nmg_ [Kwasio]
    nmg_CM [Kwasio (Cameroon)]
    nn_ [Norwegian Nynorsk]
    nn_NO [Norwegian Nynorsk (Norway)]
    nnh_ [Ngiemboon]
    nnh_CM [Ngiemboon (Cameroon)]
    nus_ [Nuer]
    nus_SD [Nuer (Sudan)]
    nyn_ [Nyankole]
    nyn_UG [Nyankole (Uganda)]
    om_ [Oromo]
    om_ET [Oromo (Ethiopia)]
    om_KE [Oromo (Kenya)]
    or_ [Oriya]
    or_IN [Oriya (India)]
    pa_ [Punjabi]
    pa_ [Punjabi (Arabic)]
    pa_PK [Punjabi (Arabic,Pakistan)]
    pa_ [Punjabi (Gurmukhi)]
    pa_IN [Punjabi (Gurmukhi,India)]
    pl_ [Polish]
    pl_PL [Polish (Poland)]
    ps_ [Pashto]
    ps_AF [Pashto (Afghanistan)]
    pt_ [Portuguese]
    pt_AO [Portuguese (Angola)]
    pt_BR [Portuguese (Brazil)]
    pt_CV [Portuguese (Cape Verde)]
    pt_GW [Portuguese (Guinea-Bissau)]
    pt_MO [Portuguese (Macau)]
    pt_MZ [Portuguese (Mozambique)]
    pt_PT [Portuguese (Portugal)]
    pt_ST [Portuguese (São Tomé and Príncipe)]
    pt_TL [Portuguese (Timor-Leste)]
    rm_ [Romansh]
    rm_CH [Romansh (Switzerland)]
    rn_ [Rundi]
    rn_BI [Rundi (Burundi)]
    ro_ [Romanian]
    ro_MD [Romanian (Moldova)]
    ro_RO [Romanian (Romania)]
    rof_ [Rombo]
    rof_TZ [Rombo (Tanzania)]
    ru_ [Russian]
    ru_BY [Russian (Belarus)]
    ru_KG [Russian (Kyrgyzstan)]
    ru_KZ [Russian (Kazakhstan)]
    ru_MD [Russian (Moldova)]
    ru_RU [Russian (Russia)]
    ru_UA [Russian (Ukraine)]
    rw_ [Kinyarwanda]
    rw_RW [Kinyarwanda (Rwanda)]
    rwk_ [Rwa]
    rwk_TZ [Rwa (Tanzania)]
    saq_ [Samburu]
    saq_KE [Samburu (Kenya)]
    sbp_ [Sangu]
    sbp_TZ [Sangu (Tanzania)]
    seh_ [Sena]
    seh_MZ [Sena (Mozambique)]
    ses_ [Koyraboro Senni]
    ses_ML [Koyraboro Senni (Mali)]
    sg_ [Sango]
    sg_CF [Sango (Central African Republic)]
    shi_ [Tachelhit]
    shi_ [Tachelhit (Latin)]
    shi_MA [Tachelhit (Latin,Morocco)]
    shi_ [Tachelhit (Tifinagh)]
    shi_MA [Tachelhit (Tifinagh,Morocco)]
    si_ [Sinhala]
    si_LK [Sinhala (Sri Lanka)]
    sk_ [Slovak]
    sk_SK [Slovak (Slovakia)]
    sl_ [Slovenian]
    sl_SI [Slovenian (Slovenia)]
    sn_ [Shona]
    sn_ZW [Shona (Zimbabwe)]
    so_ [Somali]
    so_DJ [Somali (Djibouti)]
    so_ET [Somali (Ethiopia)]
    so_KE [Somali (Kenya)]
    so_SO [Somali (Somalia)]
    sq_ [Albanian]
    sq_AL [Albanian (Albania)]
    sq_MK [Albanian (Macedonia (FYROM))]
    sq_XK [Albanian (Kosovo)]
    sr_ [Serbian]
    sr_ [Serbian (Cyrillic)]
    sr_BA [Serbian (Cyrillic,Bosnia and Herzegovina)]
    sr_ME [Serbian (Cyrillic,Montenegro)]
    sr_RS [Serbian (Cyrillic,Serbia)]
    sr_XK [Serbian (Cyrillic,Kosovo)]
    sr_ [Serbian (Latin)]
    sr_BA [Serbian (Latin,Bosnia and Herzegovina)]
    sr_ME [Serbian (Latin,Montenegro)]
    sr_RS [Serbian (Latin,Serbia)]
    sr_XK [Serbian (Latin,Kosovo)]
    sv_ [Swedish]
    sv_AX [Swedish (Åland Islands)]
    sv_FI [Swedish (Finland)]
    sv_SE [Swedish (Sweden)]
    sw_ [Swahili]
    sw_KE [Swahili (Kenya)]
    sw_TZ [Swahili (Tanzania)]
    sw_UG [Swahili (Uganda)]
    swc_ [Congo Swahili]
    swc_CD [Congo Swahili (Congo (DRC))]
    ta_ [Tamil]
    ta_IN [Tamil (India)]
    ta_LK [Tamil (Sri Lanka)]
    ta_MY [Tamil (Malaysia)]
    ta_SG [Tamil (Singapore)]
    te_ [Telugu]
    te_IN [Telugu (India)]
    teo_ [Teso]
    teo_KE [Teso (Kenya)]
    teo_UG [Teso (Uganda)]
    th_ [Thai]
    th_TH [Thai (Thailand)]
    ti_ [Tigrinya]
    ti_ER [Tigrinya (Eritrea)]
    ti_ET [Tigrinya (Ethiopia)]
    to_ [Tongan]
    to_TO [Tongan (Tonga)]
    tr_ [Turkish]
    tr_CY [Turkish (Cyprus)]
    tr_TR [Turkish (Turkey)]
    twq_ [Tasawaq]
    twq_NE [Tasawaq (Niger)]
    tzm_ [Central Atlas Tamazight]
    tzm_ [Central Atlas Tamazight (Latin)]
    tzm_MA [Central Atlas Tamazight (Latin,Morocco)]
    ug_ [Uyghur]
    ug_ [Uyghur (Arabic)]
    ug_CN [Uyghur (Arabic,China)]
    uk_ [Ukrainian]
    uk_UA [Ukrainian (Ukraine)]
    ur_ [Urdu]
    ur_IN [Urdu (India)]
    ur_PK [Urdu (Pakistan)]
    uz_ [Uzbek]
    uz_ [Uzbek (Arabic)]
    uz_AF [Uzbek (Arabic,Afghanistan)]
    uz_ [Uzbek (Cyrillic)]
    uz_UZ [Uzbek (Cyrillic,Uzbekistan)]
    uz_ [Uzbek (Latin)]
    uz_UZ [Uzbek (Latin,Uzbekistan)]
    vai_ [Vai]
    vai_ [Vai (Latin)]
    vai_LR [Vai (Latin,Liberia)]
    vai_ [Vai (Vai)]
    vai_LR [Vai (Vai,Liberia)]
    vi_ [Vietnamese]
    vi_VN [Vietnamese (Vietnam)]
    vun_ [Vunjo]
    vun_TZ [Vunjo (Tanzania)]
    xog_ [Soga]
    xog_UG [Soga (Uganda)]
    yav_ [Yangben]
    yav_CM [Yangben (Cameroon)]
    yo_ [Yoruba]
    yo_BJ [Yoruba (Benin)]
    yo_NG [Yoruba (Nigeria)]
    zgh_ [Standard Moroccan Tamazight]
    zgh_MA [Standard Moroccan Tamazight (Morocco)]
    zh_ [Chinese]
    zh_ [Chinese (Simplified Han)]
    zh_CN [Chinese (Simplified Han,China)]
    zh_HK [Chinese (Simplified Han,Hong Kong)]
    zh_MO [Chinese (Simplified Han,Macau)]
    zh_SG [Chinese (Simplified Han,Singapore)]
    zh_ [Chinese (Traditional Han)]
    zh_HK [Chinese (Traditional Han,Hong Kong)]
    zh_MO [Chinese (Traditional Han,Macau)]
    zh_TW [Chinese (Traditional Han,Taiwan)]
    zu_ [Zulu]
    zu_ZA [Zulu (South Africa)]

How to get the difference between two arrays in JavaScript?

The selected answer is only half right. You must compare the arrays both ways to get a complete answer.

const ids_exist = [
   '1234',
   '5678',
   'abcd',
]

const ids_new = [
  '1234',
  '5678',
  'efjk',
  '9999',
]

function __uniq_Filter (__array_1, __array_2) {
  const one_not_in_two = __array_1.filter(function (obj) {
    return __array_2.indexOf(obj) == -1
  })
  const two_not_in_one = __array_2.filter(function (obj) {
    return __array_1.indexOf(obj) == -1
  })
  return one_not_in_two.concat(two_not_in_one)
}

let uniq_filter = __uniq_Filter(ids_exist, ids_new)

console.log('uniq_filter', uniq_filter) // => [ 'abcd', 'efjk', '9999' ]

Python pandas Filtering out nan from a data selection of a column of strings

Just drop them:

nms.dropna(thresh=2)

this will drop all rows where there are at least two non-NaN.

Then you could then drop where name is NaN:

In [87]:

nms
Out[87]:
  movie    name  rating
0   thg    John       3
1   thg     NaN       4
3   mol  Graham     NaN
4   lob     NaN     NaN
5   lob     NaN     NaN

[5 rows x 3 columns]
In [89]:

nms = nms.dropna(thresh=2)
In [90]:

nms[nms.name.notnull()]
Out[90]:
  movie    name  rating
0   thg    John       3
3   mol  Graham     NaN

[2 rows x 3 columns]

EDIT

Actually looking at what you originally want you can do just this without the dropna call:

nms[nms.name.notnull()]

UPDATE

Looking at this question 3 years later, there is a mistake, firstly thresh arg looks for at least n non-NaN values so in fact the output should be:

In [4]:
nms.dropna(thresh=2)

Out[4]:
  movie    name  rating
0   thg    John     3.0
1   thg     NaN     4.0
3   mol  Graham     NaN

It's possible that I was either mistaken 3 years ago or that the version of pandas I was running had a bug, both scenarios are entirely possible.

How to validate phone number using PHP?

Here's how I find valid 10-digit US phone numbers. At this point I'm assuming the user wants my content so the numbers themselves are trusted. I'm using in an app that ultimately sends an SMS message so I just want the raw numbers no matter what. Formatting can always be added later

//eliminate every char except 0-9
$justNums = preg_replace("/[^0-9]/", '', $string);

//eliminate leading 1 if its there
if (strlen($justNums) == 11) $justNums = preg_replace("/^1/", '',$justNums);

//if we have 10 digits left, it's probably valid.
if (strlen($justNums) == 10) $isPhoneNum = true;

Edit: I ended up having to port this to Java, if anyone's interested. It runs on every keystroke so I tried to keep it fairly light:

boolean isPhoneNum = false;
if (str.length() >= 10 && str.length() <= 14 ) { 
  //14: (###) ###-####
  //eliminate every char except 0-9
  str = str.replaceAll("[^0-9]", "");

  //remove leading 1 if it's there
  if (str.length() == 11) str = str.replaceAll("^1", "");

  isPhoneNum = str.length() == 10;
}
Log.d("ISPHONENUM", String.valueOf(isPhoneNum));

figure of imshow() is too small

That's strange, it definitely works for me:

from matplotlib import pyplot as plt

plt.figure(figsize = (20,2))
plt.imshow(random.rand(8, 90), interpolation='nearest')

I am using the "MacOSX" backend, btw.

How to add a .dll reference to a project in Visual Studio

You probably are looking for AddReference dialog accessible from Project Context Menu (right click..)

From there you can reference dll's, after which you can reference namespaces that you need in your code.

Hide particular div onload and then show div after click

$(document).ready(function() {
    $('#div2').hide(0);
    $('#preview').on('click', function() {
        $('#div1').hide(300, function() { // first hide div1
            // then show div2
            $('#div2').show(300);
        });     
    });
});

You missed # before div2

Working Sample

How to do SQL Like % in Linq?

Well indexOf works for me too

var result = from c in SampleList
where c.LongName.IndexOf(SearchQuery) >= 0
select c;

Best way to convert strings to symbols in hash

Similar to previous solutions but written a bit differently.

  • This allows for a hash that is nested and/or has arrays.
  • Get conversion of keys to a string as a bonus.
  • Code does not mutate the hash been passed in.

    module HashUtils
      def symbolize_keys(hash)
        transformer_function = ->(key) { key.to_sym }
        transform_keys(hash, transformer_function)
      end
    
      def stringify_keys(hash)
        transformer_function = ->(key) { key.to_s }
        transform_keys(hash, transformer_function)
      end
    
      def transform_keys(obj, transformer_function)
        case obj
        when Array
          obj.map{|value| transform_keys(value, transformer_function)}
        when Hash
          obj.each_with_object({}) do |(key, value), hash|
            hash[transformer_function.call(key)] = transform_keys(value, transformer_function)
          end
        else
          obj
        end
      end
    end
    

How can I make window.showmodaldialog work in chrome 37?

Create a cross browser ModalDialog

function _showModalDialog(url, width, height, closeCallback) {
    var modalDiv,
        dialogPrefix = window.showModalDialog ? 'dialog' : '',
        unit = 'px',
        maximized = width === true || height === true,
        w = width || 600,
        h = height || 500,
        border = 5,
        taskbar = 40, // windows taskbar
        header = 20,
        x,
        y;

    if (maximized) {
        x = 0;
        y = 0;
        w = screen.width;
        h = screen.height;
    } else {
        x = window.screenX + (screen.width / 2) - (w / 2) - (border * 2);
        y = window.screenY + (screen.height / 2) - (h / 2) - taskbar - border;
    }

    var features = [
            'toolbar=no',
            'location=no',
            'directories=no',
            'status=no',
            'menubar=no',
            'scrollbars=no',
            'resizable=no',
            'copyhistory=no',
            'center=yes',
            dialogPrefix + 'width=' + w + unit,
            dialogPrefix + 'height=' + h + unit,
            dialogPrefix + 'top=' + y + unit,
            dialogPrefix + 'left=' + x + unit
        ],
        showModal = function (context) {
            if (context) {
                modalDiv = context.document.createElement('div');
                modalDiv.style.cssText = 'top:0;right:0;bottom:0;left:0;position:absolute;z-index:50000;';
                modalDiv.onclick = function () {
                    if (context.focus) {
                        context.focus();
                    }
                    return false;
                }
                window.top.document.body.appendChild(modalDiv);
            }
        },
        removeModal = function () {
            if (modalDiv) {
                modalDiv.onclick = null;
                modalDiv.parentNode.removeChild(modalDiv);
                modalDiv = null;
            }
        };

    // IE
    if (window.showModalDialog) {
        window.showModalDialog(url, null, features.join(';') + ';');

        if (closeCallback) {
            closeCallback();
        }
    // Other browsers
    } else {
        var win = window.open(url, '', features.join(','));
        if (maximized) {
            win.moveTo(0, 0);
        }

        // When charging the window.
        var onLoadFn = function () {
                showModal(this);
            },
            // When you close the window.
            unLoadFn = function () {
                window.clearInterval(interval);
                if (closeCallback) {
                    closeCallback();
                }
                removeModal();
            },
            // When you refresh the context that caught the window.
            beforeUnloadAndCloseFn = function () {
                try {
                    unLoadFn();
                }
                finally {
                    win.close();
                }
            };

        if (win) {
            // Create a task to check if the window was closed.
            var interval = window.setInterval(function () {
                try {
                    if (win == null || win.closed) {
                        unLoadFn();
                    }
                } catch (e) { }
            }, 500);

            if (win.addEventListener) {
                win.addEventListener('load', onLoadFn, false);
            } else {
                win.attachEvent('load', onLoadFn);
            }

            window.addEventListener('beforeunload', beforeUnloadAndCloseFn, false);
        }
    }
}

Passing Objects By Reference or Value in C#

One more code sample to showcase this:

void Main()
{


    int k = 0;
    TestPlain(k);
    Console.WriteLine("TestPlain:" + k);

    TestRef(ref k);
    Console.WriteLine("TestRef:" + k);

    string t = "test";

    TestObjPlain(t);
    Console.WriteLine("TestObjPlain:" +t);

    TestObjRef(ref t);
    Console.WriteLine("TestObjRef:" + t);
}

public static void TestPlain(int i)
{
    i = 5;
}

public static void TestRef(ref int i)
{
    i = 5;
}

public static void TestObjPlain(string s)
{
    s = "TestObjPlain";
}

public static void TestObjRef(ref string s)
{
    s = "TestObjRef";
}

And the output:

TestPlain:0

TestRef:5

TestObjPlain:test

TestObjRef:TestObjRef

dropzone.js - how to do something after ALL files are uploaded

I up-voted you as your method is simple. I did make only a couple of slight amends as sometimes the event fires even though there are no bytes to send - On my machine it did it when I clicked the remove button on a file.

myDropzone.on("totaluploadprogress", function(totalPercentage, totalBytesToBeSent, totalBytesSent ){
            if(totalPercentage >= 100 && totalBytesSent) {
                // All done! Call func here
            }
        });

convert string date to java.sql.Date

This works for me without throwing an exception:

package com.sandbox;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Sandbox {

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date parsed = format.parse("20110210");
        java.sql.Date sql = new java.sql.Date(parsed.getTime());
    }


}

HTTP get with headers using RestTemplate

Take a look at the JavaDoc for RestTemplate.

There is the corresponding getForObject methods that are the HTTP GET equivalents of postForObject, but they doesn't appear to fulfil your requirements of "GET with headers", as there is no way to specify headers on any of the calls.

Looking at the JavaDoc, no method that is HTTP GET specific allows you to also provide header information. There are alternatives though, one of which you have found and are using. The exchange methods allow you to provide an HttpEntity object representing the details of the request (including headers). The execute methods allow you to specify a RequestCallback from which you can add the headers upon its invocation.

Reading HTTP headers in a Spring REST controller

Instead of taking the HttpServletRequest object in every method, keep in controllers' context by auto-wiring via the constructor. Then you can access from all methods of the controller.

public class OAuth2ClientController {
    @Autowired
    private OAuth2ClientService oAuth2ClientService;

    private HttpServletRequest request;

    @Autowired
    public OAuth2ClientController(HttpServletRequest request) {
        this.request = request;
    }

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<String> createClient(@RequestBody OAuth2Client client) {
        System.out.println(request.getRequestURI());
        System.out.println(request.getHeader("Content-Type"));

        return ResponseEntity.ok();
    }
}

How to iterate over a JSONObject?

We used below set of code to iterate over JSONObject fields

Iterator iterator = jsonObject.entrySet().iterator();

while (iterator.hasNext())  {
        Entry<String, JsonElement> entry = (Entry<String, JsonElement>) iterator.next();
        processedJsonObject.add(entry.getKey(), entry.getValue());
}

How can I autoformat/indent C code in vim?

The builtin command for properly indenting the code has already been mentioned (gg=G). If you want to beautify the code, you'll need to use an external application like indent. Since % denotes the current file in ex mode, you can use it like this:

:!indent %

How can I make the Android emulator show the soft keyboard?

To be more precise, with Lollipop these are the steps I followed to show soft keyboard:

  1. Settings > Language & Input;
  2. under "Keyboard & input methods" label, select "Current Keyboard";
  3. A Dialog named "Change Keyboard" appears, switch ON "Hardware", then select "Choose keyboards";
  4. another Dialog appears, switch ON the "Sample Soft Keyboard". Here you get an alert about the possibility that keyboard will store everything you write, also passwords. Give OK;
  5. Repeat above steps in order to show "Change Keyboard" Dialog again, here the new option "Sample Soft Keyboard" is available and you can select it.

NOTE: after that, you might experience problems in running you app (as I had). Simply restart the emulator.

Json.net serialize/deserialize derived types?

Use this JsonKnownTypes, it's very similar way to use, it just add discriminator to json:

[JsonConverter(typeof(JsonKnownTypeConverter<BaseClass>))]
[JsonKnownType(typeof(Base), "base")]
[JsonKnownType(typeof(Derived), "derived")]
public class Base
{
    public string Name;
}
public class Derived : Base
{
    public string Something;
}

Now when you serialize object in json will be add "$type" with "base" and "derived" value and it will be use for deserialize

Serialized list example:

[
    {"Name":"some name", "$type":"base"},
    {"Name":"some name", "Something":"something", "$type":"derived"}
]

How to get Enum Value from index in Java?

I recently had the same problem and used the solution provided by Harry Joy. That solution only works with with zero-based enumaration though. I also wouldn't consider it save as it doesn't deal with indexes that are out of range.

The solution I ended up using might not be as simple but it's completely save and won't hurt the performance of your code even with big enums:

public enum Example {

    UNKNOWN(0, "unknown"), ENUM1(1, "enum1"), ENUM2(2, "enum2"), ENUM3(3, "enum3");

    private static HashMap<Integer, Example> enumById = new HashMap<>();
    static {
        Arrays.stream(values()).forEach(e -> enumById.put(e.getId(), e));
    }

    public static Example getById(int id) {
        return enumById.getOrDefault(id, UNKNOWN);
    }

    private int id;
    private String description;

    private Example(int id, String description) {
        this.id = id;
        this.description= description;
    }

    public String getDescription() {
        return description;
    }

    public int getId() {
        return id;
    }
}

If you are sure that you will never be out of range with your index and you don't want to use UNKNOWN like I did above you can of course also do:

public static Example getById(int id) {
        return enumById.get(id);
}

Any way to make a WPF textblock selectable?


new TextBox
{
   Text = text,
   TextAlignment = TextAlignment.Center,
   TextWrapping = TextWrapping.Wrap,
   IsReadOnly = true,
   Background = Brushes.Transparent,
   BorderThickness = new Thickness()
         {
             Top = 0,
             Bottom = 0,
             Left = 0,
             Right = 0
         }
};

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

Personally I'd go with AJAX.

If you cannot switch to @Ajax... helpers, I suggest you to add a couple of properties in your model

public bool TriggerOnLoad { get; set; }
public string TriggerOnLoadMessage { get; set: }

Change your view to a strongly typed Model via

@using MyModel

Before returning the View, in case of successfull creation do something like

MyModel model = new MyModel();
model.TriggerOnLoad = true;
model.TriggerOnLoadMessage = "Object successfully created!";
return View ("Add", model);

then in your view, add this

@{
   if (model.TriggerOnLoad) {
   <text>
   <script type="text/javascript">
     alert('@Model.TriggerOnLoadMessage');
   </script>
   </text>
   }
}

Of course inside the tag you can choose to do anything you want, event declare a jQuery ready function:

$(document).ready(function () {
   alert('@Model.TriggerOnLoadMessage');
});

Please remember to reset the Model properties upon successfully alert emission.

Another nice thing about MVC is that you can actually define an EditorTemplate for all this, and then use it in your view via:

@Html.EditorFor (m => m.TriggerOnLoadMessage)

But in case you want to build up such a thing, maybe it's better to define your own C# class:

class ClientMessageNotification {
    public bool TriggerOnLoad { get; set; }
    public string TriggerOnLoadMessage { get; set: }
}

and add a ClientMessageNotification property in your model. Then write EditorTemplate / DisplayTemplate for the ClientMessageNotification class and you're done. Nice, clean, and reusable.

Add IIS 7 AppPool Identities as SQL Server Logons

CREATE LOGIN [IIS APPPOOL\MyAppPool] FROM WINDOWS;
CREATE USER MyAppPoolUser FOR LOGIN [IIS APPPOOL\MyAppPool];

MySQL Select all columns from one table and some from another table

I need more information really but it will be along the lines of..

SELECT table1.*, table2.col1, table2.col3 FROM table1 JOIN table2 USING(id)

Maven is not working in Java 8 when Javadoc tags are incomplete

I don't think just turning off DocLint is a good solution, at least not long term. It is good that Javadoc has become a bit more strict so the right way to fix the build problem is to fix the underlying problem. Yes, you'll ultimately need to fix those source code files.

Here are the things to look out for that you could previously get away with:

  • Malformed HTML (for example a missing end-tag, un-escaped brackets, etc)
  • Invalid {@link }s. (same goes for similar tags such as @see)
  • Invalid @author values. This used to be accepted : @author John <[email protected]> but not so anymore because of the un-escaped brackets.
  • HTML tables in Javadoc now require a summary or caption. See this question for explanation.

You'll simply have to fix your source code files and keep building your Javadoc until it can build without a failure. Cumbersome yes, but personally I like when I have brought my projects up to DocLint level because it means I can be more confident that the Javadoc I produce is actually what I intend.

There's of course the problem if you are generating Javadoc on some source code you've not produced yourself, for example because it comes from some code generator, e.g. wsimport. Strange that Oracle didn't prepare their own tools for JDK8 compliance before actually releasing JDK8. It seems it won't be fixed until Java 9. Only in this particular case I suggest to turn off DocLint as documented elsewhere on this page.

Get size of a View in React Native

As of React Native 0.4.2, View components have an onLayout prop. Pass in a function that takes an event object. The event's nativeEvent contains the view's layout.

<View onLayout={(event) => {
  var {x, y, width, height} = event.nativeEvent.layout;
}} />

The onLayout handler will also be invoked whenever the view is resized.

The main caveat is that the onLayout handler is first invoked one frame after your component has mounted, so you may want to hide your UI until you have computed your layout.

Git merge errors

as suggested in git status,

Unmerged paths:                                                                                                                                
(use "git add <file>..." to mark resolution)                                                                                                 

    both modified:   a.jl                                  
    both modified:   b.jl

I used git add to finish the merging, then git checkout works fine.

ld.exe: cannot open output file ... : Permission denied

  1. Open task manager -> Processes -> Click on .exe (Fibonacci.exe) -> End Process

    if it doesn't work

  2. Close eclipse IDE (or whatever IDE you use) and repeat step 1.

Sort list in C# with LINQ

Like this?

In LINQ:

var sortedList = originalList.OrderBy(foo => !foo.AVC)
                             .ToList();

Or in-place:

originalList.Sort((foo1, foo2) => foo2.AVC.CompareTo(foo1.AVC));

As Jon Skeet says, the trick here is knowing that false is considered to be 'smaller' than true.

If you find that you are doing these ordering operations in lots of different places in your code, you might want to get your type Foo to implement the IComparable<Foo> and IComparable interfaces.

fileReader.readAsBinaryString to upload files

(Following is a late but complete answer)

FileReader methods support


FileReader.readAsBinaryString() is deprecated. Don't use it! It's no longer in the W3C File API working draft:

void abort();
void readAsArrayBuffer(Blob blob);
void readAsText(Blob blob, optional DOMString encoding);
void readAsDataURL(Blob blob);

NB: Note that File is a kind of extended Blob structure.

Mozilla still implements readAsBinaryString() and describes it in MDN FileApi documentation:

void abort();
void readAsArrayBuffer(in Blob blob); Requires Gecko 7.0
void readAsBinaryString(in Blob blob);
void readAsDataURL(in Blob file);
void readAsText(in Blob blob, [optional] in DOMString encoding);

The reason behind readAsBinaryString() deprecation is in my opinion the following: the standard for JavaScript strings are DOMString which only accept UTF-8 characters, NOT random binary data. So don't use readAsBinaryString(), that's not safe and ECMAScript-compliant at all.

We know that JavaScript strings are not supposed to store binary data but Mozilla in some sort can. That's dangerous in my opinion. Blob and typed arrays (ArrayBuffer and the not-yet-implemented but not necessary StringView) were invented for one purpose: allow the use of pure binary data, without UTF-8 strings restrictions.

XMLHttpRequest upload support


XMLHttpRequest.send() has the following invocations options:

void send();
void send(ArrayBuffer data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);

XMLHttpRequest.sendAsBinary() has the following invocations options:

void sendAsBinary(   in DOMString body );

sendAsBinary() is NOT a standard and may not be supported in Chrome.

Solutions


So you have several options:

  1. send() the FileReader.result of FileReader.readAsArrayBuffer ( fileObject ). It is more complicated to manipulate (you'll have to make a separate send() for it) but it's the RECOMMENDED APPROACH.
  2. send() the FileReader.result of FileReader.readAsDataURL( fileObject ). It generates useless overhead and compression latency, requires a decompression step on the server-side BUT it's easy to manipulate as a string in Javascript.
  3. Being non-standard and sendAsBinary() the FileReader.result of FileReader.readAsBinaryString( fileObject )

MDN states that:

The best way to send binary content (like in files upload) is using ArrayBuffers or Blobs in conjuncton with the send() method. However, if you want to send a stringifiable raw data, use the sendAsBinary() method instead, or the StringView (Non native) typed arrays superclass.

How to fix Error: listen EADDRINUSE while using nodejs?

Two servers can not listen on same port, so check out if other server listening on same port, also check out for browser sync if its running on same port

MongoDB Data directory /data/db not found

MongoDB needs data directory to store data. Default path is /data/db

When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user.

If you want to change the path of your data directory then you should specify it while starting mongod server like,

mongod --dbpath /data/<path> --port <port no> 

This should help you start your mongod server with custom path and port.

SVN undo delete before commit

The simplest solution I could find was to delete the parent directory from the working copy (with rm -rf, not svn delete), and then run svn update in the grandparent. Eg, if you deleted a/b/c, rm -rf a/b, cd a, svn up. That brings everything back. Of course, this is only a good solution if you have no other uncommitted changes in the parent directory that you want to keep.

Hopefully this page will be at the top of the results next time I google this question. It would be even better if someone suggested a cleaner method, of course.

Python AttributeError: 'module' object has no attribute 'Serial'

I accidentally installed 'serial' (sudo python -m pip install serial) instead of 'pySerial' (sudo python -m pip install pyserial), which lead to the same error.

If the previously mentioned solutions did not work for you, double check if you installed the correct library.

Avoiding "resource is out of sync with the filesystem"

This happens to me all the time.

Go to the error log, find the exception, and open a few levels until you can see something more like a root cause. Does it says "Resource is out of sync with the file system" ?

When renaming packages, of course, Eclipse has to move files around in the file system. Apparently what happens is that it later discovers that something it thinks it needs to clean up has been renamed, can't find it, throws an exception.

There are a couple of things you might try. First, go to Window: Preferences, Workspace, and enable "Refresh Automatically". In theory this should fix the problem, but for me, it didn't.

Second, if you are doing a large refactoring with subpackages, do the subpackages one at a time, from the bottom up, and explicitly refresh with the file system after each subpackage is renamed.

Third, just ignore the error: when the error dialog comes up, click Abort to preserve the partial change, instead of rolling it back. Try it again, and again, and you may find you can get through the entire operation using multiple retries.

Difference between "while" loop and "do while" loop

While:

  1. entry control loop

  2. condition is checked before loop execution

  3. never execute loop if condition is false

  4. there is no semicolon at the end of while statement

Do-while:

  1. exit control loop

  2. condition is checked at the end of loop

  3. executes false condition at least once since condition is checked later

  4. there is semicolon at the end of while statement.

Break out of a While...Wend loop

A While/Wend loop can only be exited prematurely with a GOTO or by exiting from an outer block (Exit sub/function or another exitable loop)

Change to a Do loop instead:

Do While True
    count = count + 1

    If count = 10 Then
        Exit Do
    End If
Loop

Or for looping a set number of times:

for count = 1 to 10
   msgbox count
next

(Exit For can be used above to exit prematurely)

Filtering DataGridView without changing datasource

I just spent an hour on a similar problem. For me the answer turned out to be embarrassingly simple.

(dataGridViewFields.DataSource as DataTable).DefaultView.RowFilter = string.Format("Field = '{0}'", textBoxFilter.Text);

Compare dates in MySQL

This works for me:

select date_format(date(starttime),'%Y-%m-%d') from data
where date(starttime) >= date '2012-11-02';

Note the format string '%Y-%m-%d' and the format of the input date.

How to validate inputs dynamically created using ng-repeat, ng-show (angular)

Building on pkozlowski.opensource's answer, I've added a way to have dynamic input names that also work with ngMessages. Note the ng-init part on the ng-form element and the use of furryName. furryName becomes the variable name that contains the variable value for the input's name attribute.

<ion-item ng-repeat="animal in creatures track by $index">
<ng-form name="animalsForm" ng-init="furryName = 'furry' + $index">
        <!-- animal is furry toggle buttons -->
        <input id="furryRadio{{$index}}"
               type="radio"
               name="{{furryName}}"
               ng-model="animal.isFurry"
               ng-value="radioBoolValues.boolTrue"
               required
                >
        <label for="furryRadio{{$index}}">Furry</label>

        <input id="hairlessRadio{{$index}}"
               name="{{furryName}}"
               type="radio"
               ng-model="animal.isFurry"
               ng-value="radioBoolValues.boolFalse"
               required
               >
        <label for="hairlessRadio{{$index}}">Hairless</label>

        <div ng-messages="animalsForm[furryName].$error"
             class="form-errors"
             ng-show="animalsForm[furryName].$invalid && sectionForm.$submitted">
            <div ng-messages-include="client/views/partials/form-errors.ng.html"></div>
        </div>
</ng-form>
</ion-item>

Synchronously waiting for an async operation, and why does Wait() freeze the program here

Here is what I did

private void myEvent_Handler(object sender, SomeEvent e)
{
  // I dont know how many times this event will fire
  Task t = new Task(() =>
  {
    if (something == true) 
    {
        DoSomething(e);  
    }
  });
  t.RunSynchronously();
}

working great and not blocking UI thread

What is the most robust way to force a UIView to redraw?

Well I know this might be a big change or even not suitable for your project, but did you consider not performing the push until you already have the data? That way you only need to draw the view once and the user experience will also be better - the push will move in already loaded.

The way you do this is in the UITableView didSelectRowAtIndexPath you asynchronously ask for the data. Once you receive the response, you manually perform the segue and pass the data to your viewController in prepareForSegue. Meanwhile you may want to show some activity indicator, for simple loading indicator check https://github.com/jdg/MBProgressHUD

Opening Chrome From Command Line

Have a look into the start command. It should do what you're trying to achieve.

Also, you might be able to leave out path to chrome. The following works on Windows 7:

start chrome "site1.com" "site2.com"

How to Convert a Text File into a List in Python

Maybe:

crimefile = open(fileName, 'r')
yourResult = [line.split(',') for line in crimefile.readlines()]

maxReceivedMessageSize and maxBufferSize in app.config

The currently accepted answer is incorrect. It is NOT required to set maxBufferSize and maxReceivedMessageSize on the client and the server binding. It depends!

If your request is too large (i.e., method parameters of the service operation are memory intensive) set the properties on the server-side, if the response is too large (i.e., the method return value of the service operation is memory intensive) set the values on the client-side.

For the difference between maxBufferSize and maxReceivedMessageSize see MaxBufferSize property?.

How to store phone numbers on MySQL databases?

varchar, Don't store separating characters you may want to format the phone numbers differently for different uses. so store (619) 123-4567 as 6191234567 I work with phone directory data and have found this to be the best practice.

Temporarily change current working directory in bash to run a command

You can run the cd and the executable in a subshell by enclosing the command line in a pair of parentheses:

(cd SOME_PATH && exec_some_command)

Demo:

$ pwd
/home/abhijit
$ (cd /tmp && pwd)  # directory changed in the subshell
/tmp 
$ pwd               # parent shell's pwd is still the same
/home/abhijit

Unable to install boto3

I have faced the same issue and also not using virtual environment. easy_install is working for me.

easy_install boto3

Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied

For those who run into this issue and running the command prompt as administrator does not work this worked for me:

Since I had already tried a first time without running the cmd prompt as admin, in my c:\Users\"USER"\AppData\Local\Temp folder I found it was trying to run files from the same pip-u2e7e0ad-uninstall folder. Deleting this folder from the Temp folder and retrying the installation fixed the issue for me.

What is the difference between iterator and iterable and how to use them?

Consider an example having 10 apples. When it implements Iterable, it is like putting each apple in boxes from 1 to 10 and return an iterator which can be used to navigate.

By implementing iterator, we can get any apple, apple in next boxes etc.

So implementing iterable gives an iterator to navigate its elements although to navigate, iterator needs to be implemented.

Query EC2 tags from within instance

For those crazy enough to use Fish shell on EC2, here's a handy snippet for your /home/ec2-user/.config/fish/config.fish. The hostdata command now will list all your tags as well as the public IP and hostname.

set -x INSTANCE_ID (wget -qO- http://instance-data/latest/meta-data/instance-id)
set -x REGION (wget -qO- http://instance-data/latest/meta-data/placement/availability-zone | sed 's/.$//')

function hostdata
    aws ec2 describe-tags --region $REGION --filter "Name=resource-id,Values=$INSTANCE_ID" --output=text | sed -r 's/TAGS\t(.*)\t.*\t.*\t(.*)/\1="\2"/'
    ec2-metadata | grep public-hostname
    ec2-metadata | grep public-ipv4
end

XMLHttpRequest (Ajax) Error

The problem is likely to lie with the line:

window.onload = onPageLoad();

By including the brackets you are saying onload should equal the return value of onPageLoad(). For example:

/*Example function*/
function onPageLoad()
{
    return "science";
}
/*Set on load*/
window.onload = onPageLoad()

If you print out the value of window.onload to the console it will be:

science

The solution is remove the brackets:

window.onload = onPageLoad;

So, you're using onPageLoad as a reference to the so-named function.

Finally, in order to get the response value you'll need a readystatechange listener for your XMLHttpRequest object, since it's asynchronous:

xmlDoc = xmlhttp.responseXML;
parser = new DOMParser(); // This code is untested as it doesn't run this far.

Here you add the listener:

xmlHttp.onreadystatechange = function() {
    if(this.readyState == 4) {
        // Do something
    }
}

How do I prevent a form from being resized by the user?

To prevent users from resizing, set the FormBoderStyle to Fixed3D or FixedDialog from properties window or from code

frmYour.BorderStyle = System.WinForms.FormBorderStyle.Fixed3D

And set the WindowState property to Maximized, set the MaximizeBox and MinimizeBox properties to false.

To prevent the user from moving around, override WndProc

Protected Overrides Sub WndProc(ByRef m As Message)
        Const WM_NCLBUTTONDOWN As Integer = 161
        Const WM_SYSCOMMAND As Integer = 274
        Const HTCAPTION As Integer = 2
        Const SC_MOVE As Integer = 61456

        If (m.Msg = WM_SYSCOMMAND) And (m.WParam.ToInt32() = SC_MOVE) Then
            Return
        End If

        If (m.Msg = WM_NCLBUTTONDOWN) And (m.WParam.ToInt32() = HTCAPTION) Then
            Return
        End If

        MyBase.WndProc(m)
    End Sub

How to use table variable in a dynamic sql statement?

You can't do this because the table variables are out of scope.

You would have to declare the table variable inside the dynamic SQL statement or create temporary tables.

I would suggest you read this excellent article on dynamic SQL.

http://www.sommarskog.se/dynamic_sql.html

How to check if a string contains a substring in Bash

You should remember that shell scripting is less of a language and more of a collection of commands. Instinctively you think that this "language" requires you to follow an if with a [ or a [[. Both of those are just commands that return an exit status indicating success or failure (just like every other command). For that reason I'd use grep, and not the [ command.

Just do:

if grep -q foo <<<"$string"; then
    echo "It's there"
fi

Now that you are thinking of if as testing the exit status of the command that follows it (complete with semi-colon), why not reconsider the source of the string you are testing?

## Instead of this
filetype="$(file -b "$1")"
if grep -q "tar archive" <<<"$filetype"; then
#...

## Simply do this
if file -b "$1" | grep -q "tar archive"; then
#...

The -q option makes grep not output anything, as we only want the return code. <<< makes the shell expand the next word and use it as the input to the command, a one-line version of the << here document (I'm not sure whether this is standard or a Bashism).

join on multiple columns

Below is the structure of SQL that you may write. You can do multiple joins by using "AND" or "OR".

Select TableA.Col1, TableA.Col2, TableB.Val
FROM TableA, 
INNER JOIN TableB
 ON TableA.Col1 = TableB.Col1 OR TableA.Col2 = TableB.Col2

jquery/javascript convert date string to date

var stringDate = "Sunday, February 28, 2010";

var months = ["January", "February", "March"]; // You add the rest  :-)

var m = /(\w+) (\d+), (\d+)/.exec(stringDate);

var date = new Date(+m[3], months.indexOf(m[1]), +m[2]);

The indexOf method on arrays is only supported on newer browsers (i.e. not IE). You'll need to do the searching yourself or use one of the many libraries that provide the same functionality.

Also the code is lacking any error checking which should be added. (String not matching the regular expression, non existent months, etc.)

Python logging: use milliseconds in time format

If you prefer to use style='{', fmt="{asctime}.{msecs:0<3.0f}" will 0-pad your microseconds to three places for consistency.

Is a GUID unique 100% of the time?

In a more general sense, this is known as the "birthday problem" or "birthday paradox". Wikipedia has a pretty good overview at: Wikipedia - Birthday Problem

In very rough terms, the square root of the size of the pool is a rough approximation of when you can expect a 50% chance of a duplicate. The article includes a probability table of pool size and various probabilities, including a row for 2^128. So for a 1% probability of collision you would expect to randomly pick 2.6*10^18 128-bit numbers. A 50% chance requires 2.2*10^19 picks, while SQRT(2^128) is 1.8*10^19.

Of course, that is just the ideal case of a truly random process. As others mentioned, a lot is riding on the that random aspect - just how good is the generator and seed? It would be nice if there was some hardware support to assist with this process which would be more bullet-proof except that anything can be spoofed or virtualized. I suspect that might be the reason why MAC addresses/time-stamps are no longer incorporated.

"The operation is not valid for the state of the transaction" error and transaction scope

When I encountered this exception, there was an InnerException "Transaction Timeout". Since this was during a debug session, when I halted my code for some time inside the TransactionScope, I chose to ignore this issue.

When this specific exception with a timeout appears in deployed code, I think that the following section in you .config file will help you out:

<system.transactions> 
        <machineSettings maxTimeout="00:05:00" /> 
</system.transactions>

Is there a way to automatically build the package.json file for Node.js projects

1. Choice

If you git and GitHub user:

generate-package more simply, than npm init.

else

and/or you don't like package.json template, that generate-package or npm init generate:

you can generate your own template via scaffolding apps as generate, sails or yeoman.


2. Relevance

This answer is relevant for March 2018. In the future, the data from this answer may be obsolete.

Author of this answer personally used generate-package at March 2018.


3. Limitations

You need use git and GitHub for using generate-package.


4. Demonstration

For example, I create blank folder sasha-npm-init-vs-generate-package.

4.1. generate-package

Command:

D:\SashaDemoRepositories\sasha-npm-init-vs-generate-package>gen package
[16:58:52] starting generate
[16:59:01] v running tasks: [ 'package' ]
[16:59:04] starting package
? Project description? generate-package demo
? Author's name? Sasha Chernykh
? Author's URL? https://vk.com/hair_in_the_wind
[17:00:19] finished package v 1m

package.json:

{
  "name": "sasha-npm-init-vs-generate-package",
  "description": "generate-package demo",
  "version": "0.1.0",
  "homepage": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package",
  "author": "Sasha Chernykh (https://vk.com/hair_in_the_wind)",
  "repository": "Kristinita/sasha-npm-init-vs-generate-package",
  "bugs": {
    "url": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package/issues"
  },
  "license": "MIT",
  "engines": {
    "node": ">=4"
  },
  "scripts": {
    "test": "mocha"
  },
  "keywords": [
    "generate",
    "init",
    "npm",
    "package",
    "sasha",
    "vs"
  ]
}

4.2. npm init

D:\SashaDemoRepositories\sasha-npm-init-vs-generate-package>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (sasha-npm-init-vs-generate-package)
version: (1.0.0) 0.1.0
description: npm init demo
entry point: (index.js)
test command: mocha
git repository: https://github.com/Kristinita/sasha-npm-init-vs-generate-package
keywords: generate, package, npm, package, sasha, vs
author: Sasha Chernykh
license: (ISC) MIT
About to write to D:\SashaDemoRepositories\sasha-npm-init-vs-generate-package\package.json:

{
  "name": "sasha-npm-init-vs-generate-package",
  "version": "0.1.0",
  "description": "npm init demo",
  "main": "index.js",
  "scripts": {
    "test": "mocha"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/Kristinita/sasha-npm-init-vs-generate-package.git"
  },
  "keywords": [
    "generate",
    "package",
    "npm",
    "package",
    "sasha",
    "vs"
  ],
  "author": "Sasha Chernykh",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package/issues"
  },
  "homepage": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package#readme"
}


Is this ok? (yes) y
{
  "name": "sasha-npm-init-vs-generate-package",
  "version": "0.1.0",
  "description": "npm init demo",
  "main": "index.js",
  "scripts": {
    "test": "mocha"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/Kristinita/sasha-npm-init-vs-generate-package.git"
  },
  "keywords": [
    "generate",
    "package",
    "npm",
    "package",
    "sasha",
    "vs"
  ],
  "author": "Sasha Chernykh",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package/issues"
  },
  "homepage": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package#readme"
}

I think, that generate-package more simply, that npm init.


5. Customizing

That create your own package.json template, see generate and yeoman examples.

CSS3 Fade Effect

You can't transition between two background images, as there's no way for the browser to know what you want to interpolate. As you've discovered, you can transition the background position. If you want the image to fade in on mouse over, I think the best way to do it with CSS transitions is to put the image on a containing element and then animate the background colour to transparent on the link itself:

span {
    background: url(button.png) no-repeat 0 0;
}
a {
    width: 32px;
    height: 32px;
    text-align: left;
    background: rgb(255,255,255);

    -webkit-transition: background 300ms ease-in 200ms; /* property duration timing-function delay */
    -moz-transition: background 300ms ease-in 200ms;
    -o-transition: background 300ms ease-in 200ms;
    transition: background 300ms ease-in 200ms;
    }
a:hover {
    background: rgba(255,255,255,0);
}

Regex for Comma delimited list

It depends a bit on your exact requirements. I'm assuming: all numbers, any length, numbers cannot have leading zeros nor contain commas or decimal points. individual numbers always separated by a comma then a space, and the last number does NOT have a comma and space after it. Any of these being wrong would simplify the solution.

([1-9][0-9]*,[ ])*[1-9][0-9]*

Here's how I built that mentally:

[0-9]  any digit.
[1-9][0-9]*  leading non-zero digit followed by any number of digits
[1-9][0-9]*, as above, followed by a comma
[1-9][0-9]*[ ]  as above, followed by a space
([1-9][0-9]*[ ])*  as above, repeated 0 or more times
([1-9][0-9]*[ ])*[1-9][0-9]*  as above, with a final number that doesn't have a comma.

Playing sound notifications using Javascript?

Found something like that:

//javascript:
function playSound( url ){   
  document.getElementById("sound").innerHTML="<embed src='"+url+"' hidden=true autostart=true loop=false>";
} 

Is there an alternative sleep function in C to milliseconds?

#include <unistd.h>

int usleep(useconds_t useconds); //pass in microseconds

Git: how to reverse-merge a commit?

git reset --hard HEAD^ 

Use the above command to revert merge changes.

How do I display todays date on SSRS report?

Try this:

=FORMAT(Cdate(today), "dd-MM-yyyy")

or

=FORMAT(Cdate(today), "MM-dd-yyyy")

or

=FORMAT(Cdate(today), "yyyy-MM-dd")

or

=Report Generation Date: " & FORMAT(Cdate(today), "dd-MM-yyyy")

You should format the date in the same format your customer (internal or external) wants to see the date. For example In one of my servers it is running on American date format (MM-dd-yyyy) and on my reports I must ensure the dates displayed are European (yyyy-MM-dd).

Secondary axis with twinx(): how to add to legend?

You can easily add a second legend by adding the line:

ax2.legend(loc=0)

You'll get this:

enter image description here

But if you want all labels on one legend then you should do something like this:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

time = np.arange(10)
temp = np.random.random(10)*30
Swdown = np.random.random(10)*100-10
Rn = np.random.random(10)*100-10

fig = plt.figure()
ax = fig.add_subplot(111)

lns1 = ax.plot(time, Swdown, '-', label = 'Swdown')
lns2 = ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
lns3 = ax2.plot(time, temp, '-r', label = 'temp')

# added these three lines
lns = lns1+lns2+lns3
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc=0)

ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()

Which will give you this:

enter image description here

Add views in UIStackView programmatically

In my case the thing that was messing with I would expect was that I was missing this line:

stackView.translatesAutoresizingMaskIntoConstraints = false;

After that no need to set constraints to my arranged subviews whatsoever, the stackview is taking care of that.

Why does Java have transient fields?

To allow you to define variables that you don't want to serialize.

In an object you may have information that you don't want to serialize/persist (perhaps a reference to a parent factory object), or perhaps it doesn't make sense to serialize. Marking these as 'transient' means the serialization mechanism will ignore these fields.

How to convert QString to std::string?

If your ultimate aim is to get debugging messages to the console, you can use qDebug().

You can use like,

qDebug()<<string; which will print the contents to the console.

This way is better than converting it into std::string just for the sake of debugging messages.

Starting of Tomcat failed from Netbeans

For NetBeans to be able to interact with tomcat, it needs the user as setup in netbeans to be properly configured in the tomcat-users.xml file. NetBeans can do so automatically.

That is, within the tomcat-users.xml, which you can find in ${CATALINA_HOME}/conf, or ${CATALINA_BASE}/conf,

  1. make sure that the user (as chosen in netbeans) is added the script-manager role

Example, change

<user password="tomcat" roles="manager,admin" username="tomcat"/>

To

<user password="tomcat" roles="manager-script,manager,admin" username="tomcat"/>
  1. make sure that the manager-script role is declared

Add

<role rolename="manager-script"/>

Actually the netbeans online-help incorrectly states:

Username - Specifies the user name that the IDE uses to log into the server's manager application. The user must be associated with the manager role. The first time the IDE started the Tomcat Web Server, such as through the Start/Stop menu action or by executing a web component from the IDE, the IDE adds an admin user with a randomly-generated password to the tomcat-base-path/conf/tomcat-users.xml file. (Right-click the Tomcat Web server instance node in the Services window and select Properties. In the Properties dialog box, the Base Directory property points to the base-dir directory.) The admin user entry in the tomcat-users.xml file looks similar to the following: <user username="idea" password="woiehh" roles="manager"/>

The role should be manager-script, and not manager.

For a more complete tomcat-users.xml file:

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
  <role rolename="manager-script"/>
  <role rolename="manager-gui"/>
  <user password="tomcat" roles="manager-script" username="tomcat"/>
  <user password="pass" roles="manager-gui" username="me"/>
</tomcat-users>

There is another nice posting on why am I getting the deployment error?

PHP code to remove everything but numbers

Try this:

preg_replace('/[^0-9]/', '', '604-619-5135');

preg_replace uses PCREs which generally start and end with a /.

what happens when you type in a URL in browser

First the computer looks up the destination host. If it exists in local DNS cache, it uses that information. Otherwise, DNS querying is performed until the IP address is found.

Then, your browser opens a TCP connection to the destination host and sends the request according to HTTP 1.1 (or might use HTTP 1.0, but normal browsers don't do it any more).

The server looks up the required resource (if it exists) and responds using HTTP protocol, sends the data to the client (=your browser)

The browser then uses HTML parser to re-create document structure which is later presented to you on screen. If it finds references to external resources, such as pictures, css files, javascript files, these are is delivered the same way as the HTML document itself.

How do I raise the same Exception with a custom message in Python?

Python 3 built-in exceptions have the strerror field:

except ValueError as err:
  err.strerror = "New error message"
  raise err

How to use background thread in swift?

Good answers though, anyway I want to share my Object Oriented solution Up to date for swift 5.

please check it out: AsyncTask

Conceptually inspired by android's AsyncTask, I've wrote my own class in Swift

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread.

Here are few usage examples

Example 1 -

AsyncTask(backgroundTask: {(p:String)->Void in//set BGParam to String and BGResult to Void
        print(p);//print the value in background thread
    }).execute("Hello async");//execute with value 'Hello async'

Example 2 -

let task2=AsyncTask(beforeTask: {
           print("pre execution");//print 'pre execution' before backgroundTask
        },backgroundTask:{(p:Int)->String in//set BGParam to Int & BGResult to String
            if p>0{//check if execution value is bigger than zero
               return "positive"//pass String "poitive" to afterTask
            }
            return "negative";//otherwise pass String "negative"
        }, afterTask: {(p:String) in
            print(p);//print background task result
    });
    task2.execute(1);//execute with value 1

It has 2 generic types:

  • BGParam - the type of the parameter sent to the task upon execution.

  • BGResult - the type of the result of the background computation.

    When you create an AsyncTask you can those types to whatever you need to pass in and out of the background task, but if you don't need those types, you can mark it as unused with just setting it to: Void or with shorter syntax: ()

When an asynchronous task is executed, it goes through 3 steps:

  1. beforeTask:()->Void invoked on the UI thread just before the task is executed.
  2. backgroundTask: (param:BGParam)->BGResult invoked on the background thread immediately after
  3. afterTask:(param:BGResult)->Void invoked on the UI thread with result from the background task

POSTing JsonObject With HttpClient From Web API

the code over it in vbnet:

dim FeToSend as new (object--> define class)

Dim client As New HttpClient
Dim content = New StringContent(FeToSend.ToString(), Encoding.UTF8,"application/json")
content.Headers.ContentType = New MediaTypeHeaderValue( "application/json" )
Dim risp = client.PostAsync(Chiamata, content).Result

msgbox(risp.tostring)

Hope this help

Hide div after a few seconds

we can directly use

$('#selector').delay(5000).fadeOut('slow');

How to change the cursor into a hand when a user hovers over a list item?

Check the following. I get it from W3Schools.

_x000D_
_x000D_
.alias { cursor: alias; }
.all-scroll { cursor: all-scroll; }
.auto { cursor: auto; }
.cell { cursor: cell; }
.context-menu { cursor: context-menu; }
.col-resize { cursor: col-resize; }
.copy { cursor: copy; }
.crosshair { cursor: crosshair; }
.default { cursor: default; }
.e-resize { cursor: e-resize; }
.ew-resize { cursor: ew-resize; }
.grab {
  cursor: -webkit-grab;
  cursor: grab;
}
.grabbing {
  cursor: -webkit-grabbing;
  cursor: grabbing;
}
.help { cursor: help; }
.move { cursor: move; }
.n-resize { cursor: n-resize; }
.ne-resize { cursor: ne-resize; }
.nesw-resize { cursor: nesw-resize; }
.ns-resize { cursor: ns-resize; }
.nw-resize { cursor: nw-resize; }
.nwse-resize { cursor: nwse-resize; }
.no-drop { cursor: no-drop; }
.none { cursor: none; }
.not-allowed { cursor: not-allowed; }
.pointer { cursor: pointer; }
.progress { cursor: progress; }
.row-resize { cursor: row-resize; }
.s-resize { cursor: s-resize; }
.se-resize { cursor: se-resize; }
.sw-resize { cursor: sw-resize; }
.text { cursor: text; }
.url { cursor: url(myBall.cur), auto; }
.w-resize { cursor: w-resize; }
.wait { cursor: wait; }
.zoom-in { cursor: zoom-in; }
.zoom-out { cursor: zoom-out; }
_x000D_
<!DOCTYPE html>
<html>

<body>
  <h1>The cursor property</h1>
  <p>Mouse over the words to change the mouse cursor.</p>
  <p class="alias">alias</p>
  <p class="all-scroll">all-scroll</p>
  <p class="auto">auto</p>
  <p class="cell">cell</p>
  <p class="context-menu">context-menu</p>
  <p class="col-resize">col-resize</p>
  <p class="copy">copy</p>
  <p class="crosshair">crosshair</p>
  <p class="default">default</p>
  <p class="e-resize">e-resize</p>
  <p class="ew-resize">ew-resize</p>
  <p class="grab">grab</p>
  <p class="grabbing">grabbing</p>
  <p class="help">help</p>
  <p class="move">move</p>
  <p class="n-resize">n-resize</p>
  <p class="ne-resize">ne-resize</p>
  <p class="nesw-resize">nesw-resize</p>
  <p class="ns-resize">ns-resize</p>
  <p class="nw-resize">nw-resize</p>
  <p class="nwse-resize">nwse-resize</p>
  <p class="no-drop">no-drop</p>
  <p class="none">none</p>
  <p class="not-allowed">not-allowed</p>
  <p class="pointer">pointer</p>
  <p class="progress">progress</p>
  <p class="row-resize">row-resize</p>
  <p class="s-resize">s-resize</p>
  <p class="se-resize">se-resize</p>
  <p class="sw-resize">sw-resize</p>
  <p class="text">text</p>
  <p class="url">url</p>
  <p class="w-resize">w-resize</p>
  <p class="wait">wait</p>
  <p class="zoom-in">zoom-in</p>
  <p class="zoom-out">zoom-out</p>
</body>

</html>
_x000D_
_x000D_
_x000D_

What is the purpose of mvnw and mvnw.cmd files?

The Maven Wrapper is an excellent choice for projects that need a specific version of Maven (or for users that don't want to install Maven at all). Instead of installing many versions of it in the operating system, we can just use the project-specific wrapper script.

mvnw: it's an executable Unix shell script used in place of a fully installed Maven

mvnw.cmd: it's for Windows environment


Use Cases

The wrapper should work with different operating systems such as:

  • Linux
  • OSX
  • Windows
  • Solaris

After that, we can run our goals like this for the Unix system:

./mvnw clean install

And the following command for Batch:

./mvnw.cmd clean install

If we don't have the specified Maven in the wrapper properties, it'll be downloaded and installed in the folder $USER_HOME/.m2/wrapper/dists of the system.


Maven Wrapper plugin

Maven Wrapper plugin to make auto installation in a simple Spring Boot project.

First, we need to go in the main folder of the project and run this command:

mvn -N io.takari:maven:wrapper

We can also specify the version of Maven:

mvn -N io.takari:maven:wrapper -Dmaven=3.5.2

The option -N means –non-recursive so that the wrapper will only be applied to the main project of the current directory, not in any submodules.


Source 1 (further reading): https://www.baeldung.com/maven-wrapper

Replace all occurrences of a string in a data frame

late to the party. but if you only want to get rid of leading/trailing white space, R base has a function trimws

For example:

data <- apply(X = data, MARGIN = 2, FUN = trimws) %>% as.data.frame()

How to repeat a char using printf?

In c++ you could use std::string to get repeated character

printf("%s",std::string(count,char).c_str());

For example:

printf("%s",std::string(5,'a').c_str());

output:

aaaaa

How to change the bootstrap primary color?

This seem to work for me in Bootstrap v5 alpha 3

_variables-overrides.scss

$primary: #00adef;

$theme-colors: (
  "primary":    $primary,
);

main.scss

// Overrides
@import "variables-overrides";

// Required - Configuration
@import "@/node_modules/bootstrap/scss/functions";
@import "@/node_modules/bootstrap/scss/variables";
@import "@/node_modules/bootstrap/scss/mixins";
@import "@/node_modules/bootstrap/scss/utilities";

// Optional - Layout & components
@import "@/node_modules/bootstrap/scss/root";
@import "@/node_modules/bootstrap/scss/reboot";
@import "@/node_modules/bootstrap/scss/type";
@import "@/node_modules/bootstrap/scss/images";
@import "@/node_modules/bootstrap/scss/containers";
@import "@/node_modules/bootstrap/scss/grid";
@import "@/node_modules/bootstrap/scss/tables";
@import "@/node_modules/bootstrap/scss/forms";
@import "@/node_modules/bootstrap/scss/buttons";
@import "@/node_modules/bootstrap/scss/transitions";
@import "@/node_modules/bootstrap/scss/dropdown";
@import "@/node_modules/bootstrap/scss/button-group";
@import "@/node_modules/bootstrap/scss/nav";
@import "@/node_modules/bootstrap/scss/navbar";
@import "@/node_modules/bootstrap/scss/card";
@import "@/node_modules/bootstrap/scss/accordion";
@import "@/node_modules/bootstrap/scss/breadcrumb";
@import "@/node_modules/bootstrap/scss/pagination";
@import "@/node_modules/bootstrap/scss/badge";
@import "@/node_modules/bootstrap/scss/alert";
@import "@/node_modules/bootstrap/scss/progress";
@import "@/node_modules/bootstrap/scss/list-group";
@import "@/node_modules/bootstrap/scss/close";
@import "@/node_modules/bootstrap/scss/toasts";
@import "@/node_modules/bootstrap/scss/modal";
@import "@/node_modules/bootstrap/scss/tooltip";
@import "@/node_modules/bootstrap/scss/popover";
@import "@/node_modules/bootstrap/scss/carousel";
@import "@/node_modules/bootstrap/scss/spinners";

// Helpers
@import "@/node_modules/bootstrap/scss/helpers";

// Utilities
@import "@/node_modules/bootstrap/scss/utilities/api";

@import "custom";

Fixing "Lock wait timeout exceeded; try restarting transaction" for a 'stuck" Mysql table?

I had this problem when trying to delete a certain group of records (using MS Access 2007 with an ODBC connection to MySQL on a web server). Typically I would delete certain records from MySQL then replace with updated records (cascade delete several related records, this streamlines deleting all related records for a single record deletion).

I tried to run through the operations available in phpMyAdmin for the table (optimize,flush, etc), but I was getting a need permission to RELOAD error when I tried to flush. Since my database is on a web server, I couldn't restart the database. Restoring from a backup was not an option.

I tried running delete query for this group of records on the cPanel mySQL access on the web. Got same error message.

My solution: I used Sun's (Oracle's) free MySQL Query Browser (that I previously installed on my computer) and ran the delete query there. It worked right away, Problem solved. I was then able to once again perform the function using the Access script using the ODBC Access to MySQL connection.

Parse error: Syntax error, unexpected end of file in my PHP code

You should avoid this (at the end of your code):

{?>

and this:

<?php}

You shouldn't put brackets directly close to the open/close php tag, but separate it with a space:

{ ?>
<?php {

also avoid <? and use <?php

How can I get current location from user in iOS

iOS 11.x Swift 4.0 Info.plist needs these two properties

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>We're watching you</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Watch Out</string>

And this code ... making sure of course your a CLLocationManagerDelegate

let locationManager = CLLocationManager()

// MARK location Manager delegate code + more

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    switch status {
    case .notDetermined:
        print("User still thinking")
    case .denied:
        print("User hates you")
    case .authorizedWhenInUse:
            locationManager.stopUpdatingLocation()
    case .authorizedAlways:
            locationManager.startUpdatingLocation()
    case .restricted:
        print("User dislikes you")
    }

And of course this code too which you can put in viewDidLoad().

locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestLocation()

And these two for the requestLocation to get you going, aka save you having to get out of your seat :)

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print(error)
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    print(locations)
}

What is the difference between a "function" and a "procedure"?

This depends on the context.

In Pascal-like languages, functions and procedures are distinct entities, differing in whether they do or don't return a value. They behave differently wrt. the language syntax (eg. procedure calls form statements; you cannot use a procedure call inside an expression vs. function calls don't form statements, you must use them in other statements). Therefore, Pascal-bred programmers differentiate between those.

In C-like languages, and many other contemporary languages, this distinction is gone; in statically typed languages, procedures are just functions with a funny return type. This is probably why they are used interchangeably.

In functional languages, there is typically no such thing as a procedure - everything is a function.

Angular 2: Get Values of Multiple Checked Checkboxes

create a list like :-

this.xyzlist = [
  {
    id: 1,
    value: 'option1'
  },
  {
    id: 2,
    value: 'option2'
  }
];

Html :-

<div class="checkbox" *ngFor="let list of xyzlist">
            <label>
              <input formControlName="interestSectors" type="checkbox" value="{{list.id}}" (change)="onCheckboxChange(list,$event)">{{list.value}}</label>
          </div>

then in it's component ts :-

onCheckboxChange(option, event) {
     if(event.target.checked) {
       this.checkedList.push(option.id);
     } else {
     for(var i=0 ; i < this.xyzlist.length; i++) {
       if(this.checkedList[i] == option.id) {
         this.checkedList.splice(i,1);
      }
    }
  }
  console.log(this.checkedList);
}

SOAP Action WSDL

SOAPAction is required in SOAP 1.1 but can be empty ("").

See https://www.w3.org/TR/2000/NOTE-SOAP-20000508/#_Toc478383528

"The header field value of empty string ("") means that the intent of the SOAP message is provided by the HTTP Request-URI."

Try setting SOAPAction=""

How to add a Try/Catch to SQL Stored Procedure

Create Proc[usp_mquestions]  
( 
 @title  nvarchar(500),   --0
 @tags  nvarchar(max),   --1
 @category  nvarchar(200),   --2
 @ispoll  char(1),   --3
 @descriptions  nvarchar(max),   --4
)              
 AS  
 BEGIN TRY




BEGIN
DECLARE @message varchar(1000); 
DECLARE @tempid bigint; 

IF((SELECT count(id) from  [xyz] WHERE title=@title)>0)
BEGIN
SELECT 'record already existed.';
END
ELSE
BEGIN               


if @id=0 
begin 
select @tempid =id from [xyz] where id=@id;

if @tempid is null 
BEGIN 
        INSERT INTO xyz
        (entrydate,updatedate)
        VALUES
        (GETDATE(),GETDATE())

        SET @tempid=@@IDENTITY;
 END 
END 
ELSE 
BEGIN 
set @tempid=@id 
END 
if @tempid>0 
BEGIN 

    -- Updation of table begin--


UPDATE  tab_questions
set title=@title, --0 
 tags=@tags, --1 
 category=@category, --2 
 ispoll=@ispoll, --3 
 descriptions=@descriptions, --4 
 status=@status, --5

WHERE id=@tempid ; --9 ;


IF @id=0 
BEGIN 
SET @message= 'success:Record added successfully:'+ convert(varchar(10), @tempid)
END 
ELSE 
BEGIN 
SET @message= 'success:Record updated successfully.:'+ convert(varchar(10), @tempid)

END 
END 
ELSE 
BEGIN 
SET @message= 'failed:invalid request:'+convert(varchar(10), @tempid)
END 

END
END

END TRY
BEGIN CATCH
    SET @message='failed:'+ ERROR_MESSAGE();
END CATCH
SELECT @message;

How do you clear your Visual Studio cache on Windows Vista?

I had the same issue but when i deleted the cached items from Temp folder the build failed.

In order to make the build work again I had to close the project and reopen it.

CSS Margin: 0 is not setting to 0

Just use this code at the Start of the main CSS.

       * {
           margin: 0;
           padding: 0;
         }

The above code works in almost all Browsers.

How to draw a custom UIView that is just a circle - iPhone app

Another way of approaching circle (and other shapes) drawing is by using masks. You draw circles or other shapes by, first, making masks of the shapes you need, second, provide squares of your color and, third, apply masks to those squares of color. You can change either mask or color to get a new custom circle or other shape.

#import <QuartzCore/QuartzCore.h>

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *area1;
@property (weak, nonatomic) IBOutlet UIView *area2;
@property (weak, nonatomic) IBOutlet UIView *area3;
@property (weak, nonatomic) IBOutlet UIView *area4;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.area1.backgroundColor = [UIColor blueColor];
    [self useMaskFor: self.area1];

    self.area2.backgroundColor = [UIColor orangeColor];
    [self useMaskFor: self.area2];

    self.area3.backgroundColor = [UIColor colorWithRed: 1.0 green: 0.0 blue: 0.5 alpha:1.0];
    [self useMaskFor: self.area3];

    self.area4.backgroundColor = [UIColor colorWithRed: 1.0 green: 0.0 blue: 0.5 alpha:0.5];
    [self useMaskFor: self.area4];        
}

- (void)useMaskFor: (UIView *)colorArea {        
    CALayer *maskLayer = [CALayer layer];
    maskLayer.frame = colorArea.bounds;
    UIImage *maskImage = [UIImage imageNamed:@"cirMask.png"];
    maskLayer.contents = (__bridge id)maskImage.CGImage;
    colorArea.layer.mask = maskLayer;
}

@end

Here is the output of the code above:

four circles

.gitignore exclude folder but include specific subfolder

Add an additional answer:

!/.vs/              <== include this folder to source control, folder only, nothing else
/.vs/*              <== but ignore all files and sub-folder inside this folder
!/.vs/ProjectSettings.json <== but include this file to source control
!/.vs/config/       <== then include this folder to source control, folder only, nothing else
!/.vs/config/*      <== then include all files inside the folder

here is result:

enter image description here

Open file by its full path in C++

A different take on this question, which might help someone:

I came here because I was debugging in Visual Studio on Windows, and I got confused about all this / vs \\ discussion (it really should not matter in most cases).

For me, the problem was: the "current directory" was not set to what I wanted in Visual Studio. It defaults to the directory of the executable (depending on how you set up your project).

Change it via: Right-click the solution -> Properties -> Working Directory

I only mention it because the question seems Windows-centric, which generally also means VisualStudio-centric, which tells me this hint might be relevant (:

Can I catch multiple Java exceptions in the same catch clause?

Not exactly before Java 7 but, I would do something like this:

Java 6 and before

try {
  //.....
} catch (Exception exc) {
  if (exc instanceof IllegalArgumentException || exc instanceof SecurityException || 
     exc instanceof IllegalAccessException || exc instanceof NoSuchFieldException ) {

     someCode();

  } else if (exc instanceof RuntimeException) {
     throw (RuntimeException) exc;     

  } else {
    throw new RuntimeException(exc);
  }

}



Java 7

try {
  //.....
} catch ( IllegalArgumentException | SecurityException |
         IllegalAccessException |NoSuchFieldException exc) {
  someCode();
}

Count number of vector values in range with R

There are also the %<% and %<=% comparison operators in the TeachingDemos package which allow you to do this like:

sum( 2 %<% x %<% 5 )
sum( 2 %<=% x %<=% 5 )

which gives the same results as:

sum( 2 < x & x < 5 )
sum( 2 <= x & x <= 5 )

Which is better is probably more a matter of personal preference.

Java equivalent to JavaScript's encodeURIComponent that produces identical output?

Guava library has PercentEscaper:

Escaper percentEscaper = new PercentEscaper("-_.*", false);

"-_.*" are safe characters

false says PercentEscaper to escape space with '%20', not '+'

Check if a string is palindrome

bool IsPalindrome(const char* psz)
{
    int i = 0;
    int j;

    if ((psz == NULL) || (psz[0] == '\0'))
    {
        return false;
    }

    j = strlen(psz) - 1;
    while (i < j)
    {
        if (psz[i] != psz[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;

}

// STL string version:

bool IsPalindrome(const string& str)
{
    if (str.empty())
        return false;

    int i = 0;                // first characters
    int j = str.length() - 1; // last character

    while (i < j)
    {
        if (str[i] != str[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;
}

Node.js – events js 72 throw er unhandled 'error' event

Close nodejs app running in another shell. Restart the terminal and run the program again.


Another server might be also using the same port that you have used for nodejs. Kill the process that is using nodejs port and run the app.

To find the PID of the application that is using port:8000

$ fuser 8000/tcp
8000/tcp:            16708

Here PID is 16708 Now kill the process using the kill [PID] command

$ kill 16708

split string only on first instance - java

String string = "This is test string on web";
String splitData[] = string.split("\\s", 2);

Result ::
splitData[0] =>  This
splitData[1] =>  is test string  


String string = "This is test string on web";
String splitData[] = string.split("\\s", 3);

Result ::
splitData[0] =>  This
splitData[1] =>  is
splitData[1] =>  test string on web

By default split method create n number's of arrays on the basis of given regex. But if you want to restrict number of arrays to create after a split than pass second argument as an integer argument.

Java AES and using my own Key

Edit:

As written in the comments the old code is not "best practice". You should use a keygeneration algorithm like PBKDF2 with a high iteration count. You also should use at least partly a non static (meaning for each "identity" exclusive) salt. If possible randomly generated and stored together with the ciphertext.

    SecureRandom sr = SecureRandom.getInstanceStrong();
    byte[] salt = new byte[16];
    sr.nextBytes(salt);

    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 1000, 128 * 8);
    SecretKey key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec);
    Cipher aes = Cipher.getInstance("AES");
    aes.init(Cipher.ENCRYPT_MODE, key);

===========

Old Answer

You should use SHA-1 to generate a hash from your key and trim the result to 128 bit (16 bytes).

Additionally don't generate byte arrays from Strings through getBytes() it uses the platform default Charset. So the password "blaöä" results in different byte array on different platforms.

byte[] key = (SALT2 + username + password).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit

SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");

Edit: If you need 256 bit as key sizes you need to download the "Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files" Oracle download link, use SHA-256 as hash and remove the Arrays.copyOf line. "ECB" is the default Cipher Mode and "PKCS5Padding" the default padding. You could use different Cipher Modes and Padding Modes through the Cipher.getInstance string using following format: "Cipher/Mode/Padding"

For AES using CTS and PKCS5Padding the string is: "AES/CTS/PKCS5Padding"

Call method when home button pressed

The Home button is a very dangerous button to override and, because of that, Android will not let you override its behavior the same way you do the BACK button.

Take a look at this discussion.

You will notice that the home button seems to be implemented as a intent invocation, so you'll end up having to add an intent category to your activity. Then, any time the user hits home, your app will show up as an option. You should consider what it is you are looking to accomplish with the home button. If its not to replace the default home screen of the device, I would be wary of overloading the HOME button, but it is possible (per discussion in above thread.)

Identifying and removing null characters in UNIX

If the lines in the file end with \r\n\000 then what works is to delete the \n\000 then replace the \r with \n.

tr -d '\n\000' <infile | tr '\r' '\n' >outfile

Python data structure sort list alphabetically

You're dealing with a python list, and sorting it is as easy as doing this.

my_list = ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']
my_list.sort()

How do I get a PHP class constructor to call its parent's parent's constructor?

Funny detail about php: extended classes can use non-static functions of a parent class in a static matter. Outside you will get a strict error.

error_reporting(E_ALL);

class GrandPa
{
    public function __construct()
    {
        print("construct grandpa<br/>");
        $this->grandPaFkt();
    }

    protected function grandPaFkt(){
        print(">>do Grandpa<br/>");
    }
}

class Pa extends GrandPa
{
    public function __construct()
    {   parent::__construct();
        print("construct Pa <br/>");
    }

    public function paFkt(){
        print(">>do Pa <br>");
    }
}

class Child extends Pa
{
    public function __construct()
    {
        GrandPa::__construct();
        Pa::paFkt();//allright
        //parent::__construct();//whatever you want
        print("construct Child<br/>");
    }

}

$test=new Child();
$test::paFkt();//strict error 

So inside a extended class (Child) you can use

parent::paFkt(); 

or

Pa::paFkt();

to access a parent (or grandPa's) (not private) function.

Outside class def

$test::paFkt();

will trow strict error (non static function).

How to create a cron job using Bash automatically without the interactive editor?

echo "0 * * * * docker system prune --force >/dev/null 2>&1" | sudo tee /etc/cron.daily/dockerprune

How to plot all the columns of a data frame in R

You can jump through hoops and convert your solution to a lapply, sapply or apply call. (I see @jonw shows one way to do this.) Other than that what you have already is perfectly acceptable code.

If these are all a time series or similar then the following might be a suitable alternative, which plots each series in it's own panel on a single plotting region. We use the zoo package as it handles ordered data like this very well indeed.

require(zoo)
set.seed(1)
## example data
dat <- data.frame(X = cumsum(rnorm(100)), Y = cumsum(rnorm(100)),
                  Z = cumsum(rnorm(100)))
## convert to multivariate zoo object
datz <- zoo(dat)
## plot it
plot(datz)

Which gives: Example of zoo plotting capabilities

Is Java's assertEquals method reliable?

The JUnit assertEquals(obj1, obj2) does indeed call obj1.equals(obj2).

There's also assertSame(obj1, obj2) which does obj1 == obj2 (i.e., verifies that obj1 and obj2 are referencing the same instance), which is what you're trying to avoid.

So you're fine.

@synthesize vs @dynamic, what are the differences?

Take a look at this article; under the heading "Methods provided at runtime":

Some accessors are created dynamically at runtime, such as certain ones used in CoreData's NSManagedObject class. If you want to declare and use properties for these cases, but want to avoid warnings about methods missing at compile time, you can use the @dynamic directive instead of @synthesize.

...

Using the @dynamic directive essentially tells the compiler "don't worry about it, a method is on the way."

The @synthesize directive, on the other hand, generates the accessor methods for you at compile time (although as noted in the "Mixing Synthesized and Custom Accessors" section it is flexible and does not generate methods for you if either are implemented).

What is Node.js?

Also, do not forget to mention that Google's V8 is VERY fast. It actually converts the JavaScript code to machine code with the matched performance of compiled binary. So along with all the other great things, it's INSANELY fast.

Get contentEditable caret index position

A straight forward way, that iterates through all the chidren of the contenteditable div until it hits the endContainer. Then I add the end container offset and we have the character index. Should work with any number of nestings. uses recursion.

Note: requires a poly fill for ie to support Element.closest('div[contenteditable]')

https://codepen.io/alockwood05/pen/vMpdmZ

function caretPositionIndex() {
    const range = window.getSelection().getRangeAt(0);
    const { endContainer, endOffset } = range;

    // get contenteditableDiv from our endContainer node
    let contenteditableDiv;
    const contenteditableSelector = "div[contenteditable]";
    switch (endContainer.nodeType) {
      case Node.TEXT_NODE:
        contenteditableDiv = endContainer.parentElement.closest(contenteditableSelector);
        break;
      case Node.ELEMENT_NODE:
        contenteditableDiv = endContainer.closest(contenteditableSelector);
        break;
    }
    if (!contenteditableDiv) return '';


    const countBeforeEnd = countUntilEndContainer(contenteditableDiv, endContainer);
    if (countBeforeEnd.error ) return null;
    return countBeforeEnd.count + endOffset;

    function countUntilEndContainer(parent, endNode, countingState = {count: 0}) {
      for (let node of parent.childNodes) {
        if (countingState.done) break;
        if (node === endNode) {
          countingState.done = true;
          return countingState;
        }
        if (node.nodeType === Node.TEXT_NODE) {
          countingState.count += node.length;
        } else if (node.nodeType === Node.ELEMENT_NODE) {
          countUntilEndContainer(node, endNode, countingState);
        } else {
          countingState.error = true;
        }
      }
      return countingState;
    }
  }

Jenkins Git Plugin: How to build specific tag?

Can't you tell Jenkins to build from a Ref name? If so then it's

refs/tags/tag-name

From all the questions I see about Jenkins and Hudson, I'd suggest switching to TeamCity. I haven't had to edit any configuration files to get TeamCity to work.

Javascript Src Path

As your clock.js is in the root, put your code as this to call your javascript in the index.html found in the folders you mentioned.

<SCRIPT LANGUAGE="JavaScript" SRC="../clock.js"></SCRIPT>

This will call the clock.js which you put in the root of your web site.

Comparing double values in C#

Use decimal. It doesn't have this "problem".

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

create unique id with javascript

I think if you really want to have a unique ID then the best approach is to use a library like:
uuid or uniqueid

Note: Unique ID is not the same as Random ID

To use only date time milliseconds approach is wrong.
Nowadays computers are fast enough and able to run more than one iteration of a loop in a single millisecond.

npm install uuid

Importing the library:

If you are using ES modules

import { v4 as uuidv4 } from 'uuid';

And for CommonJS:

const { v4: uuidv4 } = require('uuid');

Usage:

uuidv4();

// This will output something like: 9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d

Android Studio-No Module

If you have imported the project, you may have to re-import it the proper way.
Steps :

  1. Close Android Studio. Take backup of the project from C:\Users\UserName\AndroidStudioProjects\YourProject to some other folder . Now delete the project.
  2. Launch Android Studio and click "Import Non-AndroidStudio Project (even if the project to be imported is an AndroidStudio project).
  3. Select only the root folder of the project to be imported. Set the destination directory. Keep all the options checked. AndroidStudio will prompt to make some changes, click Ok for all prompts.
  4. Now you can see the Module pre-defined at the top and you can launch the app to the emulator.

Tested on AndroidStudio version 1.0.1

How to add form validation pattern in Angular 2?

You could build your form using FormBuilder as it let you more flexible way to configure form.

export class MyComp {
  form: ControlGroup;

  constructor(@Inject()fb: FormBuilder) {  
    this.form = fb.group({  
      foo: ['', MyValidators.regex(/^(?!\s|.*\s$).*$/)]  
    });  
  }

Then in your template :

<input type="text" ngControl="foo" />
<div *ngIf="!form.foo.valid">Please correct foo entry !</div> 

You can also customize ng-invalid CSS class.

As there is actually no validators for regex, you have to write your own. It is a simple function that takes a control in input, and return null if valid or a StringMap if invalid.

export class MyValidators {
  static regex(pattern: string): Function {
    return (control: Control): {[key: string]: any} => {
      return control.value.match(pattern) ? null : {pattern: true};
    };
  }
}

Hope that it help you.

Jest spyOn function called

You were almost done without any changes besides how you spyOn. When you use the spy, you have two options: spyOn the App.prototype, or component component.instance().

const spy = jest.spyOn(Class.prototype, "method")

The order of attaching the spy on the class prototype and rendering (shallow rendering) your instance is important.

const spy = jest.spyOn(App.prototype, "myClickFn");
const instance = shallow(<App />);

The App.prototype bit on the first line there are what you needed to make things work. A JavaScript class doesn't have any of its methods until you instantiate it with new MyClass(), or you dip into the MyClass.prototype. For your particular question, you just needed to spy on the App.prototype method myClickFn.

jest.spyOn(component.instance(), "method")

const component = shallow(<App />);
const spy = jest.spyOn(component.instance(), "myClickFn");

This method requires a shallow/render/mount instance of a React.Component to be available. Essentially spyOn is just looking for something to hijack and shove into a jest.fn(). It could be:

A plain object:

const obj = {a: x => (true)};
const spy = jest.spyOn(obj, "a");

A class:

class Foo {
    bar() {}
}

const nope = jest.spyOn(Foo, "bar");
// THROWS ERROR. Foo has no "bar" method.
// Only an instance of Foo has "bar".
const fooSpy = jest.spyOn(Foo.prototype, "bar");
// Any call to "bar" will trigger this spy; prototype or instance

const fooInstance = new Foo();
const fooInstanceSpy = jest.spyOn(fooInstance, "bar");
// Any call fooInstance makes to "bar" will trigger this spy.

Or a React.Component instance:

const component = shallow(<App />);
/*
component.instance()
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(component.instance(), "myClickFn");

Or a React.Component.prototype:

/*
App.prototype
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(App.prototype, "myClickFn");
// Any call to "myClickFn" from any instance of App will trigger this spy.

I've used and seen both methods. When I have a beforeEach() or beforeAll() block, I might go with the first approach. If I just need a quick spy, I'll use the second. Just mind the order of attaching the spy.

EDIT: If you want to check the side effects of your myClickFn you can just invoke it in a separate test.

const app = shallow(<App />);
app.instance().myClickFn()
/*
Now assert your function does what it is supposed to do...
eg.
expect(app.state("foo")).toEqual("bar");
*/

EDIT: Here is an example of using a functional component. Keep in mind that any methods scoped within your functional component are not available for spying. You would be spying on function props passed into your functional component and testing the invocation of those. This example explores the use of jest.fn() as opposed to jest.spyOn, both of which share the mock function API. While it does not answer the original question, it still provides insight on other techniques that could suit cases indirectly related to the question.

function Component({ myClickFn, items }) {
   const handleClick = (id) => {
       return () => myClickFn(id);
   };
   return (<>
       {items.map(({id, name}) => (
           <div key={id} onClick={handleClick(id)}>{name}</div>
       ))}
   </>);
}

const props = { myClickFn: jest.fn(), items: [/*...{id, name}*/] };
const component = render(<Component {...props} />);
// Do stuff to fire a click event
expect(props.myClickFn).toHaveBeenCalledWith(/*whatever*/);

How to center a (background) image within a div?

try background-position:center;

EDIT: since this question is getting lots of views, its worth adding some extra info:

text-align: center will not work because the background image is not part of the document and is therefore not part of the flow.

background-position:center is shorthand for background-position: center center; (background-position: horizontal vertical);

C# Base64 String to JPEG Image

First, convert the base 64 string to an Image, then use the Image.Save method.

To convert from base 64 string to Image:

 public Image Base64ToImage(string base64String)
 {
    // Convert base 64 string to byte[]
    byte[] imageBytes = Convert.FromBase64String(base64String);
    // Convert byte[] to Image
    using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
    {
        Image image = Image.FromStream(ms, true);
        return image;
    }
 }

To convert from Image to base 64 string:

public string ImageToBase64(Image image,System.Drawing.Imaging.ImageFormat format)
{
  using (MemoryStream ms = new MemoryStream())
  {
    // Convert Image to byte[]
    image.Save(ms, format);
    byte[] imageBytes = ms.ToArray();

    // Convert byte[] to base 64 string
    string base64String = Convert.ToBase64String(imageBytes);
    return base64String;
  }
}

Finally, you can easily to call Image.Save(filePath); to save the image.

@RequestBody and @ResponseBody annotations in Spring

package com.programmingfree.springshop.controller;

import java.util.List;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.programmingfree.springshop.dao.UserShop;
import com.programmingfree.springshop.domain.User;


@RestController
@RequestMapping("/shop/user")
public class SpringShopController {

 UserShop userShop=new UserShop();

 @RequestMapping(value = "/{id}", method = RequestMethod.GET,headers="Accept=application/json")
 public User getUser(@PathVariable int id) {
  User user=userShop.getUserById(id);
  return user;
 }


 @RequestMapping(method = RequestMethod.GET,headers="Accept=application/json")
 public List<User> getAllUsers() {
  List<User> users=userShop.getAllUsers();
  return users;
 }


}

In the above example they going to display all user and particular id details now I want to use both id and name,

1) localhost:8093/plejson/shop/user <---this link will display all user details
2) localhost:8093/plejson/shop/user/11 <----if i use 11 in link means, it will display particular user 11 details

now I want to use both id and name

localhost:8093/plejson/shop/user/11/raju <-----------------like this it means we can use any one in this please help me out.....

How can I make a TextBox be a "password box" and display stars when using MVVM?

To get or set the Password in a PasswordBox, use the Password property. Such as

string password = PasswordBox.Password;

This doesn't support Databinding as far as I know, so you'd have to set the value in the codebehind, and update it accordingly.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)

The client should be set consistent with server setting.

[client]
port        = 3306
socket      = /var/run/mysqld/mysqld.sock

[mysqld]
user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306

Check if xdebug is working

Run

php -m -c

in your terminal, and then look for [Zend Modules]. It should be somewhere there if it is loaded!

NB

If you're using Ubuntu, it may not show up here because you need to add the xdebug settings from /etc/php5/apache2/php.ini into /etc/php5/cli/php.ini. Mine are

[xdebug]
zend_extension = /usr/lib/php5/20121212/xdebug.so
xdebug.remote_enable=on
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_host=localhost
xdebug.remote_port=9000

AngularJS UI Router - change url without reloading state

Simply you can use $state.transitionTo instead of $state.go . $state.go calls $state.transitionTo internally but automatically sets options to { location: true, inherit: true, relative: $state.$current, notify: true } . You can call $state.transitionTo and set notify: false . For example:

$state.go('.detail', {id: newId}) 

can be replaced by

$state.transitionTo('.detail', {id: newId}, {
    location: true,
    inherit: true,
    relative: $state.$current,
    notify: false
})

Edit: As suggested by fracz it can simply be:

$state.go('.detail', {id: newId}, {notify: false}) 

Render HTML in React Native

An iOS/Android pure javascript react-native component that renders your HTML into 100% native views. It's made to be extremely customizable and easy to use and aims at being able to render anything you throw at it.

react-native-render-html

use above library to improve your app performance level and easy to use.

Install

npm install react-native-render-html --save or yarn add react-native-render-html

Basic usage

import React, { Component } from 'react';
import { ScrollView, Dimensions } from 'react-native';
import HTML from 'react-native-render-html';

const htmlContent = `
    <h1>This HTML snippet is now rendered with native components !</h1>
    <h2>Enjoy a webview-free and blazing fast application</h2>
    <img src="https://i.imgur.com/dHLmxfO.jpg?2" />
    <em style="textAlign: center;">Look at how happy this native cat is</em>
`;

export default class Demo extends Component {
    render () {
        return (
            <ScrollView style={{ flex: 1 }}>
                <HTML html={htmlContent} imagesMaxWidth={Dimensions.get('window').width} />
            </ScrollView>
        );
    }
}

PROPS

you may user it's different different types of props (see above link) for the designing and customizable also using below link refer.

Customizable render html

Replace Div Content onclick

Try This:

I think that you want something like this.

HTML:

<div id="1">
    My Content 1
</div>

<div id="2" style="display:none;">
    My Dynamic Content
</div>
<button id="btnClick">Click me!</button>

jQuery:

$('#btnClick').on('click',function(){
if($('#1').css('display')!='none'){
$('#2').show().siblings('div').hide();
}else if($('#2').css('display')!='none'){
    $('#1').show().siblings('div').hide();
}
});


JsFiddle:
http://jsfiddle.net/ha6qp7w4/1113/ <--- see this I hope You want something like this.

Check if a value is within a range of numbers

If you must use a regexp (and really, you shouldn't!) this will work:

/^0\.00([1-8]\d*|90*)$/

should work, i.e.

  • ^ nothing before,
  • followed by 0.00 (nb: backslash escape for the . character)
  • followed by 1 through 8, and any number of additional digits
  • or 9, followed by any number of zeroes
  • $: followed by nothing else

I have never set any passwords to my keystore and alias, so how are they created?

Signing in Debug Mode

The Android build tools provide a debug signing mode that makes it easier for you to develop and debug your application, while still meeting the Android system requirement for signing your APK. When using debug mode to build your app, the SDK tools invoke Keytool to automatically create a debug keystore and key. This debug key is then used to automatically sign the APK, so you do not need to sign the package with your own key.

The SDK tools create the debug keystore/key with predetermined names/passwords:

Keystore name: "debug.keystore"
Keystore password: "android"
Key alias: "androiddebugkey"
Key password: "android"
CN: "CN=Android Debug,O=Android,C=US"

If necessary, you can change the location/name of the debug keystore/key or supply a custom debug keystore/key to use. However, any custom debug keystore/key must use the same keystore/key names and passwords as the default debug key (as described above). (To do so in Eclipse/ADT, go to Windows > Preferences > Android > Build.)

Caution: You cannot release your application to the public when signed with the debug certificate.

Source: Developer.Android

type object 'datetime.datetime' has no attribute 'datetime'

Datetime is a module that allows for handling of dates, times and datetimes (all of which are datatypes). This means that datetime is both a top-level module as well as being a type within that module. This is confusing.

Your error is probably based on the confusing naming of the module, and what either you or a module you're using has already imported.

>>> import datetime
>>> datetime
<module 'datetime' from '/usr/lib/python2.6/lib-dynload/datetime.so'>
>>> datetime.datetime(2001,5,1)
datetime.datetime(2001, 5, 1, 0, 0)

But, if you import datetime.datetime:

>>> from datetime import datetime
>>> datetime
<type 'datetime.datetime'>
>>> datetime.datetime(2001,5,1) # You shouldn't expect this to work 
                                # as you imported the type, not the module
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
>>> datetime(2001,5,1)
datetime.datetime(2001, 5, 1, 0, 0)

I suspect you or one of the modules you're using has imported like this: from datetime import datetime.

No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?

In my case I forgot to add @RequestBody annotation to the method argument:

public TestController(@RequestBody KeeperClient testClient) {
        TestController.testClient = testClient;
    }

pip install returning invalid syntax

The problem is the OS can’t find Pip. Pip helps you install packages MODIFIED SOME GREAT ANSWERS TO BE BETTER

Method 1 Go to path of python, then search for pip

  1. open cmd.exe
  2. write the following command:

E.g

cd C:\Users\Username\AppData\Local\Programs\Python\Python37-32

In this directory, search pip with python -m pip then install package

E.g

python -m pip install ipywidgets

-m module-name Searches sys.path for the named module and runs the corresponding .py file as a script.

OR

GO TO scripts from CMD. This is where Pip stays :)

cd C:\Users\User name\AppData\Local\Programs\Python\Python37-32\Scripts>

Then

pip install anypackage

VirtualBox and vmdk vmx files

VMDK/VMX are VMWare file formats but you can use it with VirtualBox:

  1. Create a new Virtual Machine and when asks for a hard disk choose "Use an existing hard disk"
  2. Click on the "button with folder and green arrow image on the combo box right" which opens Virtual Media Manager, it looks like this (you can open it directly pressing CTRL+D on main window or in File > Virtual Media Manager menu)...
  3. Then you can add the VMDK/VMX hard disk image and setup it for your virtual machine :)

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

How do you see the entire command history in interactive Python?

Code for printing the entire history:

Python 3

One-liner (quick copy and paste):

import readline; print('\n'.join([str(readline.get_history_item(i + 1)) for i in range(readline.get_current_history_length())]))

(Or longer version...)

import readline
for i in range(readline.get_current_history_length()):
    print (readline.get_history_item(i + 1))

Python 2

One-liner (quick copy and paste):

import readline; print '\n'.join([str(readline.get_history_item(i + 1)) for i in range(readline.get_current_history_length())])

(Or longer version...)

import readline
for i in range(readline.get_current_history_length()):
    print readline.get_history_item(i + 1)

Note: get_history_item() is indexed from 1 to n.

Fragment onResume() & onPause() is not called on backstack

onPause() method works in activity class you can use:

public void onDestroyView(){
super.onDestroyView    
}

for same purpose..

Windows batch files: .bat vs .cmd?

.cmd and .bat file execution is different because in a .cmd errorlevel variable it can change on a command that is affected by command extensions. That's about it really.

How to make a <svg> element expand or contract to its parent container?

The viewBox isn't the height of the container, it's the size of your drawing. Define your viewBox to be 100 units in width, then define your rect to be 10 units. After that, however large you scale the SVG, the rect will be 10% the width of the image.

How to install a specific version of Node on Ubuntu?

The n module worked for me.

Run this code to clear npm’s cache, install n, and install the latest stable version of Node:

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

See: http://www.hostingadvice.com/how-to/update-node-js-latest-version/
And: https://www.npmjs.com/package/n

To install a specific version of node:

sudo n 6.11.2

To check what version:

node -v

You might need to restart

How to find the kth largest element in an unsorted array of length n in O(n)?

There is also Wirth's selection algorithm, which has a simpler implementation than QuickSelect. Wirth's selection algorithm is slower than QuickSelect, but with some improvements it becomes faster.

In more detail. Using Vladimir Zabrodsky's MODIFIND optimization and the median-of-3 pivot selection and paying some attention to the final steps of the partitioning part of the algorithm, i've came up with the following algorithm (imaginably named "LefSelect"):

#define F_SWAP(a,b) { float temp=(a);(a)=(b);(b)=temp; }

# Note: The code needs more than 2 elements to work
float lefselect(float a[], const int n, const int k) {
    int l=0, m = n-1, i=l, j=m;
    float x;

    while (l<m) {
        if( a[k] < a[i] ) F_SWAP(a[i],a[k]);
        if( a[j] < a[i] ) F_SWAP(a[i],a[j]);
        if( a[j] < a[k] ) F_SWAP(a[k],a[j]);

        x=a[k];
        while (j>k & i<k) {
            do i++; while (a[i]<x);
            do j--; while (a[j]>x);

            F_SWAP(a[i],a[j]);
        }
        i++; j--;

        if (j<k) {
            while (a[i]<x) i++;
            l=i; j=m;
        }
        if (k<i) {
            while (x<a[j]) j--;
            m=j; i=l;
        }
    }
    return a[k];
}

In benchmarks that i did here, LefSelect is 20-30% faster than QuickSelect.

Save Javascript objects in sessionStorage

You can create 2 wrapper methods for saving and retrieving object from session storage.

function saveSession(obj) {
  sessionStorage.setItem("myObj", JSON.stringify(obj));
  return true;
}

function getSession() {
  var obj = {};
  if (typeof sessionStorage.myObj !== "undefined") {
    obj = JSON.parse(sessionStorage.myObj);
  }
  return obj;
}

Use it like this:- Get object, modify some data, and save back.

var obj = getSession();

obj.newProperty = "Prod"

saveSession(obj);

Best Practice for Forcing Garbage Collection in C#

Look at it this way - is it more efficient to throw out the kitchen garbage when the garbage can is at 10% or let it fill up before taking it out?

By not letting it fill up, you are wasting your time walking to and from the garbage bin outside. This analogous to what happens when the GC thread runs - all the managed threads are suspended while it is running. And If I am not mistaken, the GC thread can be shared among multiple AppDomains, so garbage collection affects all of them.

Of course, you might encounter a situation where you won't be adding anything to the garbage can anytime soon - say, if you're going to take a vacation. Then, it would be a good idea to throw out the trash before going out.

This MIGHT be one time that forcing a GC can help - if your program idles, the memory in use is not garbage-collected because there are no allocations.

String to list in Python

Maybe like this:

list('abcdefgh') # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

Break promise chain and call a function based on the step in the chain where it is broken (rejected)

What you need is a repeating .then() chain with a special case to start and a special case to finish.

The knack is to get the step number of the failure case to ripple through to a final error handler.

  • Start: call step(1) unconditionally.
  • Repeating pattern: chain a .then() with the following callbacks:
    • success: call step(n+1)
    • failure: throw the value with which the previous deferered was rejected or rethrow the error.
  • Finish: chain a .then() with no success handler and a final error handler.

You can write the whole thing out longhand but it's easier to demonstrate the pattern with named, generalised functions :

function nextStep(n) {
    return step(n + 1);
}

function step(n) {
    console.log('step ' + n);
    var deferred = $q.defer();
    (n === 3) ? deferred.reject(n) : deferred.resolve(n);
    return deferred.promise;
}

function stepError(n) {
    throw(n);
}

function finalError(n) {
    console.log('finalError ' + n);
}
step(1)
    .then(nextStep, stepError)
    .then(nextStep, stepError)
    .then(nextStep, stepError)
    .then(nextStep, stepError)
    .then(nextStep, stepError)
    .then(null, finalError);});

see demo

Note how in step(), the deferred is rejected or resolved with n, thus making that value available to the callbacks in the next .then() in the chain. Once stepError is called, the error is repeatedly rethrown until it is handled by finalError.

Deep copy vs Shallow Copy

The quintessential example of this is an array of pointers to structs or objects (that are mutable).

A shallow copy copies the array and maintains references to the original objects.

A deep copy will copy (clone) the objects too so they bear no relation to the original. Implicit in this is that the object themselves are deep copied. This is where it gets hard because there's no real way to know if something was deep copied or not.

The copy constructor is used to initilize the new object with the previously created object of the same class. By default compiler wrote a shallow copy. Shallow copy works fine when dynamic memory allocation is not involved because when dynamic memory allocation is involved then both objects will points towards the same memory location in a heap, Therefore to remove this problem we wrote deep copy so both objects have their own copy of attributes in a memory.

In order to read the details with complete examples and explanations you could see the article Constructors and destructors.

The default copy constructor is shallow. You can make your own copy constructors deep or shallow, as appropriate. See C++ Notes: OOP: Copy Constructors.

How can I read and manipulate CSV file data in C++?

If what you're really doing is manipulating a CSV file itself, Nelson's answer makes sense. However, my suspicion is that the CSV is simply an artifact of the problem you're solving. In C++, that probably means you have something like this as your data model:

struct Customer {
    int id;
    std::string first_name;
    std::string last_name;
    struct {
        std::string street;
        std::string unit;
    } address;
    char state[2];
    int zip;
};

Thus, when you're working with a collection of data, it makes sense to have std::vector<Customer> or std::set<Customer>.

With that in mind, think of your CSV handling as two operations:

// if you wanted to go nuts, you could use a forward iterator concept for both of these
class CSVReader {
public:
    CSVReader(const std::string &inputFile);
    bool hasNextLine();
    void readNextLine(std::vector<std::string> &fields);
private:
    /* secrets */
};
class CSVWriter {
public:
    CSVWriter(const std::string &outputFile);
    void writeNextLine(const std::vector<std::string> &fields);
private:
    /* more secrets */
};
void readCustomers(CSVReader &reader, std::vector<Customer> &customers);
void writeCustomers(CSVWriter &writer, const std::vector<Customer> &customers);

Read and write a single row at a time, rather than keeping a complete in-memory representation of the file itself. There are a few obvious benefits:

  1. Your data is represented in a form that makes sense for your problem (customers), rather than the current solution (CSV files).
  2. You can trivially add adapters for other data formats, such as bulk SQL import/export, Excel/OO spreadsheet files, or even an HTML <table> rendering.
  3. Your memory footprint is likely to be smaller (depends on relative sizeof(Customer) vs. the number of bytes in a single row).
  4. CSVReader and CSVWriter can be reused as the basis for an in-memory model (such as Nelson's) without loss of performance or functionality. The converse is not true.

Read and overwrite a file in Python

The fileinput module has an inplace mode for writing changes to the file you are processing without using temporary files etc. The module nicely encapsulates the common operation of looping over the lines in a list of files, via an object which transparently keeps track of the file name, line number etc if you should want to inspect them inside the loop.

from fileinput import FileInput
for line in FileInput("file", inplace=1):
    line = line.replace("foobar", "bar")
    print(line)

Get List of connected USB Devices

To see the devices I was interested in, I had replace Win32_USBHub by Win32_PnPEntity in Adel Hazzah's code, based on this post. This works for me:

namespace ConsoleApplication1
{
  using System;
  using System.Collections.Generic;
  using System.Management; // need to add System.Management to your project references.

  class Program
  {
    static void Main(string[] args)
    {
      var usbDevices = GetUSBDevices();

      foreach (var usbDevice in usbDevices)
      {
        Console.WriteLine("Device ID: {0}, PNP Device ID: {1}, Description: {2}",
            usbDevice.DeviceID, usbDevice.PnpDeviceID, usbDevice.Description);
      }

      Console.Read();
    }

    static List<USBDeviceInfo> GetUSBDevices()
    {
      List<USBDeviceInfo> devices = new List<USBDeviceInfo>();

      ManagementObjectCollection collection;
      using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_PnPEntity"))
        collection = searcher.Get();      

      foreach (var device in collection)
      {
        devices.Add(new USBDeviceInfo(
        (string)device.GetPropertyValue("DeviceID"),
        (string)device.GetPropertyValue("PNPDeviceID"),
        (string)device.GetPropertyValue("Description")
        ));
      }

      collection.Dispose();
      return devices;
    }
  }

  class USBDeviceInfo
  {
    public USBDeviceInfo(string deviceID, string pnpDeviceID, string description)
    {
      this.DeviceID = deviceID;
      this.PnpDeviceID = pnpDeviceID;
      this.Description = description;
    }
    public string DeviceID { get; private set; }
    public string PnpDeviceID { get; private set; }
    public string Description { get; private set; }
  }
}

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

Function for C++ struct

Structs can have functions just like classes. The only difference is that they are public by default:

struct A {
    void f() {}
};

Additionally, structs can also have constructors and destructors.

struct A {
    A() : x(5) {}
    ~A() {}

    private: int x;
};

Undefined reference to main - collect2: ld returned 1 exit status

Executable file needs a main function. See below hello world demo.

#include <stdio.h>
int main(void)
{
        printf("Hello world!\n");
        return 0;
}

As you can see there is a main function. if you don't have this main function, ld will report "undefined reference to main' "

check my result:

$ cat es3.c
#include <stdio.h>
int main(void)
{
    printf("Hello world!\n");
    return 0;
}
$ gcc -Wall -g -c es3.c
$ gcc -Wall -g es3.o -o es3
~$ ./es3
Hello world! 

please use $ objdump -t es3.o to check if there is a main symbol. Below is my result.

$ objdump -t es3.o

es3.o:     file format elf32-i386

SYMBOL TABLE:
00000000 l    df *ABS*  00000000 es3.c
00000000 l    d  .text  00000000 .text
00000000 l    d  .data  00000000 .data
00000000 l    d  .bss   00000000 .bss
00000000 l    d  .debug_abbrev  00000000 .debug_abbrev
00000000 l    d  .debug_info    00000000 .debug_info
00000000 l    d  .debug_line    00000000 .debug_line
00000000 l    d  .rodata        00000000 .rodata
00000000 l    d  .debug_frame   00000000 .debug_frame
00000000 l    d  .debug_loc     00000000 .debug_loc
00000000 l    d  .debug_pubnames        00000000 .debug_pubnames
00000000 l    d  .debug_aranges 00000000 .debug_aranges
00000000 l    d  .debug_str     00000000 .debug_str
00000000 l    d  .note.GNU-stack        00000000 .note.GNU-stack
00000000 l    d  .comment       00000000 .comment
00000000 g     F .text  0000002b main
00000000         *UND*  00000000 puts

How to center horizontal table-cell

Short snippet for future visitors - how to center horizontal table-cell (+ vertically)

_x000D_
_x000D_
html, body {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.tab {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
  display: table-cell;_x000D_
  vertical-align: middle;_x000D_
  text-align: center; /* the key */_x000D_
  background-color: #EEEEEE;_x000D_
}_x000D_
_x000D_
.content {_x000D_
  display: inline-block; /* important !! */_x000D_
  width: 100px;_x000D_
  background-color: #00FF00;_x000D_
}
_x000D_
<div class="tab">_x000D_
  <div class="cell">_x000D_
    <div class="content" id="a">_x000D_
      <p>Content</p>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to activate "Share" button in android app?

Create a button with an id share and add the following code snippet.

share.setOnClickListener(new View.OnClickListener() {             
    @Override
    public void onClick(View v) {

        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        String shareBody = "Your body here";
        String shareSub = "Your subject here";
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSub);
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
        startActivity(Intent.createChooser(sharingIntent, "Share using"));
    }
});

The above code snippet will open the share chooser on share button click action. However, note...The share code snippet might not output very good results using emulator. For actual results, run the code snippet on android device to get the real results.

How to exit git log or git diff

You're in the less program, which makes the output of git log scrollable.

Type q to exit this screen. Type h to get help.

If you don't want to read the output in a pager and want it to be just printed to the terminal define the environment variable GIT_PAGER to cat or set core.pager to cat (execute git config --global core.pager cat).

PL/SQL ORA-01422: exact fetch returns more than requested number of rows

It can also be due to a duplicate entry in any of the tables that are used.

Get value of div content using jquery

$('#field-function_purpose') will get you the element with ID field-function_purpose, which is your div element. text() returns you the content of the div.

var x = $('#field-function_purpose').text();

CodeIgniter - Correct way to link to another page in a view

you can also use PHP short tag to make it shorter. here's an example

<a href="<?= site_url('controller/function'); ?>Contacts</a>

or use the built in anchor function of CI.

IIS 7, HttpHandler and HTTP Error 500.21

It's not possible to configure an IIS managed handler to run in classic mode. You should be running IIS in integrated mode if you want to do that.

You can learn more about modules, handlers and IIS modes in the following blog post:

IIS 7.0, ASP.NET, pipelines, modules, handlers, and preconditions

For handlers, if you set preCondition="integratedMode" in the mapping, the handler will only run in integrated mode. On the other hand, if you set preCondition="classicMode" the handler will only run in classic mode. And if you omit both of these, the handler can run in both modes, although this is not possible for a managed handler.

Datatables Select All Checkbox

You can use Checkboxes extension for jQuery Datatables.

var table = $('#example').DataTable({
   'ajax': 'https://api.myjson.com/bins/1us28',
   'columnDefs': [
      {
         'targets': 0,
         'checkboxes': {
            'selectRow': true
         }
      }
   ],
   'select': {
      'style': 'multi'
   },
   'order': [[1, 'asc']]
});

See this example for code and demonstration.

See Checkboxes project page for more examples and documentation.

How to create User/Database in script for Docker Postgres

You can use this commands:

docker exec -it yournamecontainer psql -U postgres -c "CREATE DATABASE mydatabase ENCODING 'LATIN1' TEMPLATE template0 LC_COLLATE 'C' LC_CTYPE 'C';"

docker exec -it yournamecontainer psql -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE postgres TO postgres;"

Output first 100 characters in a string

From python tutorial:

Degenerate slice indices are handled gracefully: an index that is too large is replaced by the string size, an upper bound smaller than the lower bound returns an empty string.

So it is safe to use x[:100].

setState() inside of componentDidUpdate()

I would say that you need to check if the state already has the same value you are trying to set. If it's the same, there is no point to set state again for the same value.

Make sure to set your state like this:

let top = newValue /*true or false*/
if(top !== this.state.top){
    this.setState({top});
}

postgres, ubuntu how to restart service on startup? get stuck on clustering after instance reboot

ENABLE is what you are looking for

USAGE: type this command once and then you are good to go. Your service will start automaticaly at boot up

 sudo systemctl enable postgresql

DISABLE exists as well ofc

Some DOC: freedesktop man systemctl

MySQL - ERROR 1045 - Access denied

I could not connect to MySql Administrator. I fixed it by creating another user and assigning all the permissions.

I logged in with that new user and it worked.

what is reverse() in Django

reverse() | Django documentation


Let's suppose that in your urls.py you have defined this:

url(r'^foo$', some_view, name='url_name'),

In a template you can then refer to this url as:

<!-- django <= 1.4 -->
<a href="{% url url_name %}">link which calls some_view</a>

<!-- django >= 1.5 or with {% load url from future %} in your template -->
<a href="{% url 'url_name' %}">link which calls some_view</a>

This will be rendered as:

<a href="/foo/">link which calls some_view</a>

Now say you want to do something similar in your views.py - e.g. you are handling some other url (not /foo/) in some other view (not some_view) and you want to redirect the user to /foo/ (often the case on successful form submission).

You could just do:

return HttpResponseRedirect('/foo/')

But what if you want to change the url in future? You'd have to update your urls.py and all references to it in your code. This violates DRY (Don't Repeat Yourself), the whole idea of editing one place only, which is something to strive for.

Instead, you can say:

from django.urls import reverse
return HttpResponseRedirect(reverse('url_name'))

This looks through all urls defined in your project for the url defined with the name url_name and returns the actual url /foo/.

This means that you refer to the url only by its name attribute - if you want to change the url itself or the view it refers to you can do this by editing one place only - urls.py.

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

SQL Server Pivot Table with multiple column aggregates

I would do this slightly different by applying both the UNPIVOT and the PIVOT functions to get the final result. The unpivot takes the values from both the totalcount and totalamount columns and places them into one column with multiple rows. You can then pivot on those results.:

select chardate,
  Australia_totalcount as [Australia # of Transactions], 
  Australia_totalamount as [Australia Total $ Amount],
  Austria_totalcount as [Austria # of Transactions], 
  Austria_totalamount as [Austria Total $ Amount]
from
(
  select 
    numericmonth, 
    chardate,
    country +'_'+col col, 
    value
  from
  (
    select numericmonth, 
      country, 
      chardate,
      cast(totalcount as numeric(10, 2)) totalcount,
      cast(totalamount as numeric(10, 2)) totalamount
    from mytransactions
  ) src
  unpivot
  (
    value
    for col in (totalcount, totalamount)
  ) unpiv
) s
pivot
(
  sum(value)
  for col in (Australia_totalcount, Australia_totalamount,
              Austria_totalcount, Austria_totalamount)
) piv
order by numericmonth

See SQL Fiddle with Demo.

If you have an unknown number of country names, then you can use dynamic SQL:

DECLARE @cols AS NVARCHAR(MAX),
    @colsName AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(country +'_'+c.col) 
                      from mytransactions
                      cross apply 
                      (
                        select 'TotalCount' col
                        union all
                        select 'TotalAmount'
                      ) c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

select @colsName 
    = STUFF((SELECT distinct ', ' + QUOTENAME(country +'_'+c.col) 
               +' as ['
               + country + case when c.col = 'TotalCount' then ' # of Transactions]' else 'Total $ Amount]' end
             from mytransactions
             cross apply 
             (
                select 'TotalCount' col
                union all
                select 'TotalAmount'
             ) c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query 
  = 'SELECT chardate, ' + @colsName + ' 
     from 
     (
      select 
        numericmonth, 
        chardate,
        country +''_''+col col, 
        value
      from
      (
        select numericmonth, 
          country, 
          chardate,
          cast(totalcount as numeric(10, 2)) totalcount,
          cast(totalamount as numeric(10, 2)) totalamount
        from mytransactions
      ) src
      unpivot
      (
        value
        for col in (totalcount, totalamount)
      ) unpiv
     ) s
     pivot 
     (
       sum(value)
       for col in (' + @cols + ')
     ) p 
     order by numericmonth'

execute(@query)

See SQL Fiddle with Demo

Both give the result:

|             CHARDATE | AUSTRALIA # OF TRANSACTIONS | AUSTRALIA TOTAL $ AMOUNT | AUSTRIA # OF TRANSACTIONS | AUSTRIA TOTAL $ AMOUNT |
--------------------------------------------------------------------------------------------------------------------------------------
| Jul-12               |                          36 |                   699.96 |                        11 |                 257.82 |
| Aug-12               |                          44 |                  1368.71 |                         5 |                 126.55 |
| Sep-12               |                          52 |                  1161.33 |                         7 |                  92.11 |
| Oct-12               |                          50 |                  1099.84 |                        12 |                 103.56 |
| Nov-12               |                          38 |                  1078.94 |                        21 |                 377.68 |
| Dec-12               |                          63 |                  1668.23 |                         3 |                  14.35 |

How do I specify different layouts for portrait and landscape orientations?

Fastest way for Android Studio 3.x.x and Android Studio 4.x.x

1.Go to the design tab of the activity layout

2.At the top you should press on the orientation for preview button, there is a option to create a landscape layout (check image), a new folder will be created as your xml layout file for that particular orientation

enter image description here

Onclick javascript to make browser go back to previous page?

This is the only thing that works on all current browsers:

<script>
function goBack() {
    history.go(-1);
}
</script>
<button onclick="goBack()">Go Back</button>

Any way to write a Windows .bat file to kill processes?

You can do this with 'taskkill'. With the /IM parameter, you can specify image names.

Example:

taskkill /im somecorporateprocess.exe

You can also do this to 'force' kill:

Example:

taskkill /f /im somecorporateprocess.exe

Just add one line per process you want to kill, save it as a .bat file, and add in your startup directory. Problem solved!

If this is a legacy system, PsKill will do the same.

Query to get only numbers from a string

Try this one -

Query:

DECLARE @temp TABLE
(
      string NVARCHAR(50)
)

INSERT INTO @temp (string)
VALUES 
    ('003Preliminary Examination Plan'),
    ('Coordination005'),
    ('Balance1000sheet')

SELECT LEFT(subsrt, PATINDEX('%[^0-9]%', subsrt + 't') - 1) 
FROM (
    SELECT subsrt = SUBSTRING(string, pos, LEN(string))
    FROM (
        SELECT string, pos = PATINDEX('%[0-9]%', string)
        FROM @temp
    ) d
) t

Output:

----------
003
005
1000