Programs & Examples On #Lcov

LCOV is a graphical front-end for GCC's coverage testing tool gcov

Get cart item name, quantity all details woocommerce

Try this :

<?php
    global $woocommerce;
    $items = $woocommerce->cart->get_cart();

        foreach($items as $item => $values) { 
            $_product =  wc_get_product( $values['data']->get_id()); 
            echo "<b>".$_product->get_title().'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
            $price = get_post_meta($values['product_id'] , '_price', true);
            echo "  Price: ".$price."<br>";
        } 
?>

To get Product Image and Regular & Sale Price:

<?php
    global $woocommerce;
    $items = $woocommerce->cart->get_cart();

        foreach($items as $item => $values) { 
            $_product =  wc_get_product( $values['data']->get_id() );
            //product image
            $getProductDetail = wc_get_product( $values['product_id'] );
            echo $getProductDetail->get_image(); // accepts 2 arguments ( size, attr )

            echo "<b>".$_product->get_title() .'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
            $price = get_post_meta($values['product_id'] , '_price', true);
            echo "  Price: ".$price."<br>";
            /*Regular Price and Sale Price*/
            echo "Regular Price: ".get_post_meta($values['product_id'] , '_regular_price', true)."<br>";
            echo "Sale Price: ".get_post_meta($values['product_id'] , '_sale_price', true)."<br>";
        }
?>

1064 error in CREATE TABLE ... TYPE=MYISAM

A complementary note about CREATE TABLE .. TYPE="" syntax in SQL dump files

TLDR: If you still get CREATE TABLE ... TYPE="..." statements in SQL dump files generated by third party tools, it most certainly indicates that your server is configured to use a default sqlmode of MYSQL40 or MYSQL323.

Long story

As it was said by others, the TYPE argument to CREATE TABLE has been deprecated for a long time in MySQL. mysqldump correctly uses the ENGINE argument, unless you specifically ask it to generate a backward compatible dump (for example using --compatible=mysql40 in versions of mysqldump up to 5.7).

However, many external SQL dump tools (for example, those integrated in MySQL clients such as phpmyadmin, Navicat and DBVisualizer, as well as those used by external automated backup services such as iControlWP) are not specifically aware of this change, and instead rely on the SHOW CREATE TABLE ... command to provide table creation statements for each tables (and just to it make it clear: this is actually a good thing). However, the SHOW CREATE TABLE will actually produce outdated syntax, including the TYPE argument, if the sqlmode variable is set to MYSQL40 or MYSQL323.

Therefore, if you still get CREATE TABLE ... TYPE="..." statements in SQL dump files generated by third party tools, it most certainly indicates that your server is configured to use a default sqlmode of MYSQL40 or MYSQL323.

These sqlmodes basically configure MySQL to retain some backward compatible behaviours, and using them by default was largely recommended a few years ago. It is however highly improbable that you still have any code that wouldn't work correctly without these modes. Anyway, MYSQL40, MYSQL323 and several other similar sqlmodes have themselves been deprecated and are not supported in MySQL 8.0 and higher.

If your server is still configured with these sqlmodes and you are worried that some legacy program might fail if you change these, then one possibility is to set the sqlmode locally for that program, by executing SET SESSION sql_mode = 'MYSQL40'; immediately after connection. Note that this should only be considered as a temporary patch, and will not work in MySQL 8.0 and higher.

A more future-proof solution that do not involve rewriting your SQL queries would be to determine exactly which compatibility features need to be enable, and to enable only those, on a per-program basis (as described previously). The default sqlmode (that is, in server's configuration) should ideally be left unset (which will use official MySQL defaults for your current version). The full list of sqlmode (as of MySQL 5.7) is described here: https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html.

Is it possible to forward-declare a function in Python?

No, I don't believe there is any way to forward-declare a function in Python.

Imagine you are the Python interpreter. When you get to the line

print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)])

either you know what cmp_configs is or you don't. In order to proceed, you have to know cmp_configs. It doesn't matter if there is recursion.

Where is the php.ini file on a Linux/CentOS PC?

In your terminal/console (only Linux, in windows you need Putty)

ssh user@ip
php -i | grep "Loaded Configuration File"

And it will show you something like this Loaded Configuration File => /etc/php.ini.

ALTERNATIVE METHOD

You can make a php file on your website, which run: <?php phpinfo(); ?>, and you can see the php.ini location on the line with: "Loaded Configuration File".

Update This command gives the path right away

cli_php_ini=php -i | grep /.+/php.ini -oE  #ref. https://stackoverflow.com/a/15763333/248616
    php_ini="${cli_php_ini/cli/apache2}"   #replace cli by apache2 ref. https://stackoverflow.com/a/13210909/248616

Reverse a string in Python

s = 'hello'
ln = len(s)
i = 1
while True:
    rev = s[ln-i]
    print rev,
    i = i + 1
    if i == ln + 1 :
        break

OUTPUT :

o l l e h

See full command of running/stopped container in Docker

Use:

docker inspect -f "{{.Name}} {{.Config.Cmd}}" $(docker ps -a -q)

... it does a "docker inspect" for all containers.

syntax error, unexpected T_VARIABLE

There is no semicolon at the end of that instruction causing the error.

EDIT

Like RiverC pointed out, there is no semicolon at the end of the previous line!

require ("scripts/connect.php") 

EDIT

It seems you have no-semicolons whatsoever.

http://php.net/manual/en/language.basic-syntax.instruction-separation.php

As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement.

Is it possible to sort a ES6 map object?

Unfortunately, not really implemented in ES6. You have this feature with OrderedMap.sort() from ImmutableJS or _.sortBy() from Lodash.

How to tell PowerShell to wait for each command to end before starting the next?

Taking it further you could even parse on the fly

e.g.

& "my.exe" | %{
    if ($_ -match 'OK')
    { Write-Host $_ -f Green }
    else if ($_ -match 'FAIL|ERROR')
    { Write-Host $_ -f Red }
    else 
    { Write-Host $_ }
}

How to pass data from Javascript to PHP and vice versa?

the other way to exchange data from php to javascript or vice versa is by using cookies, you can save cookies in php and read by your javascript, for this you don't have to use forms or ajax

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

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

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

For example:

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

Random Tip

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

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

Save array in mysql database

To convert any array (or any object) into a string using PHP, call the serialize():

$array = array( 1, 2, 3 );
$string = serialize( $array );
echo $string;

$string will now hold a string version of the array. The output of the above code is as follows:

a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}

To convert back from the string to the array, use unserialize():

// $array will contain ( 1, 2, 3 )
$array = unserialize( $string );

mingw-w64 threads: posix vs win32

GCC comes with a compiler runtime library (libgcc) which it uses for (among other things) providing a low-level OS abstraction for multithreading related functionality in the languages it supports. The most relevant example is libstdc++'s C++11 <thread>, <mutex>, and <future>, which do not have a complete implementation when GCC is built with its internal Win32 threading model. MinGW-w64 provides a winpthreads (a pthreads implementation on top of the Win32 multithreading API) which GCC can then link in to enable all the fancy features.

I must stress this option does not forbid you to write any code you want (it has absolutely NO influence on what API you can call in your code). It only reflects what GCC's runtime libraries (libgcc/libstdc++/...) use for their functionality. The caveat quoted by @James has nothing to do with GCC's internal threading model, but rather with Microsoft's CRT implementation.

To summarize:

  • posix: enable C++11/C11 multithreading features. Makes libgcc depend on libwinpthreads, so that even if you don't directly call pthreads API, you'll be distributing the winpthreads DLL. There's nothing wrong with distributing one more DLL with your application.
  • win32: No C++11 multithreading features.

Neither have influence on any user code calling Win32 APIs or pthreads APIs. You can always use both.

NullInjectorError: No provider for AngularFirestore

I solved this problem by just removing firestore from:

import { AngularFirestore } from '@angular/fire/firestore/firestore';

in my component.ts file. as use only:

import { AngularFirestore } from '@angular/fire/firestore';

this can be also your problem.

Can two or more people edit an Excel document at the same time?

yes if it is SharePoint 2010 and above by using the Office feature co-authoring

How to disable SSL certificate checking with Spring RestTemplate?

You can also register your keystore :

private void registerKeyStore(String keyStoreName) {
    try {
        ClassLoader classLoader = this.getClass().getClassLoader();
        InputStream keyStoreInputStream = classLoader.getResourceAsStream(keyStoreName);
        if (keyStoreInputStream == null) {
            throw new FileNotFoundException("Could not find file named '" + keyStoreName + "' in the CLASSPATH");
        }

        //load the keystore
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(keyStoreInputStream, null);

        //add to known keystore 
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keystore);

        //default SSL connections are initialized with the keystore above
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustManagers, null);
        SSLContext.setDefault(sc);
    } catch (IOException | GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

Git 'fatal: Unable to write new index file'

I've been having this same problem for the last few days. Basically, without my knowledge the entire repo had been moved to a new filesystem, when I tried to run git status, it was suddenly reporting that every file in the repo had been udpated.

Possible solutions

So, after much google scouring, I tried the following:

  • changing .git permssions (same issue)
  • changing .git/index permissions (same issue)
  • git add-ing all the changes to commit (same issue)
  • git rm-ing deleted files, since they were reporting file name too long errors (same issue)
  • git reset (soft|Head|Hard) (same issue)
  • git clean (same issue)
  • turning off windows defender (same issue)
  • updating git (same issue)
  • different git clients (i use gitbash) (same issue)
  • drinking 2 coffees instead of 1 (same issue)

tl:dr - dirty solution

The only thing that managed to solve the issue was to copy the index file, delete the original and rename the copy.

I know its not really a 'solution' but now its magically working ><, with all files / branches intact. If anyone knows why this might have work, do tell.

Replacing .NET WebBrowser control with a better browser, like Chrome?

I had the same problem, the WebBrowser was using an old version of IE, with some googling I came across the following code that makes a change into registry and makes the WebBrowser to use the lastest IE version possible:

 public enum BrowserEmulationVersion
    {
        Default = 0,
        Version7 = 7000,
        Version8 = 8000,
        Version8Standards = 8888,
        Version9 = 9000,
        Version9Standards = 9999,
        Version10 = 10000,
        Version10Standards = 10001,
        Version11 = 11000,
        Version11Edge = 11001
    }
    public static class WBEmulator
    {
        private const string InternetExplorerRootKey = @"Software\Microsoft\Internet Explorer";

        public static int GetInternetExplorerMajorVersion()
        {
            int result;

            result = 0;

            try
            {
                RegistryKey key;

                key = Registry.LocalMachine.OpenSubKey(InternetExplorerRootKey);

                if (key != null)
                {
                    object value;

                    value = key.GetValue("svcVersion", null) ?? key.GetValue("Version", null);

                    if (value != null)
                    {
                        string version;
                        int separator;

                        version = value.ToString();
                        separator = version.IndexOf('.');
                        if (separator != -1)
                        {
                            int.TryParse(version.Substring(0, separator), out result);
                        }
                    }
                }
            }
            catch (SecurityException)
            {
                // The user does not have the permissions required to read from the registry key.
            }
            catch (UnauthorizedAccessException)
            {
                // The user does not have the necessary registry rights.
            }

            return result;
        }
        private const string BrowserEmulationKey = InternetExplorerRootKey + @"\Main\FeatureControl\FEATURE_BROWSER_EMULATION";

        public static BrowserEmulationVersion GetBrowserEmulationVersion()
        {
            BrowserEmulationVersion result;

            result = BrowserEmulationVersion.Default;

            try
            {
                RegistryKey key;

                key = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, true);
                if (key != null)
                {
                    string programName;
                    object value;

                    programName = Path.GetFileName(Environment.GetCommandLineArgs()[0]);
                    value = key.GetValue(programName, null);

                    if (value != null)
                    {
                        result = (BrowserEmulationVersion)Convert.ToInt32(value);
                    }
                }
            }
            catch (SecurityException)
            {
                // The user does not have the permissions required to read from the registry key.
            }
            catch (UnauthorizedAccessException)
            {
                // The user does not have the necessary registry rights.
            }

            return result;
        }
        public static bool SetBrowserEmulationVersion(BrowserEmulationVersion browserEmulationVersion)
        {
            bool result;

            result = false;

            try
            {
                RegistryKey key;

                key = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, true);

                if (key != null)
                {
                    string programName;

                    programName = Path.GetFileName(Environment.GetCommandLineArgs()[0]);

                    if (browserEmulationVersion != BrowserEmulationVersion.Default)
                    {
                        // if it's a valid value, update or create the value
                        key.SetValue(programName, (int)browserEmulationVersion, RegistryValueKind.DWord);
                    }
                    else
                    {
                        // otherwise, remove the existing value
                        key.DeleteValue(programName, false);
                    }

                    result = true;
                }
            }
            catch (SecurityException)
            {
                // The user does not have the permissions required to read from the registry key.
            }
            catch (UnauthorizedAccessException)
            {
                // The user does not have the necessary registry rights.
            }

            return result;
        }

        public static bool SetBrowserEmulationVersion()
        {
            int ieVersion;
            BrowserEmulationVersion emulationCode;

            ieVersion = GetInternetExplorerMajorVersion();

            if (ieVersion >= 11)
            {
                emulationCode = BrowserEmulationVersion.Version11;
            }
            else
            {
                switch (ieVersion)
                {
                    case 10:
                        emulationCode = BrowserEmulationVersion.Version10;
                        break;
                    case 9:
                        emulationCode = BrowserEmulationVersion.Version9;
                        break;
                    case 8:
                        emulationCode = BrowserEmulationVersion.Version8;
                        break;
                    default:
                        emulationCode = BrowserEmulationVersion.Version7;
                        break;
                }
            }

            return SetBrowserEmulationVersion(emulationCode);
        }
        public static bool IsBrowserEmulationSet()
        {
            return GetBrowserEmulationVersion() != BrowserEmulationVersion.Default;
        }
    } 

You just need to create a class and put this code in it, then run the following code when the program starts:

 if (!WBEmulator.IsBrowserEmulationSet())
            {
                WBEmulator.SetBrowserEmulationVersion();
            }

VB.NET:

Imports Microsoft.Win32
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Security
Imports System.Text
Imports System.Threading.Tasks

Public Enum BrowserEmulationVersion
    [Default] = 0
    Version7 = 7000
    Version8 = 8000
    Version8Standards = 8888
    Version9 = 9000
    Version9Standards = 9999
    Version10 = 10000
    Version10Standards = 10001
    Version11 = 11000
    Version11Edge = 11001
End Enum


Public Class WBEmulator
    Private Const InternetExplorerRootKey As String = "Software\Microsoft\Internet Explorer"
    Public Shared Function GetInternetExplorerMajorVersion() As Integer

        Dim result As Integer

        result = 0

        Try
            Dim key As RegistryKey
            key = Registry.LocalMachine.OpenSubKey(InternetExplorerRootKey)
            If key IsNot Nothing Then
                Dim value As Object = If(key.GetValue("svcVersion", Nothing), key.GetValue("Version", Nothing))

                Dim Version As String
                Dim separator As Integer
                Version = value.ToString()
                separator = Version.IndexOf(".")
                If separator <> -1 Then
                    Integer.TryParse(Version.Substring(0, separator), result)
                End If
            End If

        Catch ex As SecurityException
            'The user does Not have the permissions required to read from the registry key.
        Catch ex As UnauthorizedAccessException
            'The user does Not have the necessary registry rights.
        Catch

        End Try
        GetInternetExplorerMajorVersion = result
    End Function
    Private Const BrowserEmulationKey = InternetExplorerRootKey + "\Main\FeatureControl\FEATURE_BROWSER_EMULATION"

    Public Shared Function GetBrowserEmulationVersion() As BrowserEmulationVersion

        Dim result As BrowserEmulationVersion
        result = BrowserEmulationVersion.Default

        Try
            Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, True)
            If key IsNot Nothing Then
                Dim programName As String
                Dim value As Object
                programName = Path.GetFileName(Environment.GetCommandLineArgs()(0))
                value = key.GetValue(programName, Nothing)
                If value IsNot Nothing Then
                    result = CType(Convert.ToInt32(value), BrowserEmulationVersion)
                End If
            End If
        Catch ex As SecurityException
            'The user does Not have the permissions required to read from the registry key.
        Catch ex As UnauthorizedAccessException
            'The user does Not have the necessary registry rights.
        Catch

        End Try

        GetBrowserEmulationVersion = result
    End Function
    Public Shared Function SetBrowserEmulationVersion(BEVersion As BrowserEmulationVersion) As Boolean

        Dim result As Boolean = False

        Try
            Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, True)
            If key IsNot Nothing Then
                Dim programName As String = Path.GetFileName(Environment.GetCommandLineArgs()(0))
                If BEVersion <> BrowserEmulationVersion.Default Then
                    'if it's a valid value, update or create the value
                    key.SetValue(programName, CType(BEVersion, Integer), RegistryValueKind.DWord)
                Else
                    'otherwise, remove the existing value
                    key.DeleteValue(programName, False)
                End If
                result = True
            End If
        Catch ex As SecurityException

            ' The user does Not have the permissions required to read from the registry key.

        Catch ex As UnauthorizedAccessException

            ' The user does Not have the necessary registry rights.

        End Try

        SetBrowserEmulationVersion = result
    End Function


    Public Shared Function SetBrowserEmulationVersion() As Boolean
        Dim ieVersion As Integer
        Dim emulationCode As BrowserEmulationVersion
        ieVersion = GetInternetExplorerMajorVersion()

        If ieVersion >= 11 Then

            emulationCode = BrowserEmulationVersion.Version11
        Else

            Select Case ieVersion
                Case 10
                    emulationCode = BrowserEmulationVersion.Version10
                Case 9
                    emulationCode = BrowserEmulationVersion.Version9
                Case 8
                    emulationCode = BrowserEmulationVersion.Version8
                Case Else
                    emulationCode = BrowserEmulationVersion.Version7
            End Select
        End If

        SetBrowserEmulationVersion = SetBrowserEmulationVersion(emulationCode)
    End Function

    Public Shared Function IsBrowserEmulationSet() As Boolean
        IsBrowserEmulationSet = GetBrowserEmulationVersion() <> BrowserEmulationVersion.Default
    End Function
End Class

You may use it like:

If Not WBEmulator.IsBrowserEmulationSet() Then
    WBEmulator.SetBrowserEmulationVersion()
End If

Unsetting array values in a foreach loop

You would also need a

$i--;

after each unset to not skip an element/

Because when you unset $item[45], the next element in the for-loop should be $item[45] - which was [46] before unsetting. If you would not do this, you'd always skip an element after unsetting.

How to pass in password to pg_dump?

Create a .pgpass file in the home directory of the account that pg_dump will run as.

The format is:

hostname:port:database:username:password

Then, set the file's mode to 0600. Otherwise, it will be ignored.

chmod 600 ~/.pgpass

See the Postgresql documentation libpq-pgpass for more details.

How to shrink temp tablespace in oracle?

You should have written what version of Oracle you use. You most likely use something else than Oracle 11g, that's why you can't shrink a temp tablespace.

Alternatives:

1) alter database tempfile '[your_file]' resize 128M; which will probably fail
2) Drop and recreate the tablespace. If the temporary tablespace you want to shrink is your default temporary tablespace, you may have to first create a new temporary tablespace, set it as the default temporary tablespace then drop your old default temporary tablespace and recreate it. Afterwards drop the second temporary table created. 3) For Oracle 9i and higher you could just drop the tempfile(s) and add a new one(s)

Everything is described here in great detail.


See this link: http://databaseguide.blogspot.com/2008/06/resizing-temporary-tablespace.html
It was already linked, but maybe you missed it, so here it is again.

How to 'bulk update' with Django?

If you want to set the same value on a collection of rows, you can use the update() method combined with any query term to update all rows in one query:

some_list = ModelClass.objects.filter(some condition).values('id')
ModelClass.objects.filter(pk__in=some_list).update(foo=bar)

If you want to update a collection of rows with different values depending on some condition, you can in best case batch the updates according to values. Let's say you have 1000 rows where you want to set a column to one of X values, then you could prepare the batches beforehand and then only run X update-queries (each essentially having the form of the first example above) + the initial SELECT-query.

If every row requires a unique value there is no way to avoid one query per update. Perhaps look into other architectures like CQRS/Event sourcing if you need performance in this latter case.

Conversion from 12 hours time to 24 hours time in java

Try this:

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

public class Main {
   public static void main(String [] args) throws Exception {
       SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
       SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
       Date date = parseFormat.parse("10:30 PM");
       System.out.println(parseFormat.format(date) + " = " + displayFormat.format(date));
   }
}

which produces:

10:30 PM = 22:30

See: http://download.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html

The requested resource does not support HTTP method 'GET'

just use this attribute

[System.Web.Http.HttpGet]

not need this line of code:

[System.Web.Http.AcceptVerbs("GET", "POST")]

Manifest merger failed : uses-sdk:minSdkVersion 14

The only thing that worked for me is this:

In project.properties, I changed:

cordova.system.library.1=com.android.support:support-v4:+ to cordova.system.library.1=com.android.support:support-v4:20.+

Responsive css background images

I used

#content {
  width: 100%;
  height: 500px;
  background-size: cover;
  background-position: center top;
}

which worked really well.

Default value to a parameter while passing by reference in C++

In case of OO... To say that a Given Class has and "Default" means that this Default (value) must declared acondingly an then may be usd as an Default Parameter ex:

class Pagination {
public:
    int currentPage;
    //...
    Pagination() {
        currentPage = 1;
        //...
    }
    // your Default Pagination
    static Pagination& Default() {
        static Pagination pag;
        return pag;
    }
};

On your Method ...

 shared_ptr<vector<Auditoria> > 
 findByFilter(Auditoria& audit, Pagination& pagination = Pagination::Default() ) {

This solutions is quite suitable since in this case, "Global default Pagination" is a single "reference" value. You will also have the power to change default values at runtime like an "gobal-level" configuration ex: user pagination navigation preferences and etc..

AES Encryption for an NSString on the iPhone

I have put together a collection of categories for NSData and NSString which uses solutions found on Jeff LaMarche's blog and some hints by Quinn Taylor here on Stack Overflow.

It uses categories to extend NSData to provide AES256 encryption and also offers an extension of NSString to BASE64-encode encrypted data safely to strings.

Here's an example to show the usage for encrypting strings:

NSString *plainString = @"This string will be encrypted";
NSString *key = @"YourEncryptionKey"; // should be provided by a user

NSLog( @"Original String: %@", plainString );

NSString *encryptedString = [plainString AES256EncryptWithKey:key];
NSLog( @"Encrypted String: %@", encryptedString );

NSLog( @"Decrypted String: %@", [encryptedString AES256DecryptWithKey:key] );

Get the full source code here:

https://gist.github.com/838614

Thanks for all the helpful hints!

-- Michael

SQLAlchemy create_all() does not create tables

If someone is having issues with creating tables by using files dedicated to each model, be aware of running the "create_all" function from a file different from the one where that function is declared. So, if the filesystem is like this:

Root  
--app.py     <-- file from which app will be run
--models
----user.py      <-- file with "User" model
----order.py    <-- file with "Order" model
----database.py <-- file with database and "create_all" function declaration

Be careful about calling the "create_all" function from app.py.

This concept is explained better by the answer to this thread posted by @SuperShoot

OS detecting makefile

Detect the operating system using two simple tricks:

  • First the environment variable OS
  • Then the uname command
ifeq ($(OS),Windows_NT)     # is Windows_NT on XP, 2000, 7, Vista, 10...
    detected_OS := Windows
else
    detected_OS := $(shell uname)  # same as "uname -s"
endif

Or a more safe way, if not on Windows and uname unavailable:

ifeq ($(OS),Windows_NT) 
    detected_OS := Windows
else
    detected_OS := $(shell sh -c 'uname 2>/dev/null || echo Unknown')
endif

Ken Jackson proposes an interesting alternative if you want to distinguish Cygwin/MinGW/MSYS/Windows. See his answer that looks like that:

ifeq '$(findstring ;,$(PATH))' ';'
    detected_OS := Windows
else
    detected_OS := $(shell uname 2>/dev/null || echo Unknown)
    detected_OS := $(patsubst CYGWIN%,Cygwin,$(detected_OS))
    detected_OS := $(patsubst MSYS%,MSYS,$(detected_OS))
    detected_OS := $(patsubst MINGW%,MSYS,$(detected_OS))
endif

Then you can select the relevant stuff depending on detected_OS:

ifeq ($(detected_OS),Windows)
    CFLAGS += -D WIN32
endif
ifeq ($(detected_OS),Darwin)        # Mac OS X
    CFLAGS += -D OSX
endif
ifeq ($(detected_OS),Linux)
    CFLAGS   +=   -D LINUX
endif
ifeq ($(detected_OS),GNU)           # Debian GNU Hurd
    CFLAGS   +=   -D GNU_HURD
endif
ifeq ($(detected_OS),GNU/kFreeBSD)  # Debian kFreeBSD
    CFLAGS   +=   -D GNU_kFreeBSD
endif
ifeq ($(detected_OS),FreeBSD)
    CFLAGS   +=   -D FreeBSD
endif
ifeq ($(detected_OS),NetBSD)
    CFLAGS   +=   -D NetBSD
endif
ifeq ($(detected_OS),DragonFly)
    CFLAGS   +=   -D DragonFly
endif
ifeq ($(detected_OS),Haiku)
    CFLAGS   +=   -D Haiku
endif

Notes:

  • Command uname is same as uname -s because option -s (--kernel-name) is the default. See why uname -s is better than uname -o.

  • The use of OS (instead of uname) simplifies the identification algorithm. You can still use solely uname, but you have to deal with if/else blocks to check all MinGW, Cygwin, etc. variations.

  • The environment variable OS is always set to "Windows_NT" on different Windows versions (see %OS% environment variable on Wikipedia).

  • An alternative of OS is the environment variable MSVC (it checks the presence of MS Visual Studio, see example using Visual C++).


Below I provide a complete example using make and gcc to build a shared library: *.so or *.dll depending on the platform. The example is as simplest as possible to be more understandable.

To install make and gcc on Windows see Cygwin or MinGW.

My example is based on five files

 +-- lib
 ¦   +-- Makefile
 ¦   +-- hello.h
 ¦   +-- hello.c
 +-- app
     +-- Makefile
     +-- main.c

Reminder: Makefile is indented using tabulation. Caution when copy-pasting below sample files.

The two Makefile files

1. lib/Makefile

ifeq ($(OS),Windows_NT)
    uname_S := Windows
else
    uname_S := $(shell uname -s)
endif

ifeq ($(uname_S), Windows)
    target = hello.dll
endif
ifeq ($(uname_S), Linux)
    target = libhello.so
endif
#ifeq ($(uname_S), .....) #See https://stackoverflow.com/a/27776822/938111
#    target = .....
#endif

%.o: %.c
    gcc  -c $<  -fPIC  -o $@
    # -c $<  => $< is first file after ':' => Compile hello.c
    # -fPIC  => Position-Independent Code (required for shared lib)
    # -o $@  => $@ is the target => Output file (-o) is hello.o

$(target): hello.o
    gcc  $^  -shared  -o $@
    # $^      => $^ expand to all prerequisites (after ':') => hello.o
    # -shared => Generate shared library
    # -o $@   => Output file (-o) is $@ (libhello.so or hello.dll)

2. app/Makefile

ifeq ($(OS),Windows_NT)
    uname_S := Windows
else
    uname_S := $(shell uname -s)
endif

ifeq ($(uname_S), Windows)
    target = app.exe
endif
ifeq ($(uname_S), Linux)
    target = app
endif
#ifeq ($(uname_S), .....) #See https://stackoverflow.com/a/27776822/938111
#    target = .....
#endif

%.o: %.c
    gcc  -c $< -I ../lib  -o $@
    # -c $<     => compile (-c) $< (first file after :) = main.c
    # -I ../lib => search headers (*.h) in directory ../lib
    # -o $@     => output file (-o) is $@ (target) = main.o

$(target): main.o
    gcc  $^  -L../lib  -lhello  -o $@
    # $^       => $^ (all files after the :) = main.o (here only one file)
    # -L../lib => look for libraries in directory ../lib
    # -lhello  => use shared library hello (libhello.so or hello.dll)
    # -o $@    => output file (-o) is $@ (target) = "app.exe" or "app"

To learn more, read Automatic Variables documentation as pointed out by cfi.

The source code

- lib/hello.h

#ifndef HELLO_H_
#define HELLO_H_

const char* hello();

#endif

- lib/hello.c

#include "hello.h"

const char* hello()
{
    return "hello";
}

- app/main.c

#include "hello.h" //hello()
#include <stdio.h> //puts()

int main()
{
    const char* str = hello();
    puts(str);
}

The build

Fix the copy-paste of Makefile (replace leading spaces by one tabulation).

> sed  's/^  */\t/'  -i  */Makefile

The make command is the same on both platforms. The given output is on Unix-like OSes:

> make -C lib
make: Entering directory '/tmp/lib'
gcc  -c hello.c  -fPIC  -o hello.o
# -c hello.c  => hello.c is first file after ':' => Compile hello.c
# -fPIC       => Position-Independent Code (required for shared lib)
# -o hello.o  => hello.o is the target => Output file (-o) is hello.o
gcc  hello.o  -shared  -o libhello.so
# hello.o        => hello.o is the first after ':' => Link hello.o
# -shared        => Generate shared library
# -o libhello.so => Output file (-o) is libhello.so (libhello.so or hello.dll)
make: Leaving directory '/tmp/lib'

> make -C app
make: Entering directory '/tmp/app'
gcc  -c main.c -I ../lib  -o main.o
# -c main.c => compile (-c) main.c (first file after :) = main.cpp
# -I ../lib => search headers (*.h) in directory ../lib
# -o main.o => output file (-o) is main.o (target) = main.o
gcc  main.o  -L../lib  -lhello  -o app
# main.o   => main.o (all files after the :) = main.o (here only one file)
# -L../lib => look for libraries in directory ../lib
# -lhello  => use shared library hello (libhello.so or hello.dll)
# -o app   => output file (-o) is app.exe (target) = "app.exe" or "app"
make: Leaving directory '/tmp/app'

The run

The application requires to know where is the shared library.

On Windows, a simple solution is to copy the library where the application is:

> cp -v lib/hello.dll app
`lib/hello.dll' -> `app/hello.dll'

On Unix-like OSes, you can use the LD_LIBRARY_PATH environment variable:

> export LD_LIBRARY_PATH=lib

Run the command on Windows:

> app/app.exe
hello

Run the command on Unix-like OSes:

> app/app
hello

Understanding the results of Execute Explain Plan in Oracle SQL Developer

The CBO builds a decision tree, estimating the costs of each possible execution path available per query. The costs are set by the CPU_cost or I/O_cost parameter set on the instance. And the CBO estimates the costs, as best it can with the existing statistics of the tables and indexes that the query will use. You should not tune your query based on cost alone. Cost allows you to understand WHY the optimizer is doing what it does. Without cost you could figure out why the optimizer chose the plan it did. Lower cost does not mean a faster query. There are cases where this is true and there will be cases where this is wrong. Cost is based on your table stats and if they are wrong the cost is going to be wrong.

When tuning your query, you should take a look at the cardinality and the number of rows of each step. Do they make sense? Is the cardinality the optimizer is assuming correct? Is the rows being return reasonable. If the information present is wrong then its very likely the optimizer doesn't have the proper information it needs to make the right decision. This could be due to stale or missing statistics on the table and index as well as cpu-stats. Its best to have stats updated when tuning a query to get the most out of the optimizer. Knowing your schema is also of great help when tuning. Knowing when the optimizer chose a really bad decision and pointing it in the correct path with a small hint can save a load of time.

Printing 2D array in matrix format

Your can do it like this in short hands.

        int[,] values=new int[2,3]{{2,4,5},{4,5,2}};

        for (int i = 0; i < values.GetLength(0); i++)
        {
            for (int k = 0; k < values.GetLength(1); k++) {
                Console.Write(values[i,k]);
            }

            Console.WriteLine();
        }

How to get $HOME directory of different user in bash script?

If the user doesn't exist, getent will return an error.

Here's a small shell function that doesn't ignore the exit code of getent:

get_home() {
  local result; result="$(getent passwd "$1")" || return
  echo $result | cut -d : -f 6
}

Here's a usage example:

da_home="$(get_home missing_user)" || {
  echo 'User does NOT exist!'; exit 1
}

# Now do something with $da_home
echo "Home directory is: '$da_home'"

How do I replace NA values with zeros in an R dataframe?

I know the question is already answered, but doing it this way might be more useful to some:

Define this function:

na.zero <- function (x) {
    x[is.na(x)] <- 0
    return(x)
}

Now whenever you need to convert NA's in a vector to zero's you can do:

na.zero(some.vector)

Python urllib2, basic HTTP authentication, and tr.im

Same solutions as Python urllib2 Basic Auth Problem apply.

see https://stackoverflow.com/a/24048852/1733117; you can subclass urllib2.HTTPBasicAuthHandler to add the Authorization header to each request that matches the known url.

class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
    '''Preemptive basic auth.

    Instead of waiting for a 403 to then retry with the credentials,
    send the credentials if the url is handled by the password manager.
    Note: please use realm=None when calling add_password.'''
    def http_request(self, req):
        url = req.get_full_url()
        realm = None
        # this is very similar to the code from retry_http_basic_auth()
        # but returns a request object.
        user, pw = self.passwd.find_user_password(realm, url)
        if pw:
            raw = "%s:%s" % (user, pw)
            auth = 'Basic %s' % base64.b64encode(raw).strip()
            req.add_unredirected_header(self.auth_header, auth)
        return req

    https_request = http_request

Get MAC address using shell script

I have used command hcicongif with two greps to separate the PC Mac address and I saved the MAC address to variable:

PCMAC=$( hciconfig -a | grep -E 'BD Address:' | grep -Eo '[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}' )

You can also use this command to check if MAC address is in valid format. Note, that only big chars A-F are allowed and also you need to add input for this grep command:

grep -E '[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}'

How to set the environmental variable LD_LIBRARY_PATH in linux

Add

LD_LIBRARY_PATH="/path/you/want1:/path/you/want/2"

to /etc/environment

See the Ubuntu Documentation.

CORRECTION: I should take my own advice and actually read the documentation. It says that this does not apply to LD_LIBRARY_PATH: Since Ubuntu 9.04 Jaunty Jackalope, LD_LIBRARY_PATH cannot be set in $HOME/.profile, /etc/profile, nor /etc/environment files. You must use /etc/ld.so.conf.d/.conf configuration files.* So user1824407's answer is spot on.

How to count occurrences of a column value efficiently in SQL?

I would do something like:

select
 A.id, A.age, B.count 
from 
 students A, 
 (select age, count(*) as count from students group by age) B
where A.age=B.age;

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

Swift 4

let collectionViewLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout
collectionViewLayout?.sectionInset = UIEdgeInsetsMake(0, 20, 0, 40) 
collectionViewLayout?.invalidateLayout()

How to fix Git error: object file is empty?

Had the same problem after checking out master from a clean branch. After a while I recognized a lot of modified files in master. I don't know why they have been there, after switching from a clean branch. Anyways, because the modified files made no sense to me, I just stashed them and the error was gone.

git:(master) git stash

AppFabric installation failed because installer MSI returned with error code : 1603

In my case it was a localgroup which was already existed through a previous install. Removing localgroup (AS_Observers) resolved my issue.

net localgroup AS_Observers /delete

hope this might help someone.

How do I run a docker instance from a DockerFile?

Download the file and from the same directory run docker build -t nodebb .

This will give you an image on your local machine that's named nodebb that you can launch an container from with docker run -d nodebb (you can change nodebb to your own name).

Disable scrolling in an iPhone web application?

document.ontouchmove = function(e){ 
    e.preventDefault(); 
}

is actually the best choice i found out it allows you to still be able to tap on input fields as well as drag things using jQuery UI draggable but it stops the page from scrolling.

What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

This is a known issue of the mssql ODBC driver. According to the Microsoft blog post:

The ColumnSize parameter of SQLBindParameter refers to the number of characters in the SQL type, while BufferLength is the number of bytes in the application's buffer. However, if the SQL data type is varchar(n) or char(n), the application binds the parameter as SQL_C_CHAR or SQL_C_VARCHAR, and the character encoding of the client is UTF-8, you may get a "String data, right truncation" error from the driver even if the value of ColumnSize is aligned with the size of the data type on the server. This error occurs since conversions between character encodings may change the length of the data. For example, a right apostrophe character (U+2019) is encoded in CP-1252 as the single byte 0x92, but in UTF-8 as the 3-byte sequence 0xe2 0x80 0x99.

You can find the full article here.

When should I use a List vs a LinkedList

In most cases, List<T> is more useful. LinkedList<T> will have less cost when adding/removing items in the middle of the list, whereas List<T> can only cheaply add/remove at the end of the list.

LinkedList<T> is only at it's most efficient if you are accessing sequential data (either forwards or backwards) - random access is relatively expensive since it must walk the chain each time (hence why it doesn't have an indexer). However, because a List<T> is essentially just an array (with a wrapper) random access is fine.

List<T> also offers a lot of support methods - Find, ToArray, etc; however, these are also available for LinkedList<T> with .NET 3.5/C# 3.0 via extension methods - so that is less of a factor.

Pass variables by reference in JavaScript

JavaScript not being strong type. It allows you to resolve problems in many different ways, as it seem in this question.

However, for a maintainability point of view, I would have to agree with Bart Hofland. A function should get arguments to do something with and return the result. Making them easily reusable.

If you feel that variables need to be passed by reference, you may be better served building them into objects, IMHO.

AngularJS : How to watch service variables?

Here's my generic approach.

mainApp.service('aService',[function(){
        var self = this;
        var callbacks = {};

        this.foo = '';

        this.watch = function(variable, callback) {
            if (typeof(self[variable]) !== 'undefined') {
                if (!callbacks[variable]) {
                    callbacks[variable] = [];
                }
                callbacks[variable].push(callback);
            }
        }

        this.notifyWatchersOn = function(variable) {
            if (!self[variable]) return;
            if (!callbacks[variable]) return;

            angular.forEach(callbacks[variable], function(callback, key){
                callback(self[variable]);
            });
        }

        this.changeFoo = function(newValue) {
            self.foo = newValue;
            self.notifyWatchersOn('foo');
        }

    }]);

In Your Controller

function FooCtrl($scope, aService) {
    $scope.foo;

    $scope._initWatchers = function() {
        aService.watch('foo', $scope._onFooChange);
    }

    $scope._onFooChange = function(newValue) {
        $scope.foo = newValue;
    }

    $scope._initWatchers();

}

FooCtrl.$inject = ['$scope', 'aService'];

What is the difference between cache and persist?

The difference between cache and persist operations is purely syntactic. cache is a synonym of persist or persist(MEMORY_ONLY), i.e. cache is merely persist with the default storage level MEMORY_ONLY

But Persist() We can save the intermediate results in 5 storage levels.

  1. MEMORY_ONLY
  2. MEMORY_AND_DISK
  3. MEMORY_ONLY_SER
  4. MEMORY_AND_DISK_SER
  5. DISK_ONLY

/** * Persist this RDD with the default storage level (MEMORY_ONLY). */
def persist(): this.type = persist(StorageLevel.MEMORY_ONLY)

/** * Persist this RDD with the default storage level (MEMORY_ONLY). */
def cache(): this.type = persist()

see more details here...


Caching or persistence are optimization techniques for (iterative and interactive) Spark computations. They help saving interim partial results so they can be reused in subsequent stages. These interim results as RDDs are thus kept in memory (default) or more solid storage like disk and/or replicated. RDDs can be cached using cache operation. They can also be persisted using persist operation.

#persist, cache

These functions can be used to adjust the storage level of a RDD. When freeing up memory, Spark will use the storage level identifier to decide which partitions should be kept. The parameter less variants persist() and cache() are just abbreviations for persist(StorageLevel.MEMORY_ONLY).

Warning: Once the storage level has been changed, it cannot be changed again!


Warning -Cache judiciously... see ((Why) do we need to call cache or persist on a RDD)

Just because you can cache a RDD in memory doesn’t mean you should blindly do so. Depending on how many times the dataset is accessed and the amount of work involved in doing so, recomputation can be faster than the price paid by the increased memory pressure.

It should go without saying that if you only read a dataset once there is no point in caching it, it will actually make your job slower. The size of cached datasets can be seen from the Spark Shell..

Listing Variants...

def cache(): RDD[T]
 def persist(): RDD[T]
 def persist(newLevel: StorageLevel): RDD[T]

See below example :

val c = sc.parallelize(List("Gnu", "Cat", "Rat", "Dog", "Gnu", "Rat"), 2)
     c.getStorageLevel
     res0: org.apache.spark.storage.StorageLevel = StorageLevel(false, false, false, false, 1)
     c.cache
     c.getStorageLevel
     res2: org.apache.spark.storage.StorageLevel = StorageLevel(false, true, false, true, 1)

enter image here

Note : Due to the very small and purely syntactic difference between caching and persistence of RDDs the two terms are often used interchangeably.

See more visually here....

Persist in memory and disk:

enter image description here

Cache

Caching can improve the performance of your application to a great extent.

enter image description here

How to update nested state properties in React

Although nesting isn't really how you should treat a component state, sometimes for something easy for single tier nesting.

For a state like this

state = {
 contact: {
  phone: '888-888-8888',
  email: '[email protected]'
 }
 address: {
  street:''
 },
 occupation: {
 }
}

A re-useable method ive used would look like this.

handleChange = (obj) => e => {
  let x = this.state[obj];
  x[e.target.name] = e.target.value;
  this.setState({ [obj]: x });
};

then just passing in the obj name for each nesting you want to address...

<TextField
 name="street"
 onChange={handleChange('address')}
 />

Git Commit Messages: 50/72 Formatting

Separation of presentation and data drives my commit messages here.

Your commit message should not be hard-wrapped at any character count and instead line breaks should be used to separate thoughts, paragraphs, etc. as part of the data, not the presentation. In this case, the "data" is the message you are trying to get across and the "presentation" is how the user sees that.

I use a single summary line at the top and I try to keep it short but I don't limit myself to an arbitrary number. It would be far better if Git actually provided a way to store summary messages as a separate entity from the message but since it doesn't I have to hack one in and I use the first line break as the delimiter (luckily, many tools support this means of breaking apart the data).

For the message itself newlines indicate something meaningful in the data. A single newline indicates a start/break in a list and a double newline indicates a new thought/idea.

This is a summary line, try to keep it short and end with a line break.
This is a thought, perhaps an explanation of what I have done in human readable format.  It may be complex and long consisting of several sentences that describe my work in essay format.  It is not up to me to decide now (at author time) how the user is going to consume this data.

Two line breaks separate these two thoughts.  The user may be reading this on a phone or a wide screen monitor.  Have you ever tried to read 72 character wrapped text on a device that only displays 60 characters across?  It is a truly painful experience.  Also, the opening sentence of this paragraph (assuming essay style format) should be an intro into the paragraph so if a tool chooses it may want to not auto-wrap and let you just see the start of each paragraph.  Again, it is up to the presentation tool not me (a random author at some point in history) to try to force my particular formatting down everyone else's throat.

Just as an example, here is a list of points:
* Point 1.
* Point 2.
* Point 3.

Here's what it looks like in a viewer that soft wraps the text.

This is a summary line, try to keep it short and end with a line break.

This is a thought, perhaps an explanation of what I have done in human readable format. It may be complex and long consisting of several sentences that describe my work in essay format. It is not up to me to decide now (at author time) how the user is going to consume this data.

Two line breaks separate these two thoughts. The user may be reading this on a phone or a wide screen monitor. Have you ever tried to read 72 character wrapped text on a device that only displays 60 characters across? It is a truly painful experience. Also, the opening sentence of this paragraph (assuming essay style format) should be an intro into the paragraph so if a tool chooses it may want to not auto-wrap and let you just see the start of each paragraph. Again, it is up to the presentation tool not me (a random author at some point in history) to try to force my particular formatting down everyone else's throat.

Just as an example, here is a list of points:
* Point 1.
* Point 2.
* Point 3.

My suspicion is that the author of Git commit message recommendation you linked has never written software that will be consumed by a wide array of end-users on different devices before (i.e., a website) since at this point in the evolution of software/computing it is well known that storing your data with hard-coded presentation information is a bad idea as far as user experience goes.

Sum the digits of a number

I cam up with a recursive solution:

def sumDigits(num):
#   print "evaluating:", num
  if num < 10:
    return num

  # solution 1
#   res = num/10
#   rem = num%10
#   print "res:", res, "rem:", rem
#   return sumDigits(res+rem)

    # solution 2
  arr = [int(i) for i in str(num)]
  return sumDigits(sum(arr))

# print(sumDigits(1))
# print(sumDigits(49))
print(sumDigits(439230))
# print(sumDigits(439237))

Fatal error: Call to undefined function: ldap_connect()

If you are a Windows user, this is a common error when you use XAMPP since LDAP is not enabled by default.

You can follow this steps to make sure LDAP works in your XAMPP:

  • [Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:

     extension=php_ldap.dll
    
  • Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin (Note: moving the file is needed only for XAMPP prior to version: 5.6.28)

  • Restart Apache.

  • You can now use functions of the LDAP Module!

If you use Linux:

For php5:

sudo apt-get install php5-ldap

For php7:

sudo apt-get install php7.0-ldap

If you are using the latest version of PHP you can do

sudo apt-get install php-ldap

running the above command should do the trick.

if for any reason it doesn't work check your php.ini configuration to enable ldap, remove the semicolon before extension=ldap to uncomment, save and restart Apache

SonarQube not picking up Unit Test Coverage

Include the sunfire and jacoco plugins in the pom.xml and Run the maven command as given below.

mvn jacoco:prepare-agent jacoco:report sonar:sonar

<properties>
    <surefire.version>2.17</surefire.version>
    <jacoco.version>0.7.2.201409121644</jacoco.version>

<plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>${surefire.version}</version>
        </plugin> 

        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>${jacoco.version}</version>

            <executions>
                <execution>
                    <id>default-prepare-agent</id>
                    <goals><goal>prepare-agent</goal></goals>
                </execution>
                <execution>
                    <id>default-report</id>
                    <phase>prepare-package</phase>
                    <goals><goal>report</goal></goals>
                </execution>
            </executions>
        </plugin>
    </plugins>

Inline functions in C#?

I know this question is about C#. However, you can write inline functions in .NET with F#. see: Use of `inline` in F#

Difference between socket and websocket?

Websockets use sockets in their implementation. Websockets are based on a standard protocol (now in final call, but not yet final) that defines a connection "handshake" and message "frame." The two sides go through the handshake procedure to mutually accept a connection and then use the standard message format ("frame") to pass messages back and forth.

I'm developing a framework that will allow you to communicate directly machine to machine with installed software. It might suit your purpose. You can follow my blog if you wish: http://highlevellogic.blogspot.com/2011/09/websocket-server-demonstration_26.html

Add a list item through javascript

The above answer was helpful for me, but it might be useful (or best practice) to add the name on submit, as I wound up doing. Hopefully this will be helpful to someone. CodePen Sample

    <form id="formAddName">
      <fieldset>
        <legend>Add Name </legend>
            <label for="firstName">First Name</label>
            <input type="text" id="firstName" name="firstName" />

        <button>Add</button>
      </fieldset>
    </form>

      <ol id="demo"></ol>

<script>
    var list = document.getElementById('demo');
    var entry = document.getElementById('formAddName');
    entry.onsubmit = function(evt) {
    evt.preventDefault();
    var firstName = document.getElementById('firstName').value;
    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(firstName));
    list.appendChild(entry);
  }
</script>

How to normalize a vector in MATLAB efficiently? Any related built-in function?

I don't know any MATLAB and I've never used it, but it seems to me you are dividing. Why? Something like this will be much faster:

d = 1/norm(V)
V1 = V * d

Angular2 get clicked element id

For TypeScript users:

    toggle(event: Event): void {
        let elementId: string = (event.target as Element).id;
        // do something with the id... 
    }

Python copy files to a new directory and rename if file name already exists

For me shutil.copy is the best:

import shutil

#make a copy of the invoice to work with
src="invoice.pdf"
dst="copied_invoice.pdf"
shutil.copy(src,dst)

You can change the path of the files as you want.

How to use default Android drawables

As far as i remember, the documentation advises against using the menu icons from android.R.drawable directly and recommends copying them to your drawables folder. The main reason is that those icons and names can be subject to change and may not be available in future releases.

Warning: Because these resources can change between platform versions, you should not reference these icons using the Android platform resource IDs (i.e. menu icons under android.R.drawable). If you want to use any icons or other internal drawable resources, you should store a local copy of those icons or drawables in your application resources, then reference the local copy from your application code. In that way, you can maintain control over the appearance of your icons, even if the system's copy changes.

from: http://developer.android.com/guide/practices/ui_guidelines/icon_design_menu.html

At least one JAR was scanned for TLDs yet contained no TLDs

For anyone trying to get this working using the Sysdeo Eclipse Tomcat plugin, try the following steps (I used Sysdeo Tomcat Plugin 3.3.0, Eclipse Kepler, and Tomcat 7.0.53 to construct these steps):

  1. Window --> Preferences --> Expand the Tomcat node in the tree --> JVM Settings
  2. Under "Append to JVM Parameters", click the "Add" button.
  3. In the "New Tomcat JVM parameter" popup, enter -Djava.util.logging.config.file="{TOMCAT_HOME}\conf\logging.properties", where {TOMCAT_HOME} is the path to your Tomcat directory (example: C:\Tomcat\apache-tomcat-7.0.53\conf\logging.properties). Click OK.
  4. Under "Append to JVM Parameters", click the "Add" button again.
  5. In the "New Tomcat JVM parameter" popup, enter -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager. Click OK.
  6. Click OK in the Preferences window.
  7. Make the adjustments to the {TOMCAT_HOME}\conf\logging.properties file as specified in the question above.
  8. The next time you start Tomcat in Eclipse, you should see the scanned .jars listed in the Eclipse Console instead of the "Enable debug logging for this logger" message. The information should also be logged in {TOMCAT_HOME}\logs\catalina.yyyy-mm-dd.log.

How to clear the canvas for redrawing

Given that canvas is a canvas element,

const context = canvas.getContext('2d');

context.clearRect(0, 0, canvas.width, canvas.height);

How to solve WAMP and Skype conflict on Windows 7?

Detail blog to fix this issue is : http://goo.gl/JXWqfJ

You can solve this problem by following two ways:
A) Start your WAMP befor you login to skype. So that WAMP will take over the the port and there will be no conflict with the port number. And you are able to use Skype as well as WAMP.
But this is not the permanent solution for your problem. Whenever you want to start WAMP you need to signout Skype first and than only you are able to start WAMP. Which is really i don’t like.

B) Second option is to change the port of Skype itself, so that it will not conflict with WAMP. Following screen/steps will help you to solve this problem:
1) SignIn to Skype.
2) Got to the Tools -> options
3) Select the “Advanced” -> Connection
4) Unchecked “Use port 80 and 443 as alternatives for incoming connections” checkbox and click save.
5) Now Signout and SignIn again to skype. (this change will take affect only you relogin to skype)
Now every time you start WAMP will not conflict with skype.

How Does Modulus Divison Work

27 % 16 = 11

You can interpret it this way:

16 goes 1 time into 27 before passing it.

16 * 2 = 32.

So you could say that 16 goes one time in 27 with a remainder of 11.

In fact,

16 + 11 = 27

An other exemple:

20 % 3 = 2

Well 3 goes 6 times into 20 before passing it.

3 * 6 = 18

To add-up to 20 we need 2 so the remainder of the modulus expression is 2.

Add borders to cells in POI generated Excel File

HSSFCellStyle style=workbook.createCellStyle();
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

How to open a page in a new window or tab from code-behind

Target= "_blank"

This does it in html, give it a try in C#

How Do I Insert a Byte[] Into an SQL Server VARBINARY Column

My solution would be to use a parameterised query, as the connectivity objects take care of formatting the data correctly (including ensuring the correct data-type, and escaping "dangerous" characters where applicable):

// Assuming "conn" is an open SqlConnection
using(SqlCommand cmd = new SqlCommand("INSERT INTO mssqltable(varbinarycolumn) VALUES (@binaryValue)", conn))
{
    // Replace 8000, below, with the correct size of the field
    cmd.Parameters.Add("@binaryValue", SqlDbType.VarBinary, 8000).Value = arraytoinsert;
    cmd.ExecuteNonQuery();
}

Edit: Added the wrapping "using" statement as suggested by John Saunders to correctly dispose of the SqlCommand after it is finished with

How to compare datetime with only date in SQL Server

According to your query Select * from [User] U where U.DateCreated = '2014-02-07'

SQL Server is comparing exact date and time i.e (comparing 2014-02-07 12:30:47.220 with 2014-02-07 00:00:00.000 for equality). that's why result of comparison is false

Therefore, While comparing dates you need to consider time also. You can use
Select * from [User] U where U.DateCreated BETWEEN '2014-02-07' AND '2014-02-08'.

CSS3 100vh not constant in mobile browser

The VH 100 does not work well on mobile as it does not factor in the iOS bar (or similar functionality on other platforms).

One solution that works well is to use JavaScript "window.innerHeight".

Simply assign the height of the element to this value e.g. $('.element-name').height(window.innerHeight);

Note: It may be useful to create a function in JS, so that the height can change when the screen is resized. However, I would suggest only calling the function when the width of the screen is changed, this way the element will not jump in height when the iOS bar disappears when the user scrolls down the page.

Calculate MD5 checksum for a file

I know that I am late to party but performed test before actually implement the solution.

I did perform test against inbuilt MD5 class and also md5sum.exe. In my case inbuilt class took 13 second where md5sum.exe too around 16-18 seconds in every run.

    DateTime current = DateTime.Now;
    string file = @"C:\text.iso";//It's 2.5 Gb file
    string output;
    using (var md5 = MD5.Create())
    {
        using (var stream = File.OpenRead(file))
        {
            byte[] checksum = md5.ComputeHash(stream);
            output = BitConverter.ToString(checksum).Replace("-", String.Empty).ToLower();
            Console.WriteLine("Total seconds : " + (DateTime.Now - current).TotalSeconds.ToString() + " " + output);
        }
    }

How to unbind a listener that is calling event.preventDefault() (using jQuery)?

The best way to do this by using namespace. It is a safe and secure way. Here .rb is the namespace which ensures unbind function works on that particular keydown but not on others.

$(document).bind('keydown.rb','Ctrl+r',function(e){
            e.stopImmediatePropagation();
            return false;
        });

$(document).unbind('keydown.rb');

ref1: http://idodev.co.uk/2014/01/safely-binding-to-events-using-namespaces-in-jquery/

ref2: http://jqfundamentals.com/chapter/events

Change GridView row color based on condition

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    e.Row.Attributes.Add("style", "cursor:help;");
    if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Alternate)
    { 
        if (e.Row.RowType == DataControlRowType.DataRow)
        {                
            e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='orange'");
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#E56E94'");
            e.Row.BackColor = Color.FromName("#E56E94");                
        }           
    }
    else
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='orange'");
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='gray'");
            e.Row.BackColor = Color.FromName("gray");                
        }           
    }
}

How to resolve conflicts in EGit

This approach is similar to "stash" solution but I think it might be more clear:

  1. Your current local branch is "master" and you have local changes.
  2. After synchronizing, there are incoming changes and some files need to be merged.
  3. So, the first step is to switch to a new local branch (say "my_changes"):
    • Team -> Switch To -> New branch
      • Branch name: my_changes (for example)
  4. After switching to the new branch, the uncommitted local changes still exist. So, commit all your local uncommitted changes to the new branch "my_changes":
  5. Switch back to the local "master" branch:
    • Team -> Switch To -> master
  6. Now, when you choose Team -> Synchronize Workspace, no "merge" files are expected to appear.
  7. Select Team -> Pull
    • Now the local "master" branch is up to date with respect to the remote "master" branch.
  8. Now, there are two options:
    • Option 1:
      • Select Team -> Merge to merge the original local changes from "my_changes" local branch into "master" local branch.
      • Now commit the incoming changes from the previous step into the local "master" branch and push them to the remote "master" branch.
    • Option 2:
      • Switch again to "my_changes" local branch.
      • Merge the updates from the local "master" branch into "my_changes" branch.
      • Proceed with the current task in "my_changes" branch.
      • When the task is done, use Option 1 above to update both the local "master" branch as well as the remote one.

html select option separator

Instead of the regular hyphon I replaced it using a horizontal bar symbol from the extended character set, it won't look very nice if the user is in another country that replaces that character but works fine for me. There is a range of different chacters you could use for some great effects and there is no css involved.

<option value='-' disabled>----</option>

Check if string contains \n Java

I'd rather trust JDK over System property. Following is a working snippet.

    private boolean checkIfStringContainsNewLineCharacters(String str){
        if(!StringUtils.isEmpty(str)){
            Scanner scanner = new Scanner(str);
            scanner.nextLine();
            boolean hasNextLine =  scanner.hasNextLine();
            scanner.close();
            return hasNextLine;
        }
        return false;
    }

How to invoke the super constructor in Python?

One way is to call A's constructor and pass self as an argument, like so:

class B(A):
    def __init__(self):
        A.__init__(self)
        print "hello"

The advantage of this style is that it's very clear. It call A's initialiser. The downside is that it doesn't handle diamond-shaped inheritance very well, since you may end up calling the shared base class's initialiser twice.

Another way is to use super(), as others have shown. For single-inheritance, it does basically the same thing as letting you call the parent's initialiser.

However, super() is quite a bit more complicated under-the-hood and can sometimes be counter-intuitive in multiple inheritance situations. On the plus side, super() can be used to handle diamond-shaped inheritance. If you want to know the nitty-gritty of what super() does, the best explanation I've found for how super() works is here (though I'm not necessarily endorsing that article's opinions).

SQL Server database backup restore on lower version

Go to Task->Generate Scripts...

In Advanced in "Types of data for script" select "Schema and data" and try to run this script in your lower version.

Get webpage contents with Python?

The best way to do this these day is to use the 'requests' library:

import requests
response = requests.get('http://hiscore.runescape.com/index_lite.ws?player=zezima')
print (response.status_code)
print (response.content)

Programmatically obtain the phone number of the Android phone

Update: This answer is no longer available as Whatsapp had stopped exposing the phone number as account name, kindly disregard this answer.

There is actually an alternative solution you might want to consider, if you can't get it through telephony service.

As of today, you can rely on another big application Whatsapp, using AccountManager. Millions of devices have this application installed and if you can't get the phone number via TelephonyManager, you may give this a shot.

Permission:

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

Code:

AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccounts();

for (Account ac : accounts) {
    String acname = ac.name;
    String actype = ac.type;
    // Take your time to look at all available accounts
    System.out.println("Accounts : " + acname + ", " + actype);
}

Check actype for WhatsApp account

if(actype.equals("com.whatsapp")){
    String phoneNumber = ac.name;
}

Of course you may not get it if user did not install WhatsApp, but its worth to try anyway. And remember you should always ask user for confirmation.

Count records for every month in a year

Try This query:

SELECT 
  SUM(CASE datepart(month,ARR_DATE) WHEN 1 THEN 1 ELSE 0 END) AS 'January',
  SUM(CASE datepart(month,ARR_DATE) WHEN 2 THEN 1 ELSE 0 END) AS 'February',
  SUM(CASE datepart(month,ARR_DATE) WHEN 3 THEN 1 ELSE 0 END) AS 'March',
  SUM(CASE datepart(month,ARR_DATE) WHEN 4 THEN 1 ELSE 0 END) AS 'April',
  SUM(CASE datepart(month,ARR_DATE) WHEN 5 THEN 1 ELSE 0 END) AS 'May',
  SUM(CASE datepart(month,ARR_DATE) WHEN 6 THEN 1 ELSE 0 END) AS 'June',
  SUM(CASE datepart(month,ARR_DATE) WHEN 7 THEN 1 ELSE 0 END) AS 'July',
  SUM(CASE datepart(month,ARR_DATE) WHEN 8 THEN 1 ELSE 0 END) AS 'August',
  SUM(CASE datepart(month,ARR_DATE) WHEN 9 THEN 1 ELSE 0 END) AS 'September',
  SUM(CASE datepart(month,ARR_DATE) WHEN 10 THEN 1 ELSE 0 END) AS 'October',
  SUM(CASE datepart(month,ARR_DATE) WHEN 11 THEN 1 ELSE 0 END) AS 'November',
  SUM(CASE datepart(month,ARR_DATE) WHEN 12 THEN 1 ELSE 0 END) AS 'December',
  SUM(CASE datepart(year,ARR_DATE) WHEN 2012 THEN 1 ELSE 0 END) AS 'TOTAL'
FROM
    sometable
WHERE
  ARR_DATE BETWEEN '2012/01/01' AND '2012/12/31' 

Set Locale programmatically

For those who tried everything but not not working. Please check that if you set darkmode with AppCompatDelegate.setDefaultNightMode and the system is not dark, then Configuration.setLocale will not work above Andorid 7.0.

Add this code in your every activity to solve this issue:

override fun applyOverrideConfiguration(overrideConfiguration: Configuration?) {
  if (overrideConfiguration != null) {
    val uiMode = overrideConfiguration.uiMode
    overrideConfiguration.setTo(baseContext.resources.configuration)
    overrideConfiguration.uiMode = uiMode
  }
  super.applyOverrideConfiguration(overrideConfiguration)
}

Links in <select> dropdown options

Maybe this will help:

<select onchange="location = this.value;">
 <option value="home.html">Home</option>
 <option value="contact.html">Contact</option>
 <option value="about.html">About</option>
</select>

How to force a list to be vertical using html css

Hope this is your structure:

   <ul> 
     <li>
        <div ><img.. /><p>text</p></div>
    </li>
     <li>
        <div ><img.. /><p>text</p></div>
    </li>
     <li>
        <div ><img.. /><p>text</p></div>
    </li>
   </ul> 

By default, it will be add one after another row:

-----
-----
-----

if you want to make it vertical, just add float left to li, give width and height, make sure that content will not break the width:

|  |  |
|  |  |

li
{
   display:block;
   float:left;
   width:300px; /* adjust */
   height:150px; /* adjust */
   padding: 5px; /*adjust*/
}

Uncaught TypeError: Cannot read property 'msie' of undefined

$.browser was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.

Python socket.error: [Errno 111] Connection refused

The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND command on another connection, but it apparently was "not opening [it] up in sync with the client side".

Well, the main reason would be there was no synchronisation whatsoever. Calling:

cs.send("SEND " + FILE)
cs.close()

would just place the data into a OS buffer; close would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep after close might mitigate the problem, but this is not synchronisation.

The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK, or better PORT 36250 to indicate where to connect). This would make sure the server is already listening.

The other thing is you must check the return values of send to make sure how many bytes was taken from your buffer. Or use sendall.

(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)

Microsoft Excel mangles Diacritics in .csv files?

A correctly formatted UTF8 file can have a Byte Order Mark as its first three octets. These are the hex values 0xEF, 0xBB, 0xBF. These octets serve to mark the file as UTF8 (since they are not relevant as "byte order" information).1 If this BOM does not exist, the consumer/reader is left to infer the encoding type of the text. Readers that are not UTF8 capable will read the bytes as some other encoding such as Windows-1252 and display the characters  at the start of the file.

There is a known bug where Excel, upon opening UTF8 CSV files via file association, assumes that they are in a single-byte encoding, disregarding the presence of the UTF8 BOM. This can not be fixed by any system default codepage or language setting. The BOM will not clue in Excel - it just won't work. (A minority report claims that the BOM sometimes triggers the "Import Text" wizard.) This bug appears to exist in Excel 2003 and earlier. Most reports (amidst the answers here) say that this is fixed in Excel 2007 and newer.

Note that you can always* correctly open UTF8 CSV files in Excel using the "Import Text" wizard, which allows you to specify the encoding of the file you're opening. Of course this is much less convenient.

Readers of this answer are most likely in a situation where they don't particularly support Excel < 2007, but are sending raw UTF8 text to Excel, which is misinterpreting it and sprinkling your text with à and other similar Windows-1252 characters. Adding the UTF8 BOM is probably your best and quickest fix.

If you are stuck with users on older Excels, and Excel is the only consumer of your CSVs, you can work around this by exporting UTF16 instead of UTF8. Excel 2000 and 2003 will double-click-open these correctly. (Some other text editors can have issues with UTF16, so you may have to weigh your options carefully.)


* Except when you can't, (at least) Excel 2011 for Mac's Import Wizard does not actually always work with all encodings, regardless of what you tell it. </anecdotal-evidence> :)

C: What is the difference between ++i and i++?

Shortly:

++i and i++ works same if you are not writing them in a function. If you use something like function(i++) or function(++i) you can see the difference.

function(++i) says first increment i by 1, after that put this i into the function with new value.

function(i++) says put first i into the function after that increment i by 1.

int i=4;
printf("%d\n",pow(++i,2));//it prints 25 and i is 5 now
i=4;
printf("%d",pow(i++,2));//it prints 16 i is 5 now

How to get two or more commands together into a batch file

set "PathName=X:\Web Content Mgmt\Completed Filtering\2013_Folder"
set "comd=dir /b /s *.zip"
cd /d "%PathName%"
%comd%

How To fix white screen on app Start up?

enter image description here

Like you tube.. initially they show icon screen instead of white screen. And after 2 seconds shows home screen.

first create an XML drawable in res/drawable.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@color/gray"/>

    <item>
        <bitmap
            android:gravity="center"
            android:src="@mipmap/ic_launcher"/>
    </item>

</layer-list>

Next, you will set this as your splash activity’s background in the theme. Navigate to your styles.xml file and add a new theme for your splash activity

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

    <style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
        <item name="android:windowBackground">@drawable/background_splash</item>
    </style>

</resources>

In your new SplashTheme, set the window background attribute to your XML drawable. Configure this as your splash activity’s theme in your AndroidManifest.xml:

<activity
    android:name=".SplashActivity"
    android:theme="@style/SplashTheme">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

This link gives what you want. step by step procedure. https://www.bignerdranch.com/blog/splash-screens-the-right-way/

UPDATE:

The layer-list can be even simpler like this (which also accepts vector drawables for the centered logo, unlike the <bitmap> tag):

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Background color -->
    <item android:drawable="@color/gray"/>

    <!-- Logo at the center of the screen -->
    <item
        android:drawable="@mipmap/ic_launcher"
        android:gravity="center"/>
</layer-list>

How can I hide/show a div when a button is clicked?

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Show and hide div with JavaScript</title>
<script>

    var button_beg = '<button id="button" onclick="showhide()">', button_end = '</button>';
    var show_button = 'Show', hide_button = 'Hide';
    function showhide() {
        var div = document.getElementById( "hide_show" );
        var showhide = document.getElementById( "showhide" );
        if ( div.style.display !== "none" ) {
            div.style.display = "none";
            button = show_button;
            showhide.innerHTML = button_beg + button + button_end;
        } else {
            div.style.display = "block";
            button = hide_button;
            showhide.innerHTML = button_beg + button + button_end;
        }
    }
    function setup_button( status ) {
        if ( status == 'show' ) {
            button = hide_button;
        } else {
            button = show_button;
        }
        var showhide = document.getElementById( "showhide" );
        showhide.innerHTML = button_beg + button + button_end;
    }
    window.onload = function () {
        setup_button( 'hide' );
        showhide(); // if setup_button is set to 'show' comment this line
    }
</script>
</head>
<body>
    <div id="showhide"></div>
    <div id="hide_show">
        <p>This div will be show and hide on button click</p>
    </div>
</body>
</html>

Google Apps Script to open a URL

There really isn't a need to create a custom click event as suggested in the bountied answer or to show the url as suggested in the accepted answer.

window.open(url)1 does open web pages automatically without user interaction, provided pop- up blockers are disabled(as is the case with Stephen's answer)

openUrl.html

<!DOCTYPE html>
<html>
  <head>
   <base target="_blank">
    <script>
     var url1 ='https://stackoverflow.com/a/54675103';
     var winRef = window.open(url1);
     winRef ? google.script.host.close() : window.alert('Allow popup to redirect you to '+url1) ;
     window.onload=function(){document.getElementById('url').href = url1;}
    </script>
  </head>
  <body>
    Kindly allow pop ups</br>
    Or <a id='url'>Click here </a>to continue!!!
  </body>
</html>

code.gs:

function modalUrl(){
  SpreadsheetApp.getUi()
   .showModalDialog(
     HtmlService.createHtmlOutputFromFile('openUrl').setHeight(50),
     'Opening StackOverflow'
   )
}    

'invalid value encountered in double_scalars' warning, possibly numpy

Whenever you are working with csv imports, try to use df.dropna() to avoid all such warnings or errors.

How can I use a custom font in Java?

If you want to use the font to draw with graphics2d or similar, this works:

InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream("roboto-bold.ttf")
Font font = Font.createFont(Font.TRUETYPE_FONT, stream).deriveFont(48f)

Fast ceiling of an integer division in C / C++

Compile with O3, The compiler performs optimization well.

q = x / y;
if (x % y)  ++q;

Best practice to call ConfigureAwait for all server-side code

Brief answer to your question: No. You shouldn't call ConfigureAwait(false) at the application level like that.

TL;DR version of the long answer: If you are writing a library where you don't know your consumer and don't need a synchronization context (which you shouldn't in a library I believe), you should always use ConfigureAwait(false). Otherwise, the consumers of your library may face deadlocks by consuming your asynchronous methods in a blocking fashion. This depends on the situation.

Here is a bit more detailed explanation on the importance of ConfigureAwait method (a quote from my blog post):

When you are awaiting on a method with await keyword, compiler generates bunch of code in behalf of you. One of the purposes of this action is to handle synchronization with the UI (or main) thread. The key component of this feature is the SynchronizationContext.Current which gets the synchronization context for the current thread. SynchronizationContext.Current is populated depending on the environment you are in. The GetAwaiter method of Task looks up for SynchronizationContext.Current. If current synchronization context is not null, the continuation that gets passed to that awaiter will get posted back to that synchronization context.

When consuming a method, which uses the new asynchronous language features, in a blocking fashion, you will end up with a deadlock if you have an available SynchronizationContext. When you are consuming such methods in a blocking fashion (waiting on the Task with Wait method or taking the result directly from the Result property of the Task), you will block the main thread at the same time. When eventually the Task completes inside that method in the threadpool, it is going to invoke the continuation to post back to the main thread because SynchronizationContext.Current is available and captured. But there is a problem here: the UI thread is blocked and you have a deadlock!

Also, here are two great articles for you which are exactly for your question:

Finally, there is a great short video from Lucian Wischik exactly on this topic: Async library methods should consider using Task.ConfigureAwait(false).

Hope this helps.

How to download/checkout a project from Google Code in Windows?

If you don't want to install TortoiseSVN, you can simply install 'Subversion for Windows' from here:

http://sourceforge.net/projects/win32svn/

After installing, just open up a command prompt, go the folder you want to download into, then past in the checkout command as indicated on the project's 'source' page. E.g.

svn checkout http://projectname.googlecode.com/svn/trunk/ projectname-read-only

Note the space between the URL and the last string is intentional, the last string is the folder name into which the source will be downloaded.

Change font size of UISegmentedControl

Daniel pointed me to correct way. I used it like this-

float scaleFactor = 0.8f;

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc]
initWithFrame:CGRectMake(10, 70, 300/scaleFactor,35)];

[segmentedControl insertSegmentWithTitle:@"..." atIndex:0 animated:NO];
[segmentedControl insertSegmentWithTitle:@"..." atIndex:1 animated:NO];
[segmentedControl insertSegmentWithTitle:@"..." atIndex:2 animated:NO];

segmentedControl.transform = CGAffineTransformMakeScale(scaleFactor, 1);
CGPoint segmentedControlCenter = segmentedControl.center;
segmentedControlCenter.x = self.center.x;
segmentedControl.center = segmentedControlCenter;

C# Creating and using Functions

Note: in C# the term "function" is often replaced by the term "method". For the sake of this question there is no difference, so I'll just use the term "function".

Thats not true. you may read about (func type+ Lambda expressions),( anonymous function"using delegates type"),(action type +Lambda expressions ),(Predicate type+Lambda expressions). etc...etc... this will work.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

           int a;
           int b;
           int c;

           Console.WriteLine("Enter value of 'a':");
           a = Convert.ToInt32(Console.ReadLine());

           Console.WriteLine("Enter value of 'b':");
           b = Convert.ToInt32(Console.ReadLine());

           Func<int, int, int> funcAdd = (x, y) => x + y;
           c=funcAdd.Invoke(a, b);
           Console.WriteLine(Convert.ToString(c));

        }

     }
}

Difference between 'cls' and 'self' in Python classes?

It's used in case of a class method. Check this reference for further details.

EDIT: As clarified by Adrien, it's a convention. You can actually use anything but cls and self are used (PEP8).

Changing every value in a hash in Ruby

A bit more readable one, map it to an array of single-element hashes and reduce that with merge

the_hash.map{ |key,value| {key => "%#{value}%"} }.reduce(:merge)

How to change the default collation of a table?

To change the default character set and collation of a table including those of existing columns (note the convert to clause):

alter table <some_table> convert to character set utf8mb4 collate utf8mb4_unicode_ci;

Edited the answer, thanks to the prompting of some comments:

Should avoid recommending utf8. It's almost never what you want, and often leads to unexpected messes. The utf8 character set is not fully compatible with UTF-8. The utf8mb4 character set is what you want if you want UTF-8. – Rich Remer Mar 28 '18 at 23:41

and

That seems quite important, glad I read the comments and thanks @RichRemer . Nikki , I think you should edit that in your answer considering how many views this gets. See here https://dev.mysql.com/doc/refman/8.0/en/charset-unicode-utf8.html and here What is the difference between utf8mb4 and utf8 charsets in MySQL? – Paulpro Mar 12 at 17:46

Is it possible to declare a public variable in vba and assign a default value?

It's been quite a while, but this may satisfy you :

Public MyVariable as Integer: MyVariable = 123

It's a bit ugly since you have to retype the variable name, but it's on one line.

What is the difference between id and class in CSS, and when should I use them?

This is very simple to understand :-

id is used when we have to apply CSS property to one attribute only.

class is used when we have to use CSS property in many locations within the same page or different.

General :- for unique structure like staring div and buttons layout we use id .

for same CSS throughout the page or project we use class

id is light and class is little heavy

How to find out if an installed Eclipse is 32 or 64 bit version?

Go to the Eclipse base folder ? open eclipse.ini ? you will find the below line at line no 4:

plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20150204-1316 plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20120913-144807

As you can see, line 1 is of 64-bit Eclipse. It contains x86_64 and line 2 is of 32-bit Eclipse. It contains x_86.

For 32-bit Eclipse only x86 will be present and for 64-bit Eclipse x86_64 will be present.

How to turn off gcc compiler optimization to enable buffer overflow

On newer distros (as of 2016), it seems that PIE is enabled by default so you will need to disable it explicitly when compiling.

Here's a little summary of commands which can be helpful when playing locally with buffer overflow exercises in general:

Disable canary:

gcc vuln.c -o vuln_disable_canary -fno-stack-protector

Disable DEP:

gcc vuln.c -o vuln_disable_dep -z execstack

Disable PIE:

gcc vuln.c -o vuln_disable_pie -no-pie

Disable all of protection mechanisms listed above (warning: for local testing only):

gcc vuln.c -o vuln_disable_all -fno-stack-protector -z execstack -no-pie

For 32-bit machines, you'll need to add the -m32 parameter as well.

Spring-boot default profile for integration tests

Another way to do this is to define a base (abstract) test class that your actual test classes will extend :

@RunWith(SpringRunner.class)
@SpringBootTest()
@ActiveProfiles("staging")
public abstract class BaseIntegrationTest {
}

Concrete test :

public class SampleSearchServiceTest extends BaseIntegrationTest{

    @Inject
    private SampleSearchService service;

    @Test
    public void shouldInjectService(){
        assertThat(this.service).isNotNull();
    }
} 

This allows you to extract more than just the @ActiveProfiles annotation. You could also imagine more specialised base classes for different kinds of integration tests, e.g. data access layer vs service layer, or for functional specialties (common @Before or @After methods etc).

Is there a Visual Basic 6 decompiler?

In my own experience where I needed to try and find out what some old VB6 programs were doing, I turned to Process Explorer (Sysinternals). I did the following:

  1. Run Process Explorer
  2. Run VB6 .exe
  3. Locate exe in Process Explorer
  4. Right click on process
  5. Check the "Strings" tab

This didn't show the actual functions, but it listed their names, folders of where files were being copied from and to and if it accessed a DB it would also display the connection string. Enough to help you get an idea, but may be useless for complex programs. The programs I was looking at were pretty basic (no pun intended).

YMMV.

Redirect on Ajax Jquery Call

For ExpressJs router:

router.post('/login', async(req, res) => {
    return res.send({redirect: '/yoururl'});
})

Client-side:

    success: function (response) {
        if (response.redirect) {
            window.location = response.redirect
        }
    },

How to parse JSON in Kotlin?

There is no question that the future of parsing in Kotlin will be with kotlinx.serialization. It is part of Kotlin libraries. Version kotlinx.serialization 1.0 is finally released

https://github.com/Kotlin/kotlinx.serialization

import kotlinx.serialization.*
import kotlinx.serialization.json.JSON

@Serializable
data class MyModel(val a: Int, @Optional val b: String = "42")

fun main(args: Array<String>) {

    // serializing objects
    val jsonData = JSON.stringify(MyModel.serializer(), MyModel(42))
    println(jsonData) // {"a": 42, "b": "42"}
    
    // serializing lists
    val jsonList = JSON.stringify(MyModel.serializer().list, listOf(MyModel(42)))
    println(jsonList) // [{"a": 42, "b": "42"}]

    // parsing data back
    val obj = JSON.parse(MyModel.serializer(), """{"a":42}""")
    println(obj) // MyModel(a=42, b="42")
}

Test if string is a number in Ruby on Rails

Create is_number? Method.

Create a helper method:

def is_number? string
  true if Float(string) rescue false
end

And then call it like this:

my_string = '12.34'

is_number?( my_string )
# => true

Extend String Class.

If you want to be able to call is_number? directly on the string instead of passing it as a param to your helper function, then you need to define is_number? as an extension of the String class, like so:

class String
  def is_number?
    true if Float(self) rescue false
  end
end

And then you can call it with:

my_string.is_number?
# => true

Difference between Math.Floor() and Math.Truncate()

Follow these links for the MSDN descriptions of:

  • Math.Floor, which rounds down towards negative infinity.
  • Math.Ceiling, which rounds up towards positive infinity.
  • Math.Truncate, which rounds up or down towards zero.
  • Math.Round, which rounds to the nearest integer or specified number of decimal places. You can specify the behavior if it's exactly equidistant between two possibilities, such as rounding so that the final digit is even ("Round(2.5,MidpointRounding.ToEven)" becoming 2) or so that it's further away from zero ("Round(2.5,MidpointRounding.AwayFromZero)" becoming 3).

The following diagram and table may help:

-3        -2        -1         0         1         2         3
 +--|------+---------+----|----+--|------+----|----+-------|-+
    a                     b       c           d            e

                       a=-2.7  b=-0.5  c=0.3  d=1.5  e=2.8
                       ======  ======  =====  =====  =====
Floor                    -3      -1      0      1      2
Ceiling                  -2       0      1      2      3
Truncate                 -2       0      0      1      2
Round (ToEven)           -3       0      0      2      3
Round (AwayFromZero)     -3      -1      0      2      3

Note that Round is a lot more powerful than it seems, simply because it can round to a specific number of decimal places. All the others round to zero decimals always. For example:

n = 3.145;
a = System.Math.Round (n, 2, MidpointRounding.ToEven);       // 3.14
b = System.Math.Round (n, 2, MidpointRounding.AwayFromZero); // 3.15

With the other functions, you have to use multiply/divide trickery to achieve the same effect:

c = System.Math.Truncate (n * 100) / 100;                    // 3.14
d = System.Math.Ceiling (n * 100) / 100;                     // 3.15

How do I set the size of an HTML text box?

Elements can be sized with the height and width attributes.

Bash script to cd to directory with spaces in pathname

You can use any of:

cd ~/"My Code"
cd ~/M"y Code"
cd ~/My" Code"

You cannot use:

cd ~"/My Code"

The first works because the shell expands ~/ into $HOME/, and then tacks on My Code without the double quotes. The second fails because there isn't a user called '"' (double quote) for ~" to map to.

Close virtual keyboard on button press

Crash Null Point Exception Fix: I had a case where the keyboard might not open when the user clicks the button. You have to write an if statement to check that getCurrentFocus() isn't a null:

            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if(getCurrentFocus() != null) {
            inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

Mockito: List Matchers with generics

In addition to anyListOf above, you can always specify generics explicitly using this syntax:

when(mock.process(Matchers.<List<Bar>>any(List.class)));

Java 8 newly allows type inference based on parameters, so if you're using Java 8, this may work as well:

when(mock.process(Matchers.any()));

Remember that neither any() nor anyList() will apply any checks, including type or null checks. In Mockito 2.x, any(Foo.class) was changed to mean "any instanceof Foo", but any() still means "any value including null".

NOTE: The above has switched to ArgumentMatchers in newer versions of Mockito, to avoid a name collision with org.hamcrest.Matchers. Older versions of Mockito will need to keep using org.mockito.Matchers as above.

How to define partitioning of DataFrame?

Spark >= 2.3.0

SPARK-22614 exposes range partitioning.

val partitionedByRange = df.repartitionByRange(42, $"k")

partitionedByRange.explain
// == Parsed Logical Plan ==
// 'RepartitionByExpression ['k ASC NULLS FIRST], 42
// +- AnalysisBarrier Project [_1#2 AS k#5, _2#3 AS v#6]
// 
// == Analyzed Logical Plan ==
// k: string, v: int
// RepartitionByExpression [k#5 ASC NULLS FIRST], 42
// +- Project [_1#2 AS k#5, _2#3 AS v#6]
//    +- LocalRelation [_1#2, _2#3]
// 
// == Optimized Logical Plan ==
// RepartitionByExpression [k#5 ASC NULLS FIRST], 42
// +- LocalRelation [k#5, v#6]
// 
// == Physical Plan ==
// Exchange rangepartitioning(k#5 ASC NULLS FIRST, 42)
// +- LocalTableScan [k#5, v#6]

SPARK-22389 exposes external format partitioning in the Data Source API v2.

Spark >= 1.6.0

In Spark >= 1.6 it is possible to use partitioning by column for query and caching. See: SPARK-11410 and SPARK-4849 using repartition method:

val df = Seq(
  ("A", 1), ("B", 2), ("A", 3), ("C", 1)
).toDF("k", "v")

val partitioned = df.repartition($"k")
partitioned.explain

// scala> df.repartition($"k").explain(true)
// == Parsed Logical Plan ==
// 'RepartitionByExpression ['k], None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
//    +- LogicalRDD [_1#5,_2#6], MapPartitionsRDD[3] at rddToDataFrameHolder at <console>:27
// 
// == Analyzed Logical Plan ==
// k: string, v: int
// RepartitionByExpression [k#7], None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
//    +- LogicalRDD [_1#5,_2#6], MapPartitionsRDD[3] at rddToDataFrameHolder at <console>:27
// 
// == Optimized Logical Plan ==
// RepartitionByExpression [k#7], None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
//    +- LogicalRDD [_1#5,_2#6], MapPartitionsRDD[3] at rddToDataFrameHolder at <console>:27
// 
// == Physical Plan ==
// TungstenExchange hashpartitioning(k#7,200), None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
//    +- Scan PhysicalRDD[_1#5,_2#6]

Unlike RDDs Spark Dataset (including Dataset[Row] a.k.a DataFrame) cannot use custom partitioner as for now. You can typically address that by creating an artificial partitioning column but it won't give you the same flexibility.

Spark < 1.6.0:

One thing you can do is to pre-partition input data before you create a DataFrame

import org.apache.spark.sql.types._
import org.apache.spark.sql.Row
import org.apache.spark.HashPartitioner

val schema = StructType(Seq(
  StructField("x", StringType, false),
  StructField("y", LongType, false),
  StructField("z", DoubleType, false)
))

val rdd = sc.parallelize(Seq(
  Row("foo", 1L, 0.5), Row("bar", 0L, 0.0), Row("??", -1L, 2.0),
  Row("foo", -1L, 0.0), Row("??", 3L, 0.6), Row("bar", -3L, 0.99)
))

val partitioner = new HashPartitioner(5) 

val partitioned = rdd.map(r => (r.getString(0), r))
  .partitionBy(partitioner)
  .values

val df = sqlContext.createDataFrame(partitioned, schema)

Since DataFrame creation from an RDD requires only a simple map phase existing partition layout should be preserved*:

assert(df.rdd.partitions == partitioned.partitions)

The same way you can repartition existing DataFrame:

sqlContext.createDataFrame(
  df.rdd.map(r => (r.getInt(1), r)).partitionBy(partitioner).values,
  df.schema
)

So it looks like it is not impossible. The question remains if it make sense at all. I will argue that most of the time it doesn't:

  1. Repartitioning is an expensive process. In a typical scenario most of the data has to be serialized, shuffled and deserialized. From the other hand number of operations which can benefit from a pre-partitioned data is relatively small and is further limited if internal API is not designed to leverage this property.

    • joins in some scenarios, but it would require an internal support,
    • window functions calls with matching partitioner. Same as above, limited to a single window definition. It is already partitioned internally though, so pre-partitioning may be redundant,
    • simple aggregations with GROUP BY - it is possible to reduce memory footprint of the temporary buffers**, but overall cost is much higher. More or less equivalent to groupByKey.mapValues(_.reduce) (current behavior) vs reduceByKey (pre-partitioning). Unlikely to be useful in practice.
    • data compression with SqlContext.cacheTable. Since it looks like it is using run length encoding, applying OrderedRDDFunctions.repartitionAndSortWithinPartitions could improve compression ratio.
  2. Performance is highly dependent on a distribution of the keys. If it is skewed it will result in a suboptimal resource utilization. In the worst case scenario it will be impossible to finish the job at all.

  3. A whole point of using a high level declarative API is to isolate yourself from a low level implementation details. As already mentioned by @dwysakowicz and @RomiKuntsman an optimization is a job of the Catalyst Optimizer. It is a pretty sophisticated beast and I really doubt you can easily improve on that without diving much deeper into its internals.

Related concepts

Partitioning with JDBC sources:

JDBC data sources support predicates argument. It can be used as follows:

sqlContext.read.jdbc(url, table, Array("foo = 1", "foo = 3"), props)

It creates a single JDBC partition per predicate. Keep in mind that if sets created using individual predicates are not disjoint you'll see duplicates in the resulting table.

partitionBy method in DataFrameWriter:

Spark DataFrameWriter provides partitionBy method which can be used to "partition" data on write. It separates data on write using provided set of columns

val df = Seq(
  ("foo", 1.0), ("bar", 2.0), ("foo", 1.5), ("bar", 2.6)
).toDF("k", "v")

df.write.partitionBy("k").json("/tmp/foo.json")

This enables predicate push down on read for queries based on key:

val df1 = sqlContext.read.schema(df.schema).json("/tmp/foo.json")
df1.where($"k" === "bar")

but it is not equivalent to DataFrame.repartition. In particular aggregations like:

val cnts = df1.groupBy($"k").sum()

will still require TungstenExchange:

cnts.explain

// == Physical Plan ==
// TungstenAggregate(key=[k#90], functions=[(sum(v#91),mode=Final,isDistinct=false)], output=[k#90,sum(v)#93])
// +- TungstenExchange hashpartitioning(k#90,200), None
//    +- TungstenAggregate(key=[k#90], functions=[(sum(v#91),mode=Partial,isDistinct=false)], output=[k#90,sum#99])
//       +- Scan JSONRelation[k#90,v#91] InputPaths: file:/tmp/foo.json

bucketBy method in DataFrameWriter (Spark >= 2.0):

bucketBy has similar applications as partitionBy but it is available only for tables (saveAsTable). Bucketing information can used to optimize joins:

// Temporarily disable broadcast joins
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)

df.write.bucketBy(42, "k").saveAsTable("df1")
val df2 = Seq(("A", -1.0), ("B", 2.0)).toDF("k", "v2")
df2.write.bucketBy(42, "k").saveAsTable("df2")

// == Physical Plan ==
// *Project [k#41, v#42, v2#47]
// +- *SortMergeJoin [k#41], [k#46], Inner
//    :- *Sort [k#41 ASC NULLS FIRST], false, 0
//    :  +- *Project [k#41, v#42]
//    :     +- *Filter isnotnull(k#41)
//    :        +- *FileScan parquet default.df1[k#41,v#42] Batched: true, Format: Parquet, Location: InMemoryFileIndex[file:/spark-warehouse/df1], PartitionFilters: [], PushedFilters: [IsNotNull(k)], ReadSchema: struct<k:string,v:int>
//    +- *Sort [k#46 ASC NULLS FIRST], false, 0
//       +- *Project [k#46, v2#47]
//          +- *Filter isnotnull(k#46)
//             +- *FileScan parquet default.df2[k#46,v2#47] Batched: true, Format: Parquet, Location: InMemoryFileIndex[file:/spark-warehouse/df2], PartitionFilters: [], PushedFilters: [IsNotNull(k)], ReadSchema: struct<k:string,v2:double>

* By partition layout I mean only a data distribution. partitioned RDD has no longer a partitioner. ** Assuming no early projection. If aggregation covers only small subset of columns there is probably no gain whatsoever.

JavaScript hard refresh of current page

window.location.href = window.location.href

Java Constructor Inheritance

When you inherit from Super this is what in reality happens:

public class Son extends Super{

  // If you dont declare a constructor of any type, adefault one will appear.
  public Son(){
    // If you dont call any other constructor in the first line a call to super() will be placed instead.
    super();
  }

}

So, that is the reason, because you have to call your unique constructor, since"Super" doesn't have a default one.

Now, trying to guess why Java doesn't support constructor inheritance, probably because a constructor only makes sense if it's talking about concrete instances, and you shouldn't be able to create an instance of something when you don't know how it's defined (by polymorphism).

How to add image to canvas

You have to use .onload

let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d"); 

const drawImage = (url) => {
    const image = new Image();
    image.src = url;
    image.onload = () => {
       ctx.drawImage(image, 0, 0)
    }
}

Here's Why

If you are loading the image first after the canvas has already been created then the canvas won't be able to pass all the image data to draw the image. So you need to first load all the data that came with the image and then you can use drawImage()

Updating Python on Mac

If it were me, I would just leave it as it is. Use python3 and pip3 to run your files since python and python3 can coexist.

brew install python3 && cp /usr/local/bin/python3 /usr/local/bin/python

You can use the above line but it might have unintended consequences.

CRON command to run URL address every 5 minutes

Here is an example of the wget script in action:

wget -q -O /dev/null "http://example.com/cronjob.php" > /dev/null 2>&1

Using -O parameter like the above means that the output of the web request will be sent to STDOUT (standard output).

And the >/dev/null 2>&1 will instruct standard output to be redirected to a black hole. So no message from the executing program is returned to the screen.

What does MissingManifestResourceException mean and how to fix it?

I've encountered this issue with managed C++ project based on WinForms after renaming global namespace (not manually, but with Rename tool of VS2017).

The solution is simple, but isn't mentioned elsewhere.

You have to change RootNamespace entry in vcxproj-file to match the C++ namespace.

Django - how to create a file and save it to a model's FileField?

It's good practice to use a context manager or call close() in case of exceptions during the file saving process. Could happen if your storage backend is down, etc.

Any overwrite behavior should be configured in your storage backend. For example S3Boto3Storage has a setting AWS_S3_FILE_OVERWRITE. If you're using FileSystemStorage you can write a custom mixin.

You might also want to call the model's save method instead of the FileField's save method if you want any custom side-effects to happen, like last-updated timestamps. If that's the case, you can also set the name attribute of the file to the name of the file - which is relative to MEDIA_ROOT. It defaults to the full path of the file which can cause problems if you don't set it - see File.__init__() and File.name.

Here's an example where self is the model instance where my_file is the FileField / ImageFile, calling save() on the whole model instance instead of just FileField:

import os
from django.core.files import File

with open(filepath, 'rb') as fi:
    self.my_file = File(fi, name=os.path.basename(fi.name))
    self.save()

Managing SSH keys within Jenkins for Git

Have you tried logging in as the jenkins user?

Try this:

sudo -i -u jenkins #For RedHat you might have to do 'su' instead.
git clone [email protected]:your/repo.git

Often times you see failure if the host has not been added or authorized (hence I always manually login as hudson/jenkins for the first connection to github/bitbucket) but that link you included supposedly fixes that.

If the above doesn't work try recopying the key. Make sure its the pub key (ie id_rsa.pub). Maybe you missed some characters?

PostgreSQL: FOREIGN KEY/ON DELETE CASCADE

In my humble experience with postgres 9.6, cascade delete doesn't work in practice for tables that grow above a trivial size.

  • Even worse, while the delete cascade is going on, the tables involved are locked so those tables (and potentially your whole database) is unusable.
  • Still worse, it's hard to get postgres to tell you what it's doing during the delete cascade. If it's taking a long time, which table or tables is making it slow? Perhaps it's somewhere in the pg_stats information? It's hard to tell.

How to make a variable accessible outside a function?

Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.

You have to nest the requests:

$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   obj = name;   // sID is only now available!   sID = obj.id;   console.log(sID); }); 


Clean up your code!

  • Put the second request into a function
  • and let it accept sID as a parameter, so you don't have to declare it globally anymore! (Global variables are almost always evil!)
  • Remove sID and obj variables - name.id is sufficient unless you really need the other variables outside the function.


$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   // We don't need sID or obj here - name.id is sufficient   console.log(name.id);    doSecondRequest(name.id); });  /// TODO Choose a better name function doSecondRequest(sID) {   $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){         console.log(stats);   }); } 

Hapy New Year :)

"RangeError: Maximum call stack size exceeded" Why?

The answer with for is correct, but if you really want to use functional style avoiding for statement - you can use the following instead of your expression:

Array.from(Array(1000000), () => Math.random());

The Array.from() method creates a new Array instance from an array-like or iterable object. The second argument of this method is a map function to call on every element of the array.

Following the same idea you can rewrite it using ES2015 Spread operator:

[...Array(1000000)].map(() => Math.random())

In both examples you can get an index of the iteration if you need, for example:

[...Array(1000000)].map((_, i) => i + Math.random())

lvalue required as left operand of assignment

Change = to == i.e if (strcmp("hello", "hello") == 0)

You want to compare the result of strcmp() to 0. So you need ==. Assigning it to 0 won't work because rvalues cannot be assigned to.

Creating a config file in PHP

I normally end up creating a single conn.php file that has my database connections. Then i include that file in all files that require database queries.

How to determine device screen size category (small, normal, large, xlarge) using code?

Try this function isLayoutSizeAtLeast(int screenSize)

To check small screen, atleast 320x426 dp and above getResources().getConfiguration().isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_SMALL);

To check normal screen, atleast 320x470 dp and above getResources().getConfiguration().isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_NORMAL);

To check large screen, atleast 480x640 dp and above getResources().getConfiguration().isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_LARGE);

To check extra large screen, atleast 720x960 dp and above getResources().getConfiguration().isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_XLARGE);

When would you use the Builder Pattern?

I used builder in home-grown messaging library. The library core was receiving data from the wire, collecting it with Builder instance, then, once Builder decided it've got everything it needed to create a Message instance, Builder.GetMessage() was constructing a message instance using the data collected from the wire.

How to replace negative numbers in Pandas Data Frame by zero

If you are dealing with a large df (40m x 700 in my case) it works much faster and memory savvy through iteration on columns with something like.

for col in df.columns:
    df[col][df[col] < 0] = 0

How to bind bootstrap popover on dynamic elements

Update

If your popover is going to have a selector that is consistent then you can make use of selector property of popover constructor.

var popOverSettings = {
    placement: 'bottom',
    container: 'body',
    html: true,
    selector: '[rel="popover"]', //Sepcify the selector here
    content: function () {
        return $('#popover-content').html();
    }
}

$('body').popover(popOverSettings);

Demo

Other ways:

  1. (Standard Way) Bind the popover again to the new items being inserted. Save the popoversettings in an external variable.
  2. Use Mutation Event/Mutation Observer to identify if a particular element has been inserted on to the ul or an element.

Source

var popOverSettings = { //Save the setting for later use as well
    placement: 'bottom',
    container: 'body',
    html: true,
    //content:" <div style='color:red'>This is your div content</div>"
    content: function () {
        return $('#popover-content').html();
    }

}

$('ul').on('DOMNodeInserted', function () { //listed for new items inserted onto ul
    $(event.target).popover(popOverSettings);
});

$("button[rel=popover]").popover(popOverSettings);
$('.pop-Add').click(function () {
    $('ul').append("<li class='project-name'>     <a>project name 2        <button class='pop-function' rel='popover'></button>     </a>   </li>");
});

But it is not recommended to use DOMNodeInserted Mutation Event for performance issues as well as support. This has been deprecated as well. So your best bet would be to save the setting and bind after you update with new element.

Demo

Another recommended way is to use MutationObserver instead of MutationEvent according to MDN, but again support in some browsers are unknown and performance a concern.

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
// create an observer instance
var observer = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
        $(mutation.addedNodes).popover(popOverSettings);
    });
});

// configuration of the observer:
var config = {
     attributes: true, 
     childList: true, 
     characterData: true
};

// pass in the target node, as well as the observer options
observer.observe($('ul')[0], config);

Demo

word-wrap break-word does not work in this example

to get the smart break (break-word) work well on different browsers, what worked for me was the following set of rules:

#elm {
    word-break:break-word; /* webkit/blink browsers */
    word-wrap:break-word; /* ie */
}
-moz-document url-prefix() {/* catch ff */
    #elm {
        word-break: break-all; /* in ff-  with no break-word we'll settle for break-all */
    }
}

Where does gcc look for C and C++ header files?

The set of paths where the compiler looks for the header files can be checked by the command:-

cpp -v

If you declare #include "" , the compiler first searches in current directory of source file and if not found, continues to search in the above retrieved directories.

If you declare #include <> , the compiler searches directly in those directories obtained from the above command.

Source:- http://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art026

CSS Pseudo-classes with inline styles

No, this is not possible. In documents that make use of CSS, an inline style attribute can only contain property declarations; the same set of statements that appears in each ruleset in a stylesheet. From the Style Attributes spec:

The value of the style attribute must match the syntax of the contents of a CSS declaration block (excluding the delimiting braces), whose formal grammar is given below in the terms and conventions of the CSS core grammar:

declaration-list
  : S* declaration? [ ';' S* declaration? ]*
  ;

Neither selectors (including pseudo-elements), nor at-rules, nor any other CSS construct are allowed.

Think of inline styles as the styles applied to some anonymous super-specific ID selector: those styles only apply to that one very element with the style attribute. (They take precedence over an ID selector in a stylesheet too, if that element has that ID.) Technically it doesn't work like that; this is just to help you understand why the attribute doesn't support pseudo-class or pseudo-element styles (it has more to do with how pseudo-classes and pseudo-elements provide abstractions of the document tree that can't be expressed in the document language).

Note that inline styles participate in the same cascade as selectors in rule sets, and take highest precedence in the cascade (!important notwithstanding). So they take precedence even over pseudo-class states. Allowing pseudo-classes or any other selectors in inline styles would possibly introduce a new cascade level, and with it a new set of complications.

Note also that very old revisions of the Style Attributes spec did originally propose allowing this, however it was scrapped, presumably for the reason given above, or because implementing it was not a viable option.

Converting string to double in C#

There are 3 problems.

1) Incorrect decimal separator

Different cultures use different decimal separators (namely , and .).

If you replace . with , it should work as expected:

Console.WriteLine(Convert.ToDouble("52,8725945"));

You can parse your doubles using overloaded method which takes culture as a second parameter. In this case you can use InvariantCulture (What is the invariant culture) e.g. using double.Parse:

double.Parse("52.8725945", System.Globalization.CultureInfo.InvariantCulture);

You should also take a look at double.TryParse, you can use it with many options and it is especially useful to check wheter or not your string is a valid double.

2) You have an incorrect double

One of your values is incorrect, because it contains two dots:

15.5859949000000662452.23862099999999

3) Your array has an empty value at the end, which is an incorrect double

You can use overloaded Split which removes empty values:

string[] someArray = a.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);

VBA to copy a file from one directory to another

One thing that caused me a massive headache when using this code (might affect others and I wish that somebody had left a comment like this one here for me to read):

  • My aim is to create a dynamic access dashboard, which requires that its linked tables be updated.
  • I use the copy methods described above to replace the existing linked CSVs with an updated version of them.
  • Running the above code manually from a module worked fine.
  • Running identical code from a form linked to the CSV data had runtime error 70 (Permission denied), even tho the first step of my code was to close that form (which should have unlocked the CSV file so that it could be overwritten).
  • I now believe that despite the form being closed, it keeps the outdated CSV file locked while it executes VBA associated with that form.

My solution will be to run the code (On timer event) from another hidden form that opens with the database.

How do I merge a specific commit from one branch into another in Git?

SOURCE: https://git-scm.com/book/en/v2/Distributed-Git-Maintaining-a-Project#Integrating-Contributed-Work

The other way to move introduced work from one branch to another is to cherry-pick it. A cherry-pick in Git is like a rebase for a single commit. It takes the patch that was introduced in a commit and tries to reapply it on the branch you’re currently on. This is useful if you have a number of commits on a topic branch and you want to integrate only one of them, or if you only have one commit on a topic branch and you’d prefer to cherry-pick it rather than run rebase. For example, suppose you have a project that looks like this:

enter image description here

If you want to pull commit e43a6 into your master branch, you can run

$ git cherry-pick e43a6
Finished one cherry-pick.
[master]: created a0a41a9: "More friendly message when locking the index fails."
 3 files changed, 17 insertions(+), 3 deletions(-)

This pulls the same change introduced in e43a6, but you get a new commit SHA-1 value, because the date applied is different. Now your history looks like this:

enter image description here

Now you can remove your topic branch and drop the commits you didn’t want to pull in.

Utility of HTTP header "Content-Type: application/force-download" for mobile?

To download a file please use the following code ... Store the File name with location in $file variable. It supports all mime type

$file = "location of file to download"
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);

To know about Mime types please refer to this link: http://php.net/manual/en/function.mime-content-type.php

Regular Expressions and negating a whole character group

abc(?!def) will match abc not followed by def. So it'll match abce, abc, abck, etc. what if I want neither def nor xyz will it be abc(?!(def)(xyz)) ???

I had the same question and found a solution:

abc(?:(?!def))(?:(?!xyz))

These non-counting groups are combined by "AND", so it this should do the trick. Hope it helps.

Is Spring annotation @Controller same as @Service?

From Spring In Action

As you can see, this class is annotated with @Controller. On its own, @Controller doesn’t do much. Its primary purpose is to identify this class as a component for component scanning. Because HomeController is annotated with @Controller, Spring’s component scanning automatically discovers it and creates an instance of HomeController as a bean in the Spring application context.

In fact, a handful of other annotations (including @Component, @Service, and @Repository) serve a purpose similar to @Controller. You could have just as effectively annotated HomeController with any of those other annotations, and it would have still worked the same. The choice of @Controller is, however, more descriptive of this component’s role in the application.

java.util.zip.ZipException: error in opening zip file

It could be related to log4j.

Do you have log4j.jar file in the websphere java classpath (as defined in the startup file) as well as the application classpath ?

If you do make sure that the log4j.jar file is in the java classpath and that it is NOT in the web-inf/lib directory of your webapp.


It can also be related with the ant version (may be not your case, but I do put it here for reference):

You have a .class file in your class path (i.e. not a directory or a .jar file). Starting with ant 1.6, ant will open the files in the classpath checking for manifest entries. This attempted opening will fail with the error "java.util.zip.ZipException"

The problem does not exist with ant 1.5 as it does not try to open the files. - so make sure that your classpath's do not contain .class files.


On a side note, did you consider having separate jars ?
You could in the manifest of your main jar, refer to the other jars with this attribute:

Class-Path: one.jar two.jar three.jar

Then, place all of your jars in the same folder.
Again, may be not valid for your case, but still there for reference.

What is the best way to iterate over multiple lists at once?

You can use zip:

>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> for x, y in zip(a, b):
...   print x, y
... 
1 a
2 b
3 c

How to import and use image in a Vue single file component?

You can also use the root shortcut like so

  <template>
   <div class="container">
    <h1>Recipes</h1>
      <img src="@/assets/burger.jpg" />
   </div>
  </template>

Although this was Nuxt, it should be same with Vue CLI.

Only allow specific characters in textbox

Intercept the KeyPressed event is in my opinion a good solid solution. Pay attention to trigger code characters (e.KeyChar lower then 32) if you use a RegExp.

But in this way is still possible to inject characters out of range whenever the user paste text from the clipboard. Unfortunately I did not found correct clipboard events to fix this.

So a waterproof solution is to intercept TextBox.TextChanged. Here is sometimes the original out of range character visible, for a short time. I recommend to implement both.

using System.Text.RegularExpressions;

private void Form1_Shown(object sender, EventArgs e)
{
    filterTextBoxContent(textBox1);
}


string pattern = @"[^0-9^+^\-^/^*^(^)]";

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if(e.KeyChar >= 32 && Regex.Match(e.KeyChar.ToString(), pattern).Success) { e.Handled = true; }
}

private void textBox1_TextChanged(object sender, EventArgs e)
{
    filterTextBoxContent(textBox1);
}

private bool filterTextBoxContent(TextBox textBox)
{
    string text = textBox.Text;

    MatchCollection matches = Regex.Matches(text, pattern);
    bool matched = false;

    int selectionStart = textBox.SelectionStart;
    int selectionLength = textBox.SelectionLength;

    int leftShift = 0;
    foreach (Match match in matches)
    {
        if (match.Success && match.Captures.Count > 0)
        {
            matched = true;
            Capture capture = match.Captures[0];

            int captureLength = capture.Length;
            int captureStart = capture.Index - leftShift;
            int captureEnd = captureStart + captureLength;

            int selectionEnd = selectionStart + selectionLength;

            text = text.Substring(0, captureStart) + text.Substring(captureEnd, text.Length - captureEnd);

            textBox.Text = text;

            int boundSelectionStart = selectionStart < captureStart ? -1 : (selectionStart < captureEnd ? 0 : 1);
            int boundSelectionEnd = selectionEnd < captureStart ? -1 : (selectionEnd < captureEnd ? 0 : 1);

            if (boundSelectionStart == -1)
            {
                if (boundSelectionEnd == 0)
                {
                    selectionLength -= selectionEnd - captureStart;
                }
                else if (boundSelectionEnd == 1)
                {
                    selectionLength -= captureLength;
                }
            }
            else if (boundSelectionStart == 0)
            {
                if (boundSelectionEnd == 0)
                {
                    selectionStart = captureStart;
                    selectionLength = 0;
                }
                else if (boundSelectionEnd == 1)
                {
                    selectionStart = captureStart;
                    selectionLength -= captureEnd - selectionStart;
                }
            }
            else if (boundSelectionStart == 1)
            {
                selectionStart -= captureLength;
            }

            leftShift++;
        }
    }

    textBox.SelectionStart = selectionStart;
    textBox.SelectionLength = selectionLength;

    return matched;
}

Proper usage of .net MVC Html.CheckBoxFor

None of the above answers worked for me when binding back on POST, until I added the following in CSHTML

<div class="checkbox c-checkbox">
    <label>
        <input type="checkbox" id="xPrinting" name="xPrinting" value="true"  @Html.Raw( Model.xPrinting ? "checked" : "")>
        <span class=""></span>Printing
    </label>
</div>


// POST: Index

[HttpPost]
public ActionResult Index([Bind(Include = "dateInHands,dateFrom,dateTo,pgStatus,gpStatus,vwStatus,freeSearch,xPrinting,xEmbroidery,xPersonalization,sortOrder,radioOperator")] ProductionDashboardViewModel model)

How to replace � in a string

You are asking to replace the character "?" but for me that is coming through as three characters 'ï', '¿' and '½'. This might be your problem... If you are using Java prior to Java 1.5 then you only get the UCS-2 characters, that is only the first 65K UTF-8 characters. Based on other comments, it is most likely that the character that you are looking for is '?', that is the Unicode replacement character. This is the character that is "used to replace an incoming character whose value is unknown or unrepresentable in Unicode".

Actually, looking at the comment from Kathy, the other issue that you might be having is that javac is not interpreting your .java file as UTF-8, assuming that you are writing it in UTF-8. Try using:

javac -encoding UTF-8 xx.java

Or, modify your source code to do:

String.replaceAll("\uFFFD", "");

SameSite warning Chrome 77

Fixed by adding crossorigin to the script tag.

From: https://code.jquery.com/

<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>

The integrity and crossorigin attributes are used for Subresource Integrity (SRI) checking. This allows browsers to ensure that resources hosted on third-party servers have not been tampered with. Use of SRI is recommended as a best-practice, whenever libraries are loaded from a third-party source. Read more at srihash.org

Javascript window.open pass values using POST

For what it's worth, here's the previously provided code encapsulated within a function.

openWindowWithPost("http://www.example.com/index.php", {
    p: "view.map",
    coords: encodeURIComponent(coords)
});

Function definition:

function openWindowWithPost(url, data) {
    var form = document.createElement("form");
    form.target = "_blank";
    form.method = "POST";
    form.action = url;
    form.style.display = "none";

    for (var key in data) {
        var input = document.createElement("input");
        input.type = "hidden";
        input.name = key;
        input.value = data[key];
        form.appendChild(input);
    }

    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}

How to pass extra variables in URL with WordPress

One issue you might run into is is_home() returns true when a registered query_var is present in the home URL. For example, if http://example.com displays a static page instead of the blog, http://example.com/?c=123 will return the blog.

See https://core.trac.wordpress.org/ticket/25143 and https://wordpress.org/support/topic/adding-query-var-makes-front-page-missing/ for more info on this.

What you can do (if you're not attempting to affect the query) is use add_rewrite_endpoint(). It should be run during the init action as it affects the rewrite rules. Eg.

add_action( 'init', 'add_custom_setcookie_rewrite_endpoints' );

function add_custom_setcookie_rewrite_endpoints() {
    //add ?c=123 endpoint with
    //EP_ALL so endpoint is present across all places
    //no effect on the query vars
    add_rewrite_endpoint( 'c', EP_ALL, $query_vars = false );
}

This should give you access to $_GET['c'] when the url contains more information like www.example.com/news?c=123.

Remember to flush your rewrite rules after adding/modifying this.

Saving images in Python at a very high quality

If you are using Matplotlib and are trying to get good figures in a LaTeX document, save as an EPS. Specifically, try something like this after running the commands to plot the image:

plt.savefig('destination_path.eps', format='eps')

I have found that EPS files work best and the dpi parameter is what really makes them look good in a document.

To specify the orientation of the figure before saving, simply call the following before the plt.savefig call, but after creating the plot (assuming you have plotted using an axes with the name ax):

ax.view_init(elev=elevation_angle, azim=azimuthal_angle)

Where elevation_angle is a number (in degrees) specifying the polar angle (down from vertical z axis) and the azimuthal_angle specifies the azimuthal angle (around the z axis).

I find that it is easiest to determine these values by first plotting the image and then rotating it and watching the current values of the angles appear towards the bottom of the window just below the actual plot. Keep in mind that the x, y, z, positions appear by default, but they are replaced with the two angles when you start to click+drag+rotate the image.

iPhone Debugging: How to resolve 'failed to get the task for process'?

I received this error when I tried to launch app from Xcode as I figured I had selected distribution profile only. Build was successful so I created .ipa file. I used testflightapp.com to run the app. You can use iTunes as well.

Set proxy through windows command line including login parameters

cmd

Tunnel all your internet traffic through a socks proxy:

netsh winhttp set proxy proxy-server="socks=localhost:9090" bypass-list="localhost"

View the current proxy settings:

netsh winhttp show proxy

Clear all proxy settings:

netsh winhttp reset proxy

How to find my Subversion server version number?

Here's the simplest way to get the SVN server version. HTTP works even if your SVN repository requires HTTPS.

$ curl -X OPTIONS http://my-svn-domain/
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>...</head>
<body>...
<address>Apache/2.2.11 (Debian) DAV/2 SVN/1.5.6 PHP/5.2.9-4 ...</address>
</body>
</html>

How Connect to remote host from Aptana Studio 3

There's also an option to Auto Sync built-in in Aptana.

step 1

step 2

Android ImageView setImageResource in code

One easy way to map that country name that you have to an int to be used in the setImageResource method is:

int id = getResources().getIdentifier(lowerCountryCode, "drawable", getPackageName());
setImageResource(id);

But you should really try to use different folders resources for the countries that you want to support.

How to submit form on change of dropdown list?

Simple JavaScript will do -

<form action="myservlet.do" method="POST">
    <select name="myselect" id="myselect" onchange="this.form.submit()">
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
        <option value="4">Four</option>
    </select>
</form>

Here is a link for a good javascript tutorial.

Detect click event inside iframe

The tinymce API takes care of many events in the editors iframe. I strongly suggest to use them. Here is an example for the click handler

// Adds an observer to the onclick event using tinyMCE.init
tinyMCE.init({
   ...
   setup : function(ed) {
      ed.onClick.add(function(ed, e) {
           console.debug('Iframe clicked:' + e.target);
      });
   }
});

Amazon Linux: apt-get: command not found

If you're using Amazon Linux it's CentOS-based, which is RedHat-based. RH-based installs use yum not apt-get. Something like yum search httpd should show you the available Apache packages - you likely want yum install httpd24.

Note: Amazon Linux 2 has diverged from CentOS since the writing of this answer, but still uses yum.

Get file content from URL?

Use file_get_contents in combination with json_decode and echo.

How can I update npm on Windows?

Download and run the latest MSI. The MSI will update your installed node and npm.

Difference between Eclipse Europa, Helios, Galileo

In Galileo and Helios Provisioning Platform were introduced, and non-update-site plugins now should be placed in "dropins" subfolder ("eclipse/dropins/plugin_name/features", "eclipse/dropins/plugin_name/plugins") instead of Eclipse's folder ("eclipse/features" and "eclipse/plugins").

Also for programming needs the best Eclipse is the latest Eclipse. It has too many bugs for now, and all the Eclipse team is now doing is fixing the bugs. There are very few interface enhancements since Europa. IMHO.

start/play embedded (iframe) youtube-video on click of an image

Example youtube iframe

<iframe id="video" src="https://www.youtube.com/embed/xNM7jEHgzg4" frameborder="0"></iframe>

The click to play HTML element

<div class="videoplay">Play</div> 

jQuery code to play the Video

$('.videoplay').on('click', function() {
    $("#video")[0].src += "?autoplay=1";
});

Thanks to https://codepen.io/martinwolf/pen/dyLAC

How to resize a VirtualBox vmdk file

For shrinking image size I use the following steps:

  1. On the client machine cat /dev/zero > z;sync;sleep 3;sync;rm -f z
  2. Shut down client machine
  3. On the host VBoxManage clonehd "source.vmdk" "cloned.vdi" --format vdi
  4. On the host VBoxManage modifyhd cloned.vdi --compact
  5. On the host VBoxManage clonehd "cloned.vdi" "resized.vmdk" --format vmdk

How can I position my jQuery dialog to center?

Try this....

$(window).resize(function() {
    $("#dialog").dialog("option", "position", "center");
});

In C can a long printf statement be broken up into multiple lines?

The C compiler can glue adjacent string literals into one, like

printf("foo: %s "
       "bar: %d", foo, bar);

The preprocessor can use a backslash as a last character of the line, not counting CR (or CR/LF, if you are from Windowsland):

printf("foo %s \
bar: %d", foo, bar);

draw diagonal lines in div background with CSS

you can use a CSS3 transform Property:

div
{
transform:rotate(Xdeg);
-ms-transform:rotate(Xdeg); /* IE 9 */
-webkit-transform:rotate(Xdeg); /* Safari and Chrome */
}

Xdeg = your value

For example...

You can make more div and use a z-index property. So,make a div with line, and rotate it.

Android studio doesn't list my phone under "Choose Device"

In my case, android studio selectively doesnt recognize my device for projects with COMPILE AND TARGET SDKVERSION 29 under the app level build.gradle.

I fixed this either by downloading 'sources for android 29' which comes up after clicking the 'show package details' under the sdk manager tab or by reducing the compile and targetsdkversions to 28

Bash: If/Else statement in one line

&& means "and if successful"; by placing your if statement on the right-hand side of it, you ensure that it will only run if grep returns 0. To fix it, use ; instead:

ps aux | grep some_proces[s] > /tmp/test.txt ; if [ $? -eq 0 ]; then echo 1; else echo 0; fi

(or just use a line-break).

How to center horizontal table-cell

If you add text-align: center to the declarations for .columns-container then they align centrally:

.columns-container {
    display: table-cell;
    height: 100%;
    width:600px;
    text-align: center;
}

_x000D_
_x000D_
/*************************_x000D_
 * Sticky footer hack_x000D_
 * Source: http://pixelsvsbytes.com/blog/2011/09/sticky-css-footers-the-flexible-way/_x000D_
 ************************/_x000D_
_x000D_
/* Stretching all container's parents to full height */_x000D_
_x000D_
html,_x000D_
body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
/* Setting the container to be a table with maximum width and height */_x000D_
_x000D_
#container {_x000D_
  display: table;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}_x000D_
/* All sections (container's children) should be table rows with minimal height */_x000D_
_x000D_
.section {_x000D_
  display: table-row;_x000D_
  height: 1px;_x000D_
}_x000D_
/* The last-but-one section should be stretched to automatic height */_x000D_
_x000D_
.section.expand {_x000D_
  height: auto;_x000D_
}_x000D_
/*************************_x000D_
 * Full height columns_x000D_
 ************************/_x000D_
_x000D_
/* We need one extra container, setting it to full width */_x000D_
_x000D_
.columns-container {_x000D_
display: table-cell;_x000D_
height: 100%;_x000D_
width:600px;_x000D_
text-align: center;_x000D_
}_x000D_
/* Creating columns */_x000D_
_x000D_
.column {_x000D_
  /* The float:left won't work for Chrome for some reason, so inline-block */_x000D_
  display: inline-block;_x000D_
  /* for this to work, the .column elements should have NO SPACE BETWEEN THEM */_x000D_
  vertical-align: top;_x000D_
  height: 100%;_x000D_
  width: 100px;_x000D_
}_x000D_
/****************************************************************_x000D_
 * Just some coloring so that we're able to see height of columns_x000D_
 ****************************************************************/_x000D_
_x000D_
header {_x000D_
  background-color: yellow;_x000D_
}_x000D_
#a {_x000D_
  background-color: pink;_x000D_
}_x000D_
#b {_x000D_
  background-color: lightgreen;_x000D_
}_x000D_
#c {_x000D_
  background-color: lightblue;_x000D_
}_x000D_
footer {_x000D_
  background-color: purple;_x000D_
}
_x000D_
<div id="container">_x000D_
  <header class="section">_x000D_
    foo_x000D_
  </header>_x000D_
_x000D_
  <div class="section expand">_x000D_
    <div class="columns-container">_x000D_
      <div class="column" id="a">_x000D_
        <p>Contents A</p>_x000D_
      </div>_x000D_
      <div class="column" id="b">_x000D_
        <p>Contents B</p>_x000D_
      </div>_x000D_
      <div class="column" id="c">_x000D_
        <p>Contents C</p>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <footer class="section">_x000D_
    bar_x000D_
  </footer>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This does, though, require that you reset the .column elements to text-align: left (assuming you want them left-aligned, obviously (JS Fiddle demo).

Arrays.asList() of an array

This works from Java 5 to 7:

public int getTheNumber(Integer... factors) {
    ArrayList<Integer> f = new ArrayList<Integer>(Arrays.asList(factors));
    Collections.sort(f);
    return f.get(0)*f.get(f.size()-1);
}

In Java 4 there is no vararg... :-)

MySQL SELECT WHERE datetime matches day (and not necessarily time)

NEVER EVER use a selector like DATE(datecolumns) = '2012-12-24' - it is a performance killer:

  • it will calculate DATE() for all rows, including those, that don't match
  • it will make it impossible to use an index for the query

It is much faster to use

SELECT * FROM tablename 
WHERE columname BETWEEN '2012-12-25 00:00:00' AND '2012-12-25 23:59:59'

as this will allow index use without calculation.

EDIT

As pointed out by Used_By_Already, in the time since the inital answer in 2012, there have emerged versions of MySQL, where using '23:59:59' as a day end is no longer safe. An updated version should read

SELECT * FROM tablename 
WHERE columname >='2012-12-25 00:00:00'
AND columname <'2012-12-26 00:00:00'

The gist of the answer, i.e. the avoidance of a selector on a calculated expression, of course still stands.

The controller for path was not found or does not implement IController

If appropriate to your design, you can make sure the access modifier on your controller class is 'public', not something that could limit access like 'internal' or 'private'.

How do I debug a stand-alone VBScript script?

For posterity, here's Microsoft's article KB308364 on the subject. This no longer exists on their website, it is from an archive.

How to debug Windows Script Host, VBScript, and JScript files

SUMMARY

The purpose of this article is to explain how to debug Windows Script Host (WSH) scripts, which can be written in any ActiveX script language (as long as the proper language engine is installed), but which, by default, are written in VBScript and JScript. There are certain flags in the registry and, depending on the debugger used, certain required procedures to enable debugging.

MORE INFORMATION

To debug WSH scripts in Microsoft Visual InterDev, the Microsoft Script Debugger, or any other debugger, use the following command-line syntax to start the script:

wscript.exe //d <path to WSH file>
           This code informs the user when a runtime error has occurred and gives the user a choice to debug the application. Also, the //x flag

can be used, as follows, to throw an immediate exception, which starts the debugger immediately after the script starts running:

wscript.exe //d //x <path to WSH file>
           After a debug condition exists, the following registry key determines which debugger will be used:

HKEY_CLASSES_ROOT\CLSID\{834128A2-51F4-11D0-8F20-00805F2CD064}\LocalServer32

The script debugger should be Msscrdbg.exe, and the Visual InterDev debugger should be Mdm.exe.

If Visual InterDev is the default debugger, make sure that just-in-time (JIT) functionality is enabled. To do this, follow these steps:

  1. Start Visual InterDev.

  2. On the Tools menu, click Options.

  3. Click Debugger, and then ensure that the Just-In-Time options are selected for both the General and Script categories.

Additionally, if you are trying to debug a .wsf file, make sure that the following registry key is set to 1:

HKEY_CURRENT_USER\Software\Microsoft\Windows Script\Settings\JITDebug

PROPERTIES

Article ID: 308364 - Last Review: June 19, 2014 - Revision: 3.0

Keywords: kbdswmanage2003swept kbinfo KB308364

How to attach a process in gdb

Try one of these:

gdb -p 12271
gdb /path/to/exe 12271

gdb /path/to/exe
(gdb) attach 12271

Detect the Internet connection is offline?

I think it is a very simple way.

var x = confirm("Are you sure you want to submit?");
if (x) {
  if (navigator.onLine == true) {
    return true;
  }
  alert('Internet connection is lost');
  return false;
}
return false;

How to get the EXIF data from a file using C#

Check out this metadata extractor. It is written in Java but has also been ported to C#. I have used the Java version to write a small utility to rename my jpeg files based on the date and model tags. Very easy to use.


EDIT metadata-extractor supports .NET too. It's a very fast and simple library for accessing metadata from images and videos.

It fully supports Exif, as well as IPTC, XMP and many other types of metadata from file types including JPEG, PNG, GIF, PNG, ICO, WebP, PSD, ...

var directories = ImageMetadataReader.ReadMetadata(imagePath);

// print out all metadata
foreach (var directory in directories)
foreach (var tag in directory.Tags)
    Console.WriteLine($"{directory.Name} - {tag.Name} = {tag.Description}");

// access the date time
var subIfdDirectory = directories.OfType<ExifSubIfdDirectory>().FirstOrDefault();
var dateTime = subIfdDirectory?.GetDateTime(ExifDirectoryBase.TagDateTime);

It's available via NuGet and the code's on GitHub.

Parsing date string in Go

This is rather late to the party, and not really saying anything that hasn't been already said in one form or another, mostly through links above, but I wanted to give a TL;DR recap to those with less attention span:

The date and time of the go format string is very important. It's how Go knows which field is which. They are generally 1-9 left to right as follows:

  • January / Jan / january / jan / 01 / _1 (etc) are for month
  • 02 / _2 are for day of month
  • 15 / 03 / _3 / PM / P / pm /p are for hour & meridian (3pm)
  • 04 / _4 are for minutes
  • 05 / _5 are for seconds
  • 2006 / 06 are for year
  • -0700 / 07:00 / MST are for timezone
  • .999999999 / .000000000 etc are for partial seconds (I think the distinction is if trailing zeros are removed)
  • Mon / Monday are day of the week (which 01-02-2006 actually was),

So, Don't write "01-05-15" as your date format, unless you want "Month-Second-Hour"

(... again, this was basically a summary of above.)

How to fill the whole canvas with specific color?

If you want to do the background explicitly, you must be certain that you draw behind the current elements on the canvas.

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// Add behind elements.
ctx.globalCompositeOperation = 'destination-over'
// Now draw!
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);

sqlplus how to find details of the currently connected database session

We can get the details and status of session from below query as:

select ' Sid, Serial#, Aud sid : '|| s.sid||' , '||s.serial#||' , '||
       s.audsid||chr(10)|| '     DB User / OS User : '||s.username||
       '   /   '||s.osuser||chr(10)|| '    Machine - Terminal : '||
       s.machine||'  -  '|| s.terminal||chr(10)||
       '        OS Process Ids : '||
       s.process||' (Client)  '||p.spid||' (Server)'|| chr(10)||
       '   Client Program Name : '||s.program "Session Info"
  from v$process p,v$session s
 where p.addr = s.paddr
   and s.sid = nvl('&SID',s.sid)
   and nvl(s.terminal,' ') = nvl('&Terminal',nvl(s.terminal,' '))
   and s.process = nvl('&Process',s.process)
   and p.spid = nvl('&spid',p.spid)
   and s.username = nvl('&username',s.username)
   and nvl(s.osuser,' ') = nvl('&OSUser',nvl(s.osuser,' '))
   and nvl(s.machine,' ') = nvl('&machine',nvl(s.machine,' '))
   and nvl('&SID',nvl('&TERMINAL',nvl('&PROCESS',nvl('&SPID',nvl('&USERNAME',
       nvl('&OSUSER',nvl('&MACHINE','NO VALUES'))))))) <> 'NO VALUES'
/

For more details: https://ora-data.blogspot.in/2016/11/query-session-details.html

Thanks,

jquery how to use multiple ajax calls one after the end of the other

You could also use jquery when and then functions. for example

 $.when( $.ajax( "test.aspx" ) ).then(function( data, textStatus, jqXHR ) {
  //another ajax call
});

https://api.jquery.com/jQuery.when/

How to use (install) dblink in PostgreSQL?

I am using DBLINK to connect internal database for cross database queries.

Reference taken from this article.

Install DbLink extension.

CREATE EXTENSION dblink;

Verify DbLink:

SELECT pg_namespace.nspname, pg_proc.proname 
FROM pg_proc, pg_namespace 
WHERE pg_proc.pronamespace=pg_namespace.oid 
   AND pg_proc.proname LIKE '%dblink%';

Test connection of database:

SELECT dblink_connect('host=localhost user=postgres password=enjoy dbname=postgres');

What are database constraints?

Constraints are part of a database schema definition.

A constraint is usually associated with a table and is created with a CREATE CONSTRAINT or CREATE ASSERTION SQL statement.

They define certain properties that data in a database must comply with. They can apply to a column, a whole table, more than one table or an entire schema. A reliable database system ensures that constraints hold at all times (except possibly inside a transaction, for so called deferred constraints).

Common kinds of constraints are:

  • not null - each value in a column must not be NULL
  • unique - value(s) in specified column(s) must be unique for each row in a table
  • primary key - value(s) in specified column(s) must be unique for each row in a table and not be NULL; normally each table in a database should have a primary key - it is used to identify individual records
  • foreign key - value(s) in specified column(s) must reference an existing record in another table (via it's primary key or some other unique constraint)
  • check - an expression is specified, which must evaluate to true for constraint to be satisfied

What is PEP8's E128: continuation line under-indented for visual indent?

This goes also for statements like this (auto-formatted by PyCharm):

    return combine_sample_generators(sample_generators['train']), \
           combine_sample_generators(sample_generators['dev']), \
           combine_sample_generators(sample_generators['test'])

Which will give the same style-warning. In order to get rid of it I had to rewrite it to:

    return \
        combine_sample_generators(sample_generators['train']), \
        combine_sample_generators(sample_generators['dev']), \
        combine_sample_generators(sample_generators['test'])

Any reason not to use '+' to concatenate two strings?

''.join([a, b]) is better solution than +.

Because Code should be written in a way that does not disadvantage other implementations of Python (PyPy, Jython, IronPython, Cython, Psyco, and such)

form a += b or a = a + b is fragile even in CPython and isn't present at all in implementations that don't use refcounting (reference counting is a technique of storing the number of references, pointers, or handles to a resource such as an object, block of memory, disk space or other resource)

https://www.python.org/dev/peps/pep-0008/#programming-recommendations

Generate GUID in MySQL for existing Data?

Just a minor addition to make as I ended up with a weird result when trying to modify the UUIDs as they were generated. I found the answer by Rakesh to be the simplest that worked well, except in cases where you want to strip the dashes.

For reference:

UPDATE some_table SET some_field=(SELECT uuid());

This worked perfectly on its own. But when I tried this:

UPDATE some_table SET some_field=(REPLACE((SELECT uuid()), '-', ''));

Then all the resulting values were the same (not subtly different - I quadruple checked with a GROUP BY some_field query). Doesn't matter how I situated the parentheses, the same thing happens.

UPDATE some_table SET some_field=(REPLACE(SELECT uuid(), '-', ''));

It seems when surrounding the subquery to generate a UUID with REPLACE, it only runs the UUID query once, which probably makes perfect sense as an optimization to much smarter developers than I, but it didn't to me.

To resolve this, I just split it into two queries:

UPDATE some_table SET some_field=(SELECT uuid());
UPDATE some_table SET some_field=REPLACE(some_field, '-', '');

Simple solution, obviously, but hopefully this will save someone the time that I just lost.

Pretty printing JSON from Jackson 2.2's ObjectMapper

the IDENT_OUTPUT did not do anything for me, and to give a complete answer that works with my jackson 2.2.3 jars:

public static void main(String[] args) throws IOException {

byte[] jsonBytes = Files.readAllBytes(Paths.get("C:\\data\\testfiles\\single-line.json"));

ObjectMapper objectMapper = new ObjectMapper();

Object json = objectMapper.readValue( jsonBytes, Object.class );

System.out.println( objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString( json ) );
}

What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"?

//Use following to check if the id is a valid ObjectId?

var valid = mongoose.Types.ObjectId.isValid(req.params.id);
if(valid)
{
  //process your code here
} else {
  //the id is not a valid ObjectId
}

How to do case insensitive string comparison?

I like this quick shorthand variation -

export const equalsIgnoreCase = (str1, str2) => {
    return (!str1 && !str2) || (str1 && str2 && str1.toUpperCase() == str2.toUpperCase())
}

Quick in processing, and does what it is intended to.

'Field required a bean of type that could not be found.' error spring restful API using mongodb

My Mapper implementation classes in my target folder had been deleted, so my Mapper interfaces had no implementation classes anymore. Thus I got the same error Field *** required a bean of type ***Mapper that could not be found.

I simply had to regenerate my mappers implementations with maven, and refresh the project...

How can I clear the input text after clicking

    enter code here<form id="form">
<input type="text"><input type="text"><input type="text">

<input type="button" id="new">
</form>
<form id="form1">
<input type="text"><input type="text"><input type="text">

<input type="button" id="new1">
</form>
<script type="text/javascript">
$(document).ready(function(e) {
    $("#new").click( function(){
        //alert("fegf");
    $("#form input").val('');
    });

      $("#new1").click( function(){
        //alert("fegf");
    $("#form1 input").val('');
    });
});
</script>

SELECT INTO USING UNION QUERY

Here's one working syntax for SQL Server 2017:

USE [<yourdb-name>]
GO

SELECT * INTO NEWTABLE 
FROM <table1-name>
UNION ALL
SELECT * FROM <table2-name>

Take a char input from the Scanner

// Use a BufferedReader to read characters from the console.
import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException
{
char c;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}

How to check whether a string contains a substring in Ruby

user_input = gets.chomp
user_input.downcase!

if user_input.include?('substring')
  # Do something
end

This will help you check if the string contains substring or not

puts "Enter a string"
user_input = gets.chomp  # Ex: Tommy
user_input.downcase!    #  tommy


if user_input.include?('s')
    puts "Found"
else
    puts "Not found"
end

AngularJS - Trigger when radio button is selected

For dynamic values!

<div class="col-md-4" ng-repeat="(k, v) in tiposAcesso">
    <label class="control-label">
        <input type="radio" name="tipoAcesso" ng-model="userLogin.tipoAcesso" value="{{k}}" ng-change="changeTipoAcesso(k)" />              
        <span ng-bind="v"></span>
    </label>
</div>

in controller

$scope.changeTipoAcesso = function(value) {
    console.log(value);
};

CSS position:fixed inside a positioned element

You can use the position:fixed;, but without set left and top. Then you will push it to the right using margin-left, to position it in the right position you wish.

Check a demo here: http://jsbin.com/icili5