Programs & Examples On #Google toolbox for mac

Google Toolbox for Mac is a collection of utilities from different Google projects that may be of use to developers working on other Mac or iOS projects.

I lose my data when the container exits

There are following ways to persist container data:

  1. Docker volumes

  2. Docker commit

    a) create container from ubuntu image and run a bash terminal.

       $ docker run -i -t ubuntu:14.04 /bin/bash
    

    b) Inside the terminal install curl

       # apt-get update
       # apt-get install curl
    

    c) Exit the container terminal

       # exit
    

    d) Take a note of your container id by executing following command :

       $ docker ps -a
    

    e) save container as new image

       $ docker commit <container_id> new_image_name:tag_name(optional)
    

    f) verify that you can see your new image with curl installed.

       $ docker images           
    
       $ docker run -it new_image_name:tag_name bash
          # which curl
            /usr/bin/curl
    

Return from a promise then()

You cannot return value after resolving promise. Instead call another function when promise is resolved:

function justTesting() {
    promise.then(function(output) {
        // instead of return call another function
        afterResolve(output + 1);
    });
}

function afterResolve(result) {
    // do something with result
}

var test = justTesting();

How to lowercase a pandas dataframe string column if it has missing values?

May be using List comprehension

import pandas as pd
import numpy as np
df=pd.DataFrame(['ONE','Two', np.nan],columns=['Name']})
df['Name'] = [str(i).lower() for i in df['Name']] 

print(df)

Global javascript variable inside document.ready

You can define the variable inside the document ready function without var to make it a global variable. In javascript any variable declared without var automatically becomes a global variable

$(document).ready(function() {
    intro =  "something";
});

although you cant use the variable immediately, but it would be accessible to other functions

How to Specify Eclipse Proxy Authentication Credentials?

Window ? Preferences ? General ? Network Connections then under "Proxy ByPass" click "Add Host" and enter the link from which you will be getting your third-party plugin; that's it bingo, now it should get the plugin no problem.

How to use jQuery to show/hide divs based on radio button selection?

I wrote a simple code to unterstand you to how to make a show and hide radio buttons in jquery its very simple

<div id="myRadioGroup">

    Value Based<input type="radio" name="cars" checked="checked" value="2"  />

    Percent Based<input type="radio" name="cars" value="3" />
    <br>
    <div id="Cars2" class="desc" style="display: none;">
        <br>
        <label for="txtPassportNumber">Commission Value</label>
       <input type="text" id="txtPassportNumber" class="form-control" />
    </div>
    <div id="Cars3" class="desc" style="display: none;">
        <br>
        <label for="txtPassportNumber">Commission Percent</label>
       <input type="text" id="txtPassportNumber" class="form-control" />
    </div>
</div>
</div>

Jquery code

$(document).ready(function() {
    $("input[name$='cars']").click(function() {
        var test = $(this).val();

        $("div.desc").hide();
        $("#Cars" + test).show();
    });
});

give me comments

Android studio Gradle build speed up

I’m running a 5th gen i7 with Windows 10 and a 1TB Solid State. I compressed the Android Studio Projects folder and got about an 80% boost. Hope this helps.

I then combined it with the above solutions ie (org.gradle.parallel=true, org.gradle.daemon=true). The performance boost was quite impressive.

Additionally:

All of the above answers are totally correct but I must state as an experience Android developer (of 4 and a half years) that: No Android/Gradle developer should be working on a machine with a spinner drive, you need to fork out for a Solid State. We all hit that play button in the IDE 100s of times per day. When I went from a spinner to SSD (post Gradle), my speed and efficiency was literally 2 – 4 times faster and I promise you I’m NOT exaggerating here.

Now I’m not talking about having a machine with a small SSD and a big spinner, I’m talking about 1 big SSD. If you already have a machine with a small SSD and a big spinner you can upgrade the small spinner to say a 500GB SSD and set the SSD as your main OS drive with your developer tools installed on it.

So if you’re working in a fast paced environment please show this post to your boss. A decent 1TB SSD will set you back about £300 (including VAT), or about £160 for a 500GB SSD. Depending on if you are a junior or senior Android developer the drive will pay for itself (in wages expenses) in 1 – 2 working weeks, or about 2 and a half to 5 working days if you invest in a smaller; say 500GB SSD.

A lot of developers may argue that this is not the case, but it is the case for Gradle, as the Gradle system is very hard on the direct disk access. If you work with .NET/C#/VB Net or other development tools you won’t notice much difference but the difference in Gradle is HUGE. If you act on this post I promise you, you won’t be disappointed. Personally I’m using fifth gen i7 with 8GB RAM which originally came with a 1TB Spinner and I upgraded it to a Samsung SSD 840 EVO 1TB and I’ve never looked back since. I bought mine from: https://www.aria.co.uk.

Hope this helps. Also I must state that this is NOT a commercially motivated post, I’m just recommending Aria as I’ve used them many times before and they’ve always been reliable.

Linking to an external URL in Javadoc?

Hard to find a clear answer from the Oracle site. The following is from javax.ws.rs.core.HttpHeaders.java:

/**
 * See {@link <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1">HTTP/1.1 documentation</a>}.
 */
public static final String ACCEPT = "Accept";

/**
 * See {@link <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.2">HTTP/1.1 documentation</a>}.
 */
public static final String ACCEPT_CHARSET = "Accept-Charset";

Static Initialization Blocks

So you have a static field (it's also called "class variable" because it belongs to the class rather than to an instance of the class; in other words it's associated with the class rather than with any object) and you want to initialize it. So if you do NOT want to create an instance of this class and you want to manipulate this static field, you can do it in three ways:

1- Just initialize it when you declare the variable:

static int x = 3;

2- Have a static initializing block:

static int x;

static {
 x=3;
}

3- Have a class method (static method) that accesses the class variable and initializes it: this is the alternative to the above static block; you can write a private static method:

public static int x=initializeX();

private static int initializeX(){
 return 3;
}

Now why would you use static initializing block instead of static methods?

It's really up to what you need in your program. But you have to know that static initializing block is called once and the only advantage of the class method is that they can be reused later if you need to reinitialize the class variable.

let's say you have a complex array in your program. You initialize it (using for loop for example) and then the values in this array will change throughout the program but then at some point you want to reinitialize it (go back to the initial value). In this case you can call the private static method. In case you do not need in your program to reinitialize the values, you can just use the static block and no need for a static method since you're not gonna use it later in the program.

Note: the static blocks are called in the order they appear in the code.

Example 1:

class A{
 public static int a =f();

// this is a static method
 private static int f(){
  return 3;
 }

// this is a static block
 static {
  a=5;
 }

 public static void main(String args[]) {
// As I mentioned, you do not need to create an instance of the class to use the class variable
  System.out.print(A.a); // this will print 5
 }

}

Example 2:

class A{
 static {
  a=5;
 }
 public static int a =f();

 private static int f(){
  return 3;
 }

 public static void main(String args[]) {
  System.out.print(A.a); // this will print 3
 }

}

Drop multiple columns in pandas

Try this

df.drop(df.iloc[:, 1:69], inplace=True, axis=1)

This works for me

How to POST URL in data of a curl request

I don't think it's necessary to use semi-quotes around the variables, try:

curl -XPOST 'http://localhost/Service' -d "path=%2fxyz%2fpqr%2ftest%2f&fileName=1.doc"

%2f is the escape code for a /.

http://www.december.com/html/spec/esccodes.html

Also, do you need to specify a port? ( just checking :) )

jQuery select2 get value of select tag?

If you are using ajax, you may want to get updated value of select right after the selection.

//Part 1

$(".element").select2(/*Your code*/)    

//Part 2 - continued 

$(".element").on("select2:select", function (e) { 
  var select_val = $(e.currentTarget).val();
  console.log(select_val)
});

Credits: Steven-Johnston

How to add,set and get Header in request of HttpClient?

You can test-drive this code exactly as is using the public GitHub API (don't go over the request limit):

public class App {

    public static void main(String[] args) throws IOException {

        CloseableHttpClient client = HttpClients.custom().build();

        // (1) Use the new Builder API (from v4.3)
        HttpUriRequest request = RequestBuilder.get()
                .setUri("https://api.github.com")
                // (2) Use the included enum
                .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                // (3) Or your own
                .setHeader("Your own very special header", "value")
                .build();

        CloseableHttpResponse response = client.execute(request);

        // (4) How to read all headers with Java8
        List<Header> httpHeaders = Arrays.asList(response.getAllHeaders());
        httpHeaders.stream().forEach(System.out::println);

        // close client and response
    }
}

How to write hello world in assembler under Windows?

This example shows how to go directly to the Windows API and not link in the C Standard Library.

    global _main
    extern  _GetStdHandle@4
    extern  _WriteFile@20
    extern  _ExitProcess@4

    section .text
_main:
    ; DWORD  bytes;    
    mov     ebp, esp
    sub     esp, 4

    ; hStdOut = GetstdHandle( STD_OUTPUT_HANDLE)
    push    -11
    call    _GetStdHandle@4
    mov     ebx, eax    

    ; WriteFile( hstdOut, message, length(message), &bytes, 0);
    push    0
    lea     eax, [ebp-4]
    push    eax
    push    (message_end - message)
    push    message
    push    ebx
    call    _WriteFile@20

    ; ExitProcess(0)
    push    0
    call    _ExitProcess@4

    ; never here
    hlt
message:
    db      'Hello, World', 10
message_end:

To compile, you'll need NASM and LINK.EXE (from Visual studio Standard Edition)

   nasm -fwin32 hello.asm
   link /subsystem:console /nodefaultlib /entry:main hello.obj 

PHP/regex: How to get the string value of HTML tag?

<?php
function getTextBetweenTags($string, $tagname) {
    $pattern = "/<$tagname ?.*>(.*)<\/$tagname>/";
    preg_match($pattern, $string, $matches);
    return $matches[1];
}

$str = '<textformat leading="2"><p align="left"><font size="10">get me</font></p></textformat>';
$txt = getTextBetweenTags($str, "font");
echo $txt;
?>

That should do the trick

How should I escape strings in JSON?

Use EscapeUtils class in commons lang API.

EscapeUtils.escapeJavaScript("Your JSON string");

Groovy built-in REST/HTTP client?

Native Groovy GET and POST

// GET
def get = new URL("https://httpbin.org/get").openConnection();
def getRC = get.getResponseCode();
println(getRC);
if(getRC.equals(200)) {
    println(get.getInputStream().getText());
}

// POST
def post = new URL("https://httpbin.org/post").openConnection();
def message = '{"message":"this is a message"}'
post.setRequestMethod("POST")
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/json")
post.getOutputStream().write(message.getBytes("UTF-8"));
def postRC = post.getResponseCode();
println(postRC);
if(postRC.equals(200)) {
    println(post.getInputStream().getText());
}

How to get a matplotlib Axes instance to plot to?

Use the gca ("get current axes") helper function:

ax = plt.gca()

Example:

import matplotlib.pyplot as plt
import matplotlib.finance
quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)]
ax = plt.gca()
h = matplotlib.finance.candlestick(ax, quotes)
plt.show()

enter image description here

Format bytes to kilobytes, megabytes, gigabytes

I don't know why you should make it so complicated as the others.

The following code is much simpler to understand and about 25% faster than the other solutions who uses the log function (called the function 20 Mio. times with different parameters)

function formatBytes($bytes, $precision = 2) {
    $units = ['Byte', 'Kilobyte', 'Megabyte', 'Gigabyte', 'Terabyte'];
    $i = 0;

    while($bytes > 1024) {
        $bytes /= 1024;
        $i++;
    }
    return round($bytes, $precision) . ' ' . $units[$i];
}

'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data)

You have to use now the new XLSX-Driver from Access-Redist (32/64-Bit). The current XLS-Driver are corrupted since last cumulative update.

Customize Bootstrap checkboxes

As others have said, the style you're after is actually just the Mac OS checkbox style, so it will look radically different on other devices.

In fact both screenshots you linked show what checkboxes look like on Mac OS in Chrome, the grey one is shown at non-100% zoom levels.

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

Try to add

GRANT USAGE ON SCHEMA public to readonly;

You probably were not aware that one needs to have the requisite permissions to a schema, in order to use objects in the schema.

How to access ssis package variables inside script component

This should work:

IDTSVariables100 vars = null;
VariableDispenser.LockForRead("System::TaskName");
VariableDispenser.GetVariables(vars);
string TaskName = vars("System::TaskName").Value.ToString();
vars.Unlock();

Your initial code lacks call of the GetVariables() method.

Characters allowed in a URL

The full list of the 66 unreserved characters is in RFC3986, here: http://tools.ietf.org/html/rfc3986#section-2.3

This is any character in the following regex set:

[A-Za-z0-9_.\-~]

Convert a String to Modified Camel Case in Java or Title Case as is otherwise called

Refer:

    static String toCamelCase(String s){
           String[] parts = s.split(" ");
           String camelCaseString = "";
           for (String part : parts){
               if(part!=null && part.trim().length()>0)
              camelCaseString = camelCaseString + toProperCase(part);
               else
                   camelCaseString=camelCaseString+part+" ";   
           }
           return camelCaseString;
        }

        static String toProperCase(String s) {
            String temp=s.trim();
            String spaces="";
            if(temp.length()!=s.length())
            {
            int startCharIndex=s.charAt(temp.indexOf(0));
            spaces=s.substring(0,startCharIndex);
            }
            temp=temp.substring(0, 1).toUpperCase() +
            spaces+temp.substring(1).toLowerCase()+" ";
            return temp;

        }
  public static void main(String[] args) {
     String string="HI tHiS is   SomE Statement";
     System.out.println(toCamelCase(string));
  }

Commenting multiple lines in DOS batch file

Just want to mention that pdub's GOTO solution is not fully correct in case :comment label appear in multiple times. I modify the code from this question as the example.

@ECHO OFF
SET FLAG=1
IF [%FLAG%]==[1] (
    ECHO IN THE FIRST IF...
    GOTO comment
    ECHO "COMMENT PART 1"
:comment
    ECHO HERE AT TD_NEXT IN THE FIRST BLOCK
)

IF [%FLAG%]==[1] (
    ECHO IN THE SECOND IF...
    GOTO comment
    ECHO "COMMENT PART"
:comment
    ECHO HERE AT TD_NEXT IN THE SECOND BLOCK
)

The output will be

IN THE FIRST IF...
HERE AT TD_NEXT IN THE SECOND BLOCK

The command ECHO HERE AT TD_NEXT IN THE FIRST BLOCK is skipped.

How to check if input is numeric in C++

Why not just using scanf("%i") and check its return?

Node.js: How to send headers with form data using request module?

This should work.

var url = 'http://<your_url_here>';
var headers = { 
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0',
    'Content-Type' : 'application/x-www-form-urlencoded' 
};
var form = { username: 'user', password: '', opaque: 'someValue', logintype: '1'};

request.post({ url: url, form: form, headers: headers }, function (e, r, body) {
    // your callback body
});

Gradle Sync failed could not find constraint-layout:1.0.0-alpha2

Just as a heads up to those still searching for this.

ConstraintLayout 1.0.1 and lower have been deprecated by maven.

For a list of available constraint layouts that can be downloaded, see below:

https://maven.google.com/web/index.html?q=Constrain#com.android.support.constraint:constraint-layout

The easiest solution at the moment, is to change

implementation 'com.android.support.constraint:constraint-layout:1.0.0-beta1'

to

implementation 'com.android.support.constraint:constraint-layout:1.0.2'

Limiting double to 3 decimal places

Good answers above- if you're looking for something reusable here is the code. Note that you might want to check the decimal places value, and this may overflow.

public static decimal TruncateToDecimalPlace(this decimal numberToTruncate, int decimalPlaces)
{
    decimal power = (decimal)(Math.Pow(10.0, (double)decimalPlaces));

    return Math.Truncate((power * numberToTruncate)) / power;
}

Remove insignificant trailing zeros from a number?

If you use toFixed(n) where n > 0, a more simple and stable (no more float operations) solution can be:

(+n).toFixed(2).replace(/(\.0+|0+)$/, '')


// 0 => 0
// 0.1234 => 0.12
// 0.1001 => 0.1

// 1 => 1
// 1.1234 => 1.12
// 1.1001 => 1.1

// 100 => 100
// 100.1234 => 100.12
// 100.1001 => 100.1

PS: if you use toFixed(0), then no replace is needed.

How to send email to multiple recipients using python smtplib?

It works for me.

import smtplib
from email.mime.text import MIMEText

s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = '[email protected]'
recipients = '[email protected],[email protected]'
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = recipients
s.sendmail(sender, recipients.split(','), msg.as_string())

Convert List<DerivedClass> to List<BaseClass>

You can also use the System.Runtime.CompilerServices.Unsafe NuGet package to create a reference to the same List:

using System.Runtime.CompilerServices;
...
class Tool { }
class Hammer : Tool { }
...
var hammers = new List<Hammer>();
...
var tools = Unsafe.As<List<Tool>>(hammers);

Given the sample above, you can access the existing Hammer instances in the list using the tools variable. Adding Tool instances to the list throws an ArrayTypeMismatchException exception because tools references the same variable as hammers.

In Python, how do I determine if an object is iterable?

I found a nice solution here:

isiterable = lambda obj: isinstance(obj, basestring) \
    or getattr(obj, '__iter__', False)

How should I edit an Entity Framework connection string?

Follow the next steps:

  1. Open the app.config and comment on the connection string (save file)
  2. Open the edmx (go to properties, the connection string should be blank), close the edmx file again
  3. Open the app.config and uncomment the connection string (save file)
  4. Open the edmx, go to properties, you should see the connection string uptated!!

How to make an "alias" for a long path?

but an actual alias for a dir is also possible, try

 myScripts="~/Files/Scripts/Main"
 alias myScripts="cd $myScripts"

This way you have a common naming convention (for each dir/alias pair), and if you need to copy something from the current dir to myScripts, you don't have to think about it.

IHTH

How do you get the path to the Laravel Storage folder?

use this artisan command for create shortcut in public folder

php artisan storage:link

Than you will able to access posted img or file

Vue - Deep watching an array of objects and calculating the change?

This is what I use to deep watch an object. My requirement was watching the child fields of the object.

new Vue({
    el: "#myElement",
    data:{
        entity: {
            properties: []
        }
    },
    watch:{
        'entity.properties': {
            handler: function (after, before) {
                // Changes detected.    
            },
            deep: true
        }
    }
});

How to stop C# console applications from closing automatically?

Try Ctrl + F5 in Visual Studio to run your program, this will add a pause with "Press any key to continue..." automatically without any Console.Readline() or ReadKey() functions.

How can I debug a HTTP POST in Chrome?

Another option that may be useful is a dedicated HTTP debugging tool. There's a few available, I'd suggest HTTP Toolkit: an open-source project I've been working on (yeah, I might be biased) to solve this same problem for myself.

The main difference is usability & power. The Chrome dev tools are good for simple things, and I'd recommend starting there, but if you're struggling to understand the information there, and you need either more explanation or more power then proper focused tools can be useful!

For this case, it'll show you the full POST body you're looking for, with a friendly editor and highlighting (all powered by VS Code) so you can dig around. It'll give you the request & response headers of course, but with extra info like docs from MDN (the Mozilla Developer Network) for every standard header and status code you can see.

A picture is worth a thousand StackOverflow answers:

A screenshot of HTTP Toolkit showing a POST request and its body

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

Use dynamic_cast for converting pointers/references within an inheritance hierarchy.

Use static_cast for ordinary type conversions.

Use reinterpret_cast for low-level reinterpreting of bit patterns. Use with extreme caution.

Use const_cast for casting away const/volatile. Avoid this unless you are stuck using a const-incorrect API.

Active Directory LDAP Query by sAMAccountName and Domain

I have written a C# class incorporating

  • the algorithm from Dscoduc,
  • the query optimization from sorin,
  • a cache for the domain to server mapping, and
  • a method to search for an account name in DOMAIN\sAMAccountName format.

However, it is not Site-aware.

using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using System.Text;

public static class ADUserFinder
{
    private static Dictionary<string, string> _dictDomain2LDAPPath;

    private static Dictionary<string, string> DictDomain2LDAPPath
    {
        get
        {
            if (null == _dictDomain2LDAPPath)
            {
                string configContainer;
                using (DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE"))
                    configContainer = rootDSE.Properties["ConfigurationNamingContext"].Value.ToString();

                using (DirectoryEntry partitionsContainer = new DirectoryEntry("LDAP://CN=Partitions," + configContainer))
                using (DirectorySearcher dsPartitions = new DirectorySearcher(
                        partitionsContainer,
                        "(&(objectcategory=crossRef)(systemFlags=3))",
                        new string[] { "name", "nCName", "dnsRoot" },
                        SearchScope.OneLevel
                    ))
                using (SearchResultCollection srcPartitions = dsPartitions.FindAll())
                {
                    _dictDomain2LDAPPath = srcPartitions.OfType<SearchResult>()
                        .ToDictionary(
                        result => result.Properties["name"][0].ToString(), // the DOMAIN part
                        result => $"LDAP://{result.Properties["dnsRoot"][0]}/{result.Properties["nCName"][0]}"
                    );
                }
            }

            return _dictDomain2LDAPPath;
        }
    }

    private static DirectoryEntry FindRootEntry(string domainPart)
    {
        if (DictDomain2LDAPPath.ContainsKey(domainPart))
            return new DirectoryEntry(DictDomain2LDAPPath[domainPart]);
        else
            throw new ArgumentException($"Domain \"{domainPart}\" is unknown in Active Directory");
    }

    public static DirectoryEntry FindUser(string domain, string sAMAccountName)
    {
        using (DirectoryEntry rootEntryForDomain = FindRootEntry(domain))
        using (DirectorySearcher dsUser = new DirectorySearcher(
                rootEntryForDomain,
                $"(&(sAMAccountType=805306368)(sAMAccountName={EscapeLdapSearchFilter(sAMAccountName)}))" // magic number 805306368 means "user objects", it's more efficient than (objectClass=user)
            ))
            return dsUser.FindOne().GetDirectoryEntry();
    }

    public static DirectoryEntry FindUser(string domainBackslashSAMAccountName)
    {
        string[] domainAndsAMAccountName = domainBackslashSAMAccountName.Split('\\');
        if (domainAndsAMAccountName.Length != 2)
            throw new ArgumentException($"User name \"{domainBackslashSAMAccountName}\" is not in correct format DOMAIN\\SAMACCOUNTNAME", "DomainBackslashSAMAccountName");

        string domain = domainAndsAMAccountName[0];
        string sAMAccountName = domainAndsAMAccountName[1];

        return FindUser(domain, sAMAccountName);
    }

    /// <summary>
    /// Escapes the LDAP search filter to prevent LDAP injection attacks.
    /// Copied from https://stackoverflow.com/questions/649149/how-to-escape-a-string-in-c-for-use-in-an-ldap-query
    /// </summary>
    /// <param name="searchFilter">The search filter.</param>
    /// <see cref="https://blogs.oracle.com/shankar/entry/what_is_ldap_injection" />
    /// <see cref="http://msdn.microsoft.com/en-us/library/aa746475.aspx" />
    /// <returns>The escaped search filter.</returns>
    private static string EscapeLdapSearchFilter(string searchFilter)
    {
        StringBuilder escape = new StringBuilder();
        for (int i = 0; i < searchFilter.Length; ++i)
        {
            char current = searchFilter[i];
            switch (current)
            {
                case '\\':
                    escape.Append(@"\5c");
                    break;
                case '*':
                    escape.Append(@"\2a");
                    break;
                case '(':
                    escape.Append(@"\28");
                    break;
                case ')':
                    escape.Append(@"\29");
                    break;
                case '\u0000':
                    escape.Append(@"\00");
                    break;
                case '/':
                    escape.Append(@"\2f");
                    break;
                default:
                    escape.Append(current);
                    break;
            }
        }

        return escape.ToString();
    }
}

How can I decrease the size of Ratingbar?

 <RatingBar     android:id="@+id/id_tv_rating_bar"
                style="@style/Widget.AppCompat.RatingBar.Small"
                android:layout_width="wrap_content"
                android:layout_height="@dimen/_20sdp"
                android:layout_marginLeft="@dimen/_80sdp"
                android:numStars="5"
                android:paddingTop="@dimen/_5sdp"
                android:rating="5" />

Just use style="@style/Widget.AppCompat.RatingBar.Small" it'll work for Sure!

Mapping many-to-many association table with extra column(s)

As said before, with JPA, in order to have the chance to have extra columns, you need to use two OneToMany associations, instead of a single ManyToMany relationship. You can also add a column with autogenerated values; this way, it can work as the primary key of the table, if useful.

For instance, the implementation code of the extra class should look like that:

@Entity
@Table(name = "USER_SERVICES")
public class UserService{

    // example of auto-generated ID
    @Id
    @Column(name = "USER_SERVICES_ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long userServiceID;



    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "USER_ID")
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "SERVICE_ID")
    private Service service;



    // example of extra column
    @Column(name="VISIBILITY")    
    private boolean visibility;



    public long getUserServiceID() {
        return userServiceID;
    }


    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Service getService() {
        return service;
    }

    public void setService(Service service) {
        this.service = service;
    }

    public boolean getVisibility() {
        return visibility;
    }

    public void setVisibility(boolean visibility) {
        this.visibility = visibility;
    }

}

How to programmatically get iOS status bar height

Using following single line code you can get status bar height in any orientation and also if it is visible or not

#define STATUS_BAR_HIGHT (
    [UIApplicationsharedApplication].statusBarHidden ? 0 : (
        [UIApplicationsharedApplication].statusBarFrame.size.height > 100 ?
            [UIApplicationsharedApplication].statusBarFrame.size.width :
            [UIApplicationsharedApplication].statusBarFrame.size.height
    )
)

It just a simple but very useful macro just try this you don't need to write any extra code

How to echo print statements while executing a sql script

Just to make your script more readable, maybe use this proc:

DELIMITER ;;

DROP PROCEDURE IF EXISTS printf;
CREATE PROCEDURE printf(thetext TEXT)
BEGIN

  select thetext as ``;

 END;

;;

DELIMITER ;

Now you can just do:

call printf('Counting products that have missing short description');

Access denied for user 'root'@'localhost' (using password: YES) (Mysql::Error)

I solved this problem by deleting the empty users creating by MySQL. I only have root user and my own user. I deleted the rest.

Set type for function parameters?

No, instead you would need to do something like this depending on your needs:

function myFunction(myDate, myString) {
  if(arguments.length > 1 && typeof(Date.parse(myDate)) == "number" && typeof(myString) == "string") {
    //Code here
  }
}

SQLite add Primary Key

I tried to add the primary key afterwards by changing the sqlite_master table directly. This trick seems to work. It is a hack solution of course.

In short: create a regular (unique) index on the table, then make the schema writable and change the name of the index to the form reserved by sqlite to identify a primary key index, (i.e. sqlite_autoindex_XXX_1, where XXX is the table name) and set the sql string to NULL. At last change the table definition itself. One pittfal: sqlite does not see the index name change until the database is reopened. This seems like a bug, but not a severe one (even without reopening the database, you can still use it).

Suppose the table looks like:

CREATE TABLE tab1(i INTEGER, j INTEGER, t TEXT);

Then I did the following:

BEGIN;
CREATE INDEX pk_tab1 ON tab1(i,j);
pragma writable_schema=1;
UPDATE sqlite_master SET name='sqlite_autoindex_tab1_1',sql=null WHERE name='pk_tab1';
UPDATE sqlite_master SET sql='CREATE TABLE tab1(i integer,j integer,t text,primary key(i,j))' WHERE name='tab1';
COMMIT;

Some tests (in sqlite shell):

sqlite> explain query plan select * from tab1 order by i,j;
0|0|0|SCAN TABLE tab1 USING INDEX sqlite_autoindex_tab1_1
sqlite> drop index sqlite_autoindex_tab1_1;
Error: index associated with UNIQUE or PRIMARY KEY constraint cannot be dropped    

How to set editable true/false EditText in Android programmatically?

Fetch the KeyListener value of EditText by editText.getKeyListener() and store in the KeyListener type variable, which will contain the Editable property value:

KeyListener variable;
variable = editText.getKeyListener(); 

Set the Editable property of EditText to false as:

 edittext.setKeyListener(null);

Now set Editable property of EditText to true as:

editText.setKeyListener(variable);  

Note: In XML the default Editable property of EditText should be true.

How to use find command to find all files with extensions from list?

find /path/to -regex ".*\.\(jpg\|gif\|png\|jpeg\)" > log

Could not find the main class, program will exit

You can place .; in classpath in environmental variables to overcome this problem.

InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately

The docs give a fair indicator of what's required., however requests allow us to skip a few steps:

You only need to install the security package extras (thanks @admdrew for pointing it out)

$ pip install requests[security]

or, install them directly:

$ pip install pyopenssl ndg-httpsclient pyasn1

Requests will then automatically inject pyopenssl into urllib3


If you're on ubuntu, you may run into trouble installing pyopenssl, you'll need these dependencies:

$ apt-get install libffi-dev libssl-dev

How to create a multiline UITextfield?

use UITextView instead of UITextField

using mailto to send email with an attachment

this is not possible in "mailto" function.

please go with server side coding(C#).make sure open vs in administrative permission.

Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

oMsg.Subject = "emailSubject";
oMsg.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
oMsg.BCC = "emailBcc";
oMsg.To = "emailRecipient";

string body = "emailMessage";

oMsg.HTMLBody = "body";              
oMsg.Attachments.Add(Convert.ToString(@"/my_location_virtual_path/myfile.txt"), Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);

oMsg.Display(false); //In order to displ

Change the content of a div based on selection from dropdown menu

There are many ways to perform your task, but the most elegant are, I believe, using css. Here are basic steps

  1. Listening option selection event, biding adding/removing some class to container action, which contains all divs you are interested in (for example, body)
  2. Adding styles for hiding all divs except one.
  3. Well done, sir.

This works pretty well if there a few divs, since more elements you want to toggle, more css rules should be written. Here is more general solution, binding action, base on following steps: 1. find all elements using some selector (usually it looks like '.menu-container .menu-item') 2. find one of found elements, which is current visible, hide it 3. make visible another element, the one you desire to be visible under new circumstances.

javascript it a rather timtoady language )

GitHub "fatal: remote origin already exists"

In case you want to do via GUI do the following:

  1. Ensure "hidden files" are visible in your project folder
  2. Go to .git directory
  3. Edit the url file in the config.txt file and save the file!

Can regular expressions be used to match nested patterns?

as zsolt mentioned, some regex engines support recursion -- of course, these are typically the ones that use a backtracking algorithm so it won't be particularly efficient. example: /(?>[^{}]*){(?>[^{}]*)(?R)*(?>[^{}]*)}/sm

git pull error "The requested URL returned error: 503 while accessing"

Had the same error while using SourceTree connected to BitBucket repository.

When navigating to repository url on bitbucket.org the warning message appeared:

This repository is in read-only mode. You caught us doing some quick maintenance.

After around 2 hours repository was accessible again.

You can check status and uptime of bitbucket here: http://status.bitbucket.org/

AngularJS access parent scope from child controller

From a child component you can access the properties and methods of the parent component with 'require'. Here is an example:

Parent:

.component('myParent', mymodule.MyParentComponent)
...
controllerAs: 'vm',
...
var vm = this;
vm.parentProperty = 'hello from parent';

Child:

require: {
    myParentCtrl: '^myParent'
},
controllerAs: 'vm',
...
var vm = this;
vm.myParentCtrl.parentProperty = 'hello from child';

What's a simple way to get a text input popup dialog box on an iPhone

I would use a UIAlertView with a UITextField subview. You can either add the text field manually or, in iOS 5, use one of the new methods.

List columns with indexes in PostgreSQL

RESULT OF QUERY:

table |     column     |          type          | notnull |  index_name  | is_index | primarykey | uniquekey | default
-------+----------------+------------------------+---------+--------------+----------+-   -----------+-----------+---------
 nodes | dns_datacenter | character varying(255) | f       |              | f        | f          | f         |
 nodes | dns_name       | character varying(255) | f       | dns_name_idx | t        | f          | f         |
 nodes | id             | uuid                   | t       | nodes_pkey   | t        | t          | t         |
(3 rows)

QUERY:

SELECT  
c.relname AS table,
f.attname AS column,  
pg_catalog.format_type(f.atttypid,f.atttypmod) AS type,
f.attnotnull AS notnull,  
i.relname as index_name,
CASE  
    WHEN i.oid<>0 THEN 't'  
    ELSE 'f'  
END AS is_index,  
CASE  
    WHEN p.contype = 'p' THEN 't'  
    ELSE 'f'  
END AS primarykey,  
CASE  
    WHEN p.contype = 'u' THEN 't' 
    WHEN p.contype = 'p' THEN 't' 
    ELSE 'f'
END AS uniquekey,
CASE
    WHEN f.atthasdef = 't' THEN d.adsrc
END AS default  FROM pg_attribute f  
JOIN pg_class c ON c.oid = f.attrelid  
JOIN pg_type t ON t.oid = f.atttypid  
LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum  
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace  
LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey)  
LEFT JOIN pg_class AS g ON p.confrelid = g.oid
LEFT JOIN pg_index AS ix ON f.attnum = ANY(ix.indkey) and c.oid = f.attrelid and c.oid = ix.indrelid 
LEFT JOIN pg_class AS i ON ix.indexrelid = i.oid 

WHERE c.relkind = 'r'::char  
AND n.nspname = 'public'  -- Replace with Schema name 
--AND c.relname = 'nodes'  -- Replace with table name, or Comment this for get all tables
AND f.attnum > 0
ORDER BY c.relname,f.attname;

How do I cancel a build that is in progress in Visual Studio?

Ctrl + End works for me on Visual C++ 2010 Express.

What causes this error? "Runtime error 380: Invalid property value"

2017 I know... but someone is facing this problem during their code maintenance.

This error happened when I tried:

maskedbox.Mask = "#.###"
maskedbox.Text = "12345678"

To fix that, just set PromptInclude property to "false".

How can I insert multiple rows into oracle with a sequence value?

insert into TABLE_NAME
(COL1,COL2)
WITH
data AS
(
    select 'some value'    x from dual
    union all
    select 'another value' x from dual
)
SELECT my_seq.NEXTVAL, x 
FROM data
;

I think that is what you want, but i don't have access to oracle to test it right now.

How to perform case-insensitive sorting in JavaScript?

arr.sort(function(a,b) {
    a = a.toLowerCase();
    b = b.toLowerCase();
    if (a == b) return 0;
    if (a > b) return 1;
    return -1;
});

sql set variable using COUNT

You can select directly into the variable rather than using set:

DECLARE @times int

SELECT @times = COUNT(DidWin)
FROM thetable
WHERE DidWin = 1 AND Playername='Me'

If you need to set multiple variables you can do it from the same select (example a bit contrived):

DECLARE @wins int, @losses int

SELECT @wins = SUM(DidWin), @losses = SUM(DidLose)
FROM thetable
WHERE Playername='Me'

If you are partial to using set, you can use parentheses:

DECLARE @wins int, @losses int

SET (@wins, @losses) = (SELECT SUM(DidWin), SUM(DidLose)
FROM thetable
WHERE Playername='Me');

How to convert java.sql.timestamp to LocalDate (java8) java.time?

The accepted answer is not ideal, so I decided to add my 2 cents

timeStamp.toLocalDateTime().toLocalDate();

is a bad solution in general, I'm not even sure why they added this method to the JDK as it makes things really confusing by doing an implicit conversion using the system timezone. Usually when using only java8 date classes the programmer is forced to specify a timezone which is a good thing.

The good solution is

timestamp.toInstant().atZone(zoneId).toLocalDate()

Where zoneId is the timezone you want to use which is typically either ZoneId.systemDefault() if you want to use your system timezone or some hardcoded timezone like ZoneOffset.UTC

The general approach should be

  1. Break free to the new java8 date classes using a class that is directly related, e.g. in our case java.time.Instant is directly related to java.sql.Timestamp, i.e. no timezone conversions are needed between them.
  2. Use the well-designed methods in this java8 class to do the right thing. In our case atZone(zoneId) made it explicit that we are doing a conversion and using a particular timezone for it.

Differences between Ant and Maven

I'd say it depends upon the size of your project... Personnally, I would use Maven for simple projects that need straightforward compiling, packaging and deployment. As soon as you need to do some more complicated things (many dependencies, creating mapping files...), I would switch to Ant...

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

As the error messages stated, ngFor only supports Iterables such as Array, so you cannot use it for Object.

change

private extractData(res: Response) {
  let body = <Afdelingen[]>res.json();
  return body || {};       // here you are return an object
}

to

private extractData(res: Response) {
  let body = <Afdelingen[]>res.json().afdelingen;    // return array from json file
  return body || [];     // also return empty array if there is no data
}

How do getters and setters work?

class Clock {  
        String time;  

        void setTime (String t) {  
           time = t;  
        }  

        String getTime() {  
           return time;  
        }  
}  


class ClockTestDrive {  
   public static void main (String [] args) {  
   Clock c = new Clock;  

   c.setTime("12345")  
   String tod = c.getTime();  
   System.out.println(time: " + tod);  
 }
}  

When you run the program, program starts in mains,

  1. object c is created
  2. function setTime() is called by the object c
  3. the variable time is set to the value passed by
  4. function getTime() is called by object c
  5. the time is returned
  6. It will passe to tod and tod get printed out

Stacking DIVs on top of each other?

Position the outer div however you want, then position the inner divs using absolute. They'll all stack up.

_x000D_
_x000D_
.inner {_x000D_
  position: absolute;_x000D_
}
_x000D_
<div class="outer">_x000D_
   <div class="inner">1</div>_x000D_
   <div class="inner">2</div>_x000D_
   <div class="inner">3</div>_x000D_
   <div class="inner">4</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Syntax error due to using a reserved word as a table or column name in MySQL

The Problem

In MySQL, certain words like SELECT, INSERT, DELETE etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.

As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):

Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.

...

If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.

...

The identifier quote character is the backtick ("`"):

A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.

  • ADD
  • AND
  • BEFORE
  • BY
  • CALL
  • CASE
  • CONDITION
  • DELETE
  • DESC
  • DESCRIBE
  • FROM
  • GROUP
  • IN
  • INDEX
  • INSERT
  • INTERVAL
  • IS
  • KEY
  • LIKE
  • LIMIT
  • LONG
  • MATCH
  • NOT
  • OPTION
  • OR
  • ORDER
  • PARTITION
  • RANK
  • REFERENCES
  • SELECT
  • TABLE
  • TO
  • UPDATE
  • WHERE

The Solution

You have two options.

1. Don't use reserved words as identifiers

The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.

Doing this has a couple of advantages:

  • It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.

  • The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.

Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.

2. Use backticks

If renaming the table or column isn't possible, wrap the offending identifier in backticks (`) as described in the earlier quote from 10.2 Schema Object Names.

An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):

mysql> CREATE TABLE interval (begin INT, end INT);
ERROR 1064 (42000): You have an error in your SQL syntax.
near 'interval (begin INT, end INT)'

mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)

Similarly, the query from the question can be fixed by wrapping the keyword key in backticks, as shown below:

INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)";               ^   ^

See changes to a specific file using git

Totally agree with @Greg Hewgill

And if you path includes spaces, you might use, try adding with apostrophe ' or `

git diff 'MyProject/My Folder/My Sub Folder/file_2.rb'

Invalid argument supplied for foreach()

There seems also to be a relation to the environment:

I had that "invalid argument supplied foreach()" error only in the dev environment, but not in prod (I am working on the server, not localhost).

Despite the error a var_dump indicated that the array was well there (in both cases app and dev).

The if (is_array($array)) around the foreach ($array as $subarray) solved the problem.

Sorry, that I cannot explain the cause, but as it took me a while to figure a solution I thought of better sharing this as an observation.

Import SQL dump into PostgreSQL database

I believe that you want to run in psql:

\i C:/database/db-backup.sql

jQuery Button.click() event is triggered twice

If you use

$( document ).ready({ })

or

$(function() { });

more than once, the click function will trigger as many times as it is used.

Is there a list of screen resolutions for all Android based phones and tablets?

hdpi 480x800 px Samsung S2

xhdpi 720x1280 px - Nexus 4 phone - 4.7,4.8 inches Samsung Galaxy S3 Motorola Moto G

xxhdpi 1080x1920 px - Nexus 5 phone - 4.95 inches Samsung Galaxy S4 Samsung Galaxy S5 Samsung Galaxy Note 3 - 5.7 inches LG G2 HTC One M8 HTC One M9 Sony Xperia Z1
Sony Xperia Z2 Sony Xperia Z3 Sony Xperia Z3+

xxxhdpi 1440x2560 px - Nexus 6 phablet - 6 inches Samsung S6 Samsung S6 Edge Samsung Galaxy Note 4 - 5.7 inches LG G3
LG G4

xxhdpi 1920×1200 px - Nexus 7 tablet - 7 inches Sony Z3 Tablet Compact LG G Pad 8.3 - 8.3 inches Sony Xperia Z2 Tablet - 10.1 inches

xxxhdpi 2560×1600 px - Nexus 10 tablet - 10.1 inches ~Google Nexus 9 Sony Xperia Z4 tablet Samsung Galaxy Note Pro 12.2 Samsung Galaxy Note 10.1 Samsung Galaxy Tab S 10.5 Dell Venue 8 7840

How to check if Thread finished execution

Use Thread.Join(TimeSpan.Zero) It will not block the caller and returns a value indicating whether the thread has completed its work. By the way, that is the standard way of testing all WaitHandle classes as well.

AppSettings get value from .config file

Coming back to this one after a long time...

Given the demise of ConfigurationManager, for anyone still looking for an answer to this try (for example):

AppSettingsReader appsettingsreader = new AppSettingsReader();
string timeAsString = (string)(new AppSettingsReader().GetValue("Service.Instance.Trigger.Time", typeof(string)));

Requires System.Configuration of course.

(Editted the code to something that actually works and is simpler to read)

How do I load a PHP file into a variable?

If your file has a return statement like this:

<?php return array(
  'AF' => 'Afeganistão',
  'ZA' => 'África do Sul',
  ...
  'ZW' => 'Zimbabué'
);

You can get this to a variable like this:

$data = include $filePath;

SQL/mysql - Select distinct/UNIQUE but return all columns?

Just include all of your fields in the GROUP BY clause.

How to Install gcc 5.3 with yum on CentOS 7.2?

The best approach to use yum and update your devtoolset is to utilize the CentOS SCLo RH Testing repository.

yum install centos-release-scl-rh
yum --enablerepo=centos-sclo-rh-testing install devtoolset-7-gcc devtoolset-7-gcc-c++

Many additional packages are also available, to see them all

yum --enablerepo=centos-sclo-rh-testing list devtoolset-7*

You can use this method to install any dev tool version, just swap the 7 for your desired version. devtoolset-6-gcc, devtoolset-5-gcc etc.

Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()

If you are running your application just on localhost and it is not yet live, I believe it is very difficult to send mail using this.

Once you put your application online, I believe that this problem should be automatically solved. By the way,ini_set() helps you to change the values in php.ini during run time.

This is the same question as Failed to connect to mailserver at "localhost" port 25

also check this php mail function not working

opening html from google drive

Not available any more, https://support.google.com/drive/answer/2881970?hl=en

Host web pages with Google Drive

Note: This feature will not be available after August 31, 2016.

I highly recommend https://www.heroku.com/ and https://www.netlify.com/

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

Somehow I fixed it by changing

<add name="Access-Control-Allow-Headers" 
     value="Origin, X-Requested-With, Content-Type, Accept, Authorization" 
     />

to

<add name="Access-Control-Allow-Headers" 
     value="Origin, Content-Type, Accept, Authorization" 
     />

Histogram Matplotlib

This might be useful for someone.

Numpy's histogram function returns the edges of each bin, rather than the value of the bin. This makes sense for floating-point numbers, which can lie within an interval, but may not be the desired result when dealing with discrete values or integers (0, 1, 2, etc). In particular, the length of bins returned from np.histogram is not equal to the length of the counts / density.

To get around this, I used np.digitize to quantize the input, and count the fraction of counts for each bin. You could easily edit to get the integer number of counts.

def compute_PMF(data):
    import numpy as np
    from collections import Counter
    _, bins = np.histogram(data, bins='auto', range=(data.min(), data.max()), density=False)
    h = Counter(np.digitize(data,bins) - 1)
    weights = np.asarray(list(h.values())) 
    weights = weights / weights.sum()
    values = np.asarray(list(h.keys()))
    return weights, values
####

Refs:

[1] https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html

[2] https://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html

Example of a strong and weak entity types

After browsing search engines for a few hours I came across a site with a great ERD example here: http://www.exploredatabase.com/2016/07/description-about-weak-entity-sets-in-DBMS.html

I've recreated the ERD. Unfortunately they did not specify the primary key of the weak entity.

enter image description here

If the building could only have one and only one apartment, then it seems the partial discriminator room number would not be created (i.e. discarded).

How do I determine scrollHeight?

scrollHeight is a regular javascript property so you don't need jQuery.

var test = document.getElementById("foo").scrollHeight;

"inconsistent use of tabs and spaces in indentation"

If you are using Sublime Text for Python development, you can avoid the error by using the package Anaconda. After installing Anaconda, open your file in Sublime Text, right click on the open spaces ? choose Anaconda ? click on autoformat. Done. Or press Ctrl + Alt + R.

PHP CURL Enable Linux

add this line end of php.ini

openssl.cafile=/opt/lampp/share/curl/curl-ca-bundle.crt

may be curl path cannot be identified by PHP

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

Please try this code

new_column=df[['col1', 'col2', 'col3', 'col4']].groupby(['col1', 'col2']).count()
df['count_it']=new_column
df

I think that code will add a column called 'count it' which count of each group

Is it a bad practice to use break in a for loop?

I disagree!

Why would you ignore the built-in functionality of a for loop to make your own? You do not need to reinvent the wheel.

I think it makes more sense to have your checks at the top of your for loop like so

for(int i = 0; i < myCollection.Length && myCollection[i].SomeValue != "Break Condition"; i++)
{
//loop body
}

or if you need to process the row first

for(int i = 0; i < myCollection.Length && (i == 0 ? true : myCollection[i-1].SomeValue != "Break Condition"); i++)
{
//loop body
}

This way you can write a function to perform everything and make much cleaner code.

for(int i = 0; i < myCollection.Length && (i == 0 ? true : myCollection[i-1].SomeValue != "Break Condition"); i++)
{
    DoAllThatCrazyStuff(myCollection[i]);
}

Or if your condition is complicated you can move that code out too!

for(int i = 0; i < myCollection.Length && BreakFunctionCheck(i, myCollection); i++)
{
    DoAllThatCrazyStuff(myCollection[i]);
}

"Professional Code" that is riddled with breaks doesn't really sound like professional code to me. It sounds like lazy coding ;)

Subtract one day from datetime

This should work.

select DATEADD(day, -1, convert(date, GETDATE()))

CentOS: Enabling GD Support in PHP Installation

  1. You need to find a repo that offers a GD lib matching your current php version. I've had great success using Remi Collet's repo for this purpose. In fact, I used it yesterday to update my php install to the latest 5.4.0RC6 version on my CentOS6 box.
  2. Once you've setup the repo it's a simple matter of running sudo yum install php-gd
  3. Of course, the usual things apply: make sure you restart apache after installing, etc.

HTTP 415 unsupported media type error when calling Web API 2 endpoint

I also experienced this error.

I add into header Content-Type: application/json. Following the change, my submissions succeed!

Could not load file or assembly or one of its dependencies. Access is denied. The issue is random, but after it happens once, it continues

If you get the DLL could not be found instead of access denied, make sure you have the appropriate VC++ Redistributable installed.

Docker for Windows error: "Hardware assisted virtualization and data execution protection must be enabled in the BIOS"

I had the same issue after installing VMWare, I uninstalled it but this didn't fix the issue.

Solution for me: in "Turn windows features on or off" I turned off:

  • hyper-v
  • containers
  • windows subsystem for linux

then restart

After the restart I got this message from docker:

enter image description here

I ran the ran the command as said in the message

Enable-WindowsOptionalFeature -Online -FeatureName $("VirtualMachinePlatform", "Microsoft-Windows-Subsystem-Linux")

Then restart and voilà, Docker was back with WSL2

HTTP Ajax Request via HTTPS Page

Still, this can be done with the following steps:

  1. send an https ajax request to your web-site (the same domain)

    jQuery.ajax({
        'url'      : '//same_domain.com/ajax_receiver.php',
        'type'     : 'get',
        'data'     : {'foo' : 'bar'},
        'success'  : function(response) {
            console.log('Successful request');
        }
    }).fail(function(xhr, err) {
        console.error('Request error');
    });
    
  2. get ajax request, for example, by php, and make a CURL get request to any desired website via http.

    use linslin\yii2\curl;
    $curl = new curl\Curl();
    $curl->get('http://example.com');
    

How to set different colors in HTML in one statement?

How about using FONT tag?

Like:

H<font color="red">E</font>LLO.

Can't show example here, because this site doesn't allow font tag use.

Span style is fast and easy too.

Vertically center text in a 100% height div?

I disagree, here's a JS free solution, which works:

<html style="height: 100%;">
    <body style="vertical-align: middle; margin: 0px; height: 100%;">
        <div style="height: 100%; width: 100%; display: table; background-color: #ccc;">
            <div style="display: table-cell; width: 100%; vertical-align: middle;">
                <div style="height: 300px; width: 600px; background-color: wheat; margin-left: auto; margin-right: auto;">A</div>
            </div>
        </div>
    </body>
</html>

How do I get a list of installed CPAN modules?

Try the following command

instmodsh

How to select element using XPATH syntax on Selenium for Python?

Check this blog by Martin Thoma. I tested the below code on MacOS Mojave and it worked as specified.

> def get_browser():
>     """Get the browser (a "driver")."""
>     # find the path with 'which chromedriver'
>     path_to_chromedriver = ('/home/moose/GitHub/algorithms/scraping/'
>                             'venv/bin/chromedriver')
>     download_dir = "/home/moose/selenium-download/"
>     print("Is directory: {}".format(os.path.isdir(download_dir)))
> 
>     from selenium.webdriver.chrome.options import Options
>     chrome_options = Options()
>     chrome_options.add_experimental_option('prefs', {
>         "plugins.plugins_list": [{"enabled": False,
>                                   "name": "Chrome PDF Viewer"}],
>         "download": {
>             "prompt_for_download": False,
>             "default_directory": download_dir
>         }
>     })
> 
>     browser = webdriver.Chrome(path_to_chromedriver,
>                                chrome_options=chrome_options)
>     return browser

Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"?

This is called programming to interface. This will be helpful in case if you wish to move to some other implementation of List in the future. If you want some methods in ArrayList then you would need to program to the implementation that is ArrayList a = new ArrayList().

How can I get a side-by-side diff when I do "git diff"?

For unix, combining just git and the built-in diff:

git show HEAD:path/to/file | diff -y - path/to/file

Of course, you can replace HEAD with any other git reference, and you probably want to add something like -W 170 to the diff command.

This assumes that you are just comparing your directory contents with a past commit. Comparing between two commits is more complex. If your shell is bash you can use "process substitution":

diff -y -W 170 <(git show REF1:path/to/file) <(git show REF2:path/to/file)

where REF1 and REF2 are git references – tags, branches or hashes.

Integrity constraint violation: 1452 Cannot add or update a child row:

I had this issue when I was accidentally using the WRONG "uuid" in my child record. When that happens the constraint looks from the child to the parent record to ensure that the link is correct. I was generating it manually, when I had already rigged my Model to do it automatically. So my fix was:

$parent = Parent:create($recData); // asssigning autogenerated uuid into $parent

Then when I called my child class to insert children, I passed this var value:

$parent->uuid

Hope that helps.

How to check empty object in angular 2 template using *ngIf

You could also use something like that:

<div class="comeBack_up" *ngIf="isEmptyObject(previous_info)"  >

with the isEmptyObject method defined in your component:

isEmptyObject(obj) {
  return (obj && (Object.keys(obj).length === 0));
}

How to get file creation & modification date/times in Python?

os.stat returns a named tuple with st_mtime and st_ctime attributes. The modification time is st_mtime on both platforms; unfortunately, on Windows, ctime means "creation time", whereas on POSIX it means "change time". I'm not aware of any way to get the creation time on POSIX platforms.

Uses of content-disposition in an HTTP response header

This header is defined in RFC 2183, so that would be the best place to start reading.

Permitted values are those registered with the Internet Assigned Numbers Authority (IANA); their registry of values should be seen as the definitive source.

How to call Android contacts list?

To my surprise you do not need users-permission CONTACT_READ to read the names and some basic information (Is the contact starred, what was the last calling time). However you do need permission to read the details of the contact like phone number.

Associating enums with strings in C#

I was basically looking for the Reflection answer by @ArthurC

Just to extend his answer a little bit, you can make it even better by having a generic function:

    // If you want for a specific Enum
    private static string EnumStringValue(GroupTypes e)
    {
        return EnumStringValue<GroupTypes>(e);
    }

    // Generic
    private static string EnumStringValue<T>(T enumInstance)
    {
        return Enum.GetName(typeof(T), enumInstance);
    } 

Then you can just wrap whatever you have

EnumStringValue(GroupTypes.TheGroup) // if you incorporate the top part

or

EnumStringValue<GroupTypes>(GroupTypes.TheGroup) // if you just use the generic

Update all objects in a collection using LINQ

I assume you want to change values inside a query so you could write a function for it

void DoStuff()
{
    Func<string, Foo, bool> test = (y, x) => { x.Bar = y; return true; };
    List<Foo> mylist = new List<Foo>();
    var v = from x in mylist
            where test("value", x)
            select x;
}

class Foo
{
    string Bar { get; set; }
}

But not shure if this is what you mean.

How to loop over grouped Pandas dataframe?

df.groupby('l_customer_id_i').agg(lambda x: ','.join(x)) does already return a dataframe, so you cannot loop over the groups anymore.

In general:

  • df.groupby(...) returns a GroupBy object (a DataFrameGroupBy or SeriesGroupBy), and with this, you can iterate through the groups (as explained in the docs here). You can do something like:

    grouped = df.groupby('A')
    
    for name, group in grouped:
        ...
    
  • When you apply a function on the groupby, in your example df.groupby(...).agg(...) (but this can also be transform, apply, mean, ...), you combine the result of applying the function to the different groups together in one dataframe (the apply and combine step of the 'split-apply-combine' paradigm of groupby). So the result of this will always be again a DataFrame (or a Series depending on the applied function).

SonarQube Exclude a directory

Easiest way is to go to the server URL after starting the server(localhost:8080) then login as admin,Go to settings>Exclusions> Source File Exclusions- Add your packages here. Restart the server.

Adding Google Play services version to your app's manifest?

Simply removing the google play services library from the project and adding once again from sdk->extras->google folder solved my problem perfectly.

Composer killed while updating

Increase the memory limit for composer

php -d memory_limit=4G /usr/local/bin/composer update

How to redirect to Index from another controller?

You can use the following code:

return RedirectToAction("Index", "Home");

See RedirectToAction

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

The posted code solutions may cause problems when you need to set up multiple SMTP sessions anywhere within the same JVM.

The JavaMail FAQ recommends using

Session.getInstance(properties);

instead of

Session.getDefaultInstance(properties);

because the getDefault will only use the properties given the first time it is invoked. All later uses of the default instance will ignore property changes.

See http://www.oracle.com/technetwork/java/faq-135477.html#getdefaultinstance

CodeIgniter: How to use WHERE clause and OR clause

You can use this :

$this->db->select('*');
$this->db->from('mytable');
$this->db->where(name,'Joe');
$bind = array('boss', 'active');
$this->db->where_in('status', $bind);

Push Notifications in Android Platform

You can use Xtify (http://developer.xtify.com) - they have a push notifications webservice that works with their SDK. it's free and so far, it's worked really well for me.

What is an example of the simplest possible Socket.io example?

index.html

<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
      #messages { margin-bottom: 40px }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      $(function () {
        var socket = io();
        $('form').submit(function(){
          socket.emit('chat message', $('#m').val());
          $('#m').val('');
          return false;
        });
        socket.on('chat message', function(msg){
          $('#messages').append($('<li>').text(msg));
          window.scrollTo(0, document.body.scrollHeight);
        });
      });
    </script>
  </body>
</html>

index.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

http.listen(port, function(){
  console.log('listening on *:' + port);
});

And run these commands for run the application.

npm init;  // accept defaults
npm  install  socket.io  http  --save ;
node start

and open the URL:- http://127.0.0.1:3000/ Port may be different. and you will see this OUTPUT

enter image description here

How do I debug Node.js applications?

Theseus is a project by Adobe research which lets you debug your Node.js code in their Open Source editor Brackets. It has some interesting features like real-time code coverage, retroactive inspection, asynchronous call tree.

screenshot

Changing text color of menu item in navigation drawer

You can use drawables in

app:itemTextColor app:itemIconTint

then you can control the checked state and normal state using a drawable

<android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:itemHorizontalPadding="@dimen/margin_30"
            app:itemIconTint="@drawable/drawer_item_color"
            app:itemTextColor="@drawable/drawer_item_color"
            android:theme="@style/NavigationView"
            app:headerLayout="@layout/nav_header"
            app:menu="@menu/drawer_menu">

drawer_item_color.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/selectedColor" android:state_checked="true" />
    <item android:color="@color/normalColor" />
</selector>

Count with IF condition in MySQL query

Use sum() in place of count()

Try below:

SELECT
    ccc_news . * , 
    SUM(if(ccc_news_comments.id = 'approved', 1, 0)) AS comments
FROM
    ccc_news
    LEFT JOIN
        ccc_news_comments
    ON
        ccc_news_comments.news_id = ccc_news.news_id
WHERE
    `ccc_news`.`category` = 'news_layer2'
    AND `ccc_news`.`status` = 'Active'
GROUP BY
    ccc_news.news_id
ORDER BY
    ccc_news.set_order ASC
LIMIT 20 

Sending SMS from PHP

PHP by itself has no SMS module or functions and doesn't allow you to send SMS.

SMS ( Short Messaging System) is a GSM technology an you need a GSM provider that will provide this service for you and may have an PHP API implementation for it.

Usually people in telecom business use Asterisk to handle calls and sms programming.

PHP passing $_GET in linux command prompt

If you need to pass $_GET, $_REQUEST, $_POST, or anything else you can also use PHP interactive mode:

php -a

Then type:

<?php
$_GET['a']=1;
$_POST['b']=2;
include("/somefolder/some_file_path.php");

This will manually set any variables you want and then run your php file with those variables set.

How can I detect the touch event of an UIImageView?

Instead of making a touchable UIImageView then placing it on the navbar, you should just create a UIBarButtonItem, which you make out of a UIImageView.

First make the image view:

UIImageView *yourImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"nameOfYourImage.png"]];

Then make the barbutton item out of your image view:

UIBarButtonItem *yourBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:yourImageView];

Then add the bar button item to your navigation bar:

self.navigationItem.rightBarButtonItem = yourBarButtonItem;

Remember that this code goes into the view controller which is inside a navigation controller viewcontroller array. So basically, this "touchable image-looking bar button item" will only appear in the navigation bar when this view controller when it's being shown. When you push another view controller, this navigation bar button item will disappear.

When to use setAttribute vs .attribute= in JavaScript?

One case I found where setAttribute is necessary is when changing ARIA attributes, since there are no corresponding properties. For example

x.setAttribute('aria-label', 'Test');
x.getAttribute('aria-label');

There's no x.arialabel or anything like that, so you have to use setAttribute.

Edit: x["aria-label"] does not work. You really do need setAttribute.

x.getAttribute('aria-label')
null
x["aria-label"] = "Test"
"Test"
x.getAttribute('aria-label')
null
x.setAttribute('aria-label', 'Test2')
undefined
x["aria-label"]
"Test"
x.getAttribute('aria-label')
"Test2"

I don't have "Dynamic Web Project" option in Eclipse new Project wizard

This helped me find the "Dynamic web project" in Eclipse 2020-12 version. Restart the eclipse and go to file->new->other->web and you will see project will be available.

#define in Java

Comment space too small, so here is some more information for you on the use of static final. As I said in my comment to the Andrzej's answer, only primitive and String are compiled directly into the code as literals. To demonstrate this, try the following:

You can see this in action by creating three classes (in separate files):

public class DisplayValue {
    private String value;

    public DisplayValue(String value) {
        this.value = value;
    }

    public String toString() {
        return value;
    }
}

public class Constants {
    public static final int INT_VALUE = 0;
    public static final DisplayValue VALUE = new DisplayValue("A");
}

public class Test {
    public static void main(String[] args) {
        System.out.println("Int   = " + Constants.INT_VALUE);
        System.out.println("Value = " + Constants.VALUE);
    }
}

Compile these and run Test, which prints:

Int    = 0
Value  = A

Now, change Constants to have a different value for each and just compile class Constants. When you execute Test again (without recompiling the class file) it still prints the old value for INT_VALUE but not VALUE. For example:

public class Constants {
    public static final int INT_VALUE = 2;
    public static final DisplayValue VALUE = new DisplayValue("X");
}

Run Test without recompiling Test.java:

Int    = 0
Value  = X

Note that any other type used with static final is kept as a reference.

Similar to C/C++ #if/#endif, a constant literal or one defined through static final with primitives, used in a regular Java if condition and evaluates to false will cause the compiler to strip the byte code for the statements within the if block (they will not be generated).

private static final boolean DEBUG = false;

if (DEBUG) {
    ...code here...
}

The code at "...code here..." would not be compiled into the byte code. But if you changed DEBUG to true then it would be.

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in

The in operator only works on objects. You are using it on a string. Make sure your value is an object before you using $.each. In this specific case, you have to parse the JSON:

$.each(JSON.parse(myData), ...);

npm install hangs

I'm not sure if your problem is being caused by the same reason that mine was, but I too was experiencing a hanging "npm install" and was able to fix it.

In my case, I wanted to install typescript locally in the project:

npm i typescript --save-dev

For some reason this was conflicting with a global install of typescript that I had, and the shell was just hanging forever instead of finishing or erroring...

I fixing it by first removing the globally installed typescript with the -g global flag:

npm uninstall typescript -g

After doing this the first command worked!

How to stop mongo DB in one command

Use mongod --shutdown

According to the official doc : manage-mongodb-processes/

:D

How to remove docker completely from ubuntu 14.04

Apparently, the system I was using had the docker-ce not Docker. Thus, running below command did the trick.

sudo apt-get purge docker-ce

sudo rm -rf /var/lib/docker

hope it helps

How to update RecyclerView Adapter Data?

This is a general answer for future visitors. The various ways to update the adapter data are explained. The process includes two main steps every time:

  1. Update the data set
  2. Notify the adapter of the change

#Insert single item

Add "Pig" at index 2.

Insert single item
String item = "Pig";
int insertIndex = 2;
data.add(insertIndex, item);
adapter.notifyItemInserted(insertIndex);

#Insert multiple items

Insert three more animals at index 2.

Insert multiple items
ArrayList<String> items = new ArrayList<>();
items.add("Pig");
items.add("Chicken");
items.add("Dog");
int insertIndex = 2;
data.addAll(insertIndex, items);
adapter.notifyItemRangeInserted(insertIndex, items.size());

#Remove a single item

Remove "Pig" from the list.

Remove single item
int removeIndex = 2;
data.remove(removeIndex);
adapter.notifyItemRemoved(removeIndex);

#Remove multiple items

Remove "Camel" and "Sheep" from the list.

Remove multiple items
int startIndex = 2; // inclusive
int endIndex = 4;   // exclusive
int count = endIndex - startIndex; // 2 items will be removed
data.subList(startIndex, endIndex).clear();
adapter.notifyItemRangeRemoved(startIndex, count);

#Remove all items

Clear the whole list.

Remove all items
data.clear();
adapter.notifyDataSetChanged();

#Replace old list with the new list

Clear the old list then add a new one.

Replace old list with new list
// clear old list
data.clear();

// add new list
ArrayList<String> newList = new ArrayList<>();
newList.add("Lion");
newList.add("Wolf");
newList.add("Bear");
data.addAll(newList);

// notify adapter
adapter.notifyDataSetChanged();

The adapter has a reference to data, so it is important that I didn't set data to a new object. Instead, I cleared the old items from data and then added the new ones.

#Update single item

Change the "Sheep" item so that it says "I like sheep."

Update single item
String newValue = "I like sheep.";
int updateIndex = 3;
data.set(updateIndex, newValue);
adapter.notifyItemChanged(updateIndex);

#Move single item

Move "Sheep" from position 3 to position 1.

Move single item
int fromPosition = 3;
int toPosition = 1;

// update data array
String item = data.get(fromPosition);
data.remove(fromPosition);
data.add(toPosition, item);

// notify adapter
adapter.notifyItemMoved(fromPosition, toPosition);

#Code

Here is the project code for your reference. The RecyclerView Adapter code can be found at this answer.

MainActivity.java

public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {

    List<String> data;
    MyRecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // data to populate the RecyclerView with
        data = new ArrayList<>();
        data.add("Horse");
        data.add("Cow");
        data.add("Camel");
        data.add("Sheep");
        data.add("Goat");

        // set up the RecyclerView
        RecyclerView recyclerView = findViewById(R.id.rvAnimals);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
                layoutManager.getOrientation());
        recyclerView.addItemDecoration(dividerItemDecoration);
        adapter = new MyRecyclerViewAdapter(this, data);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onItemClick(View view, int position) {
        Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
    }

    public void onButtonClick(View view) {
        insertSingleItem();
    }

    private void insertSingleItem() {
        String item = "Pig";
        int insertIndex = 2;
        data.add(insertIndex, item);
        adapter.notifyItemInserted(insertIndex);
    }

    private void insertMultipleItems() {
        ArrayList<String> items = new ArrayList<>();
        items.add("Pig");
        items.add("Chicken");
        items.add("Dog");
        int insertIndex = 2;
        data.addAll(insertIndex, items);
        adapter.notifyItemRangeInserted(insertIndex, items.size());
    }

    private void removeSingleItem() {
        int removeIndex = 2;
        data.remove(removeIndex);
        adapter.notifyItemRemoved(removeIndex);
    }

    private void removeMultipleItems() {
        int startIndex = 2; // inclusive
        int endIndex = 4;   // exclusive
        int count = endIndex - startIndex; // 2 items will be removed
        data.subList(startIndex, endIndex).clear();
        adapter.notifyItemRangeRemoved(startIndex, count);
    }

    private void removeAllItems() {
        data.clear();
        adapter.notifyDataSetChanged();
    }

    private void replaceOldListWithNewList() {
        // clear old list
        data.clear();

        // add new list
        ArrayList<String> newList = new ArrayList<>();
        newList.add("Lion");
        newList.add("Wolf");
        newList.add("Bear");
        data.addAll(newList);

        // notify adapter
        adapter.notifyDataSetChanged();
    }

    private void updateSingleItem() {
        String newValue = "I like sheep.";
        int updateIndex = 3;
        data.set(updateIndex, newValue);
        adapter.notifyItemChanged(updateIndex);
    }

    private void moveSingleItem() {
        int fromPosition = 3;
        int toPosition = 1;

        // update data array
        String item = data.get(fromPosition);
        data.remove(fromPosition);
        data.add(toPosition, item);

        // notify adapter
        adapter.notifyItemMoved(fromPosition, toPosition);
    }
}

#Notes

  • If you use notifyDataSetChanged(), then no animation will be performed. This can also be an expensive operation, so it is not recommended to use notifyDataSetChanged() if you are only updating a single item or a range of items.
  • Check out DiffUtil if you are making large or complex changes to a list.

#Further study

How to concatenate two MP4 files using FFmpeg?

Here is a script (works for an arbitrary number of specified files (not just all in the working directory), without additional files, also works for .mov; tested on macOS):

#!/bin/bash

if [ $# -lt 1 ]; then
    echo "Usage: `basename $0` input_1.mp4 input_2.mp4 ... output.mp4"
    exit 0
fi

ARGS=("$@") # determine all arguments
output=${ARGS[${#ARGS[@]}-1]} # get the last argument (output file)
unset ARGS[${#ARGS[@]}-1] # drop it from the array
(for f in "${ARGS[@]}"; do echo "file '$f'"; done) | ffmpeg -protocol_whitelist file,pipe -f concat -safe 0 -i pipe: -vcodec copy -acodec copy $output

Get href attribute on jQuery

Use this:

$(function(){
    $("tr.b_row").each(function(){
    var a_href = $(this).find('div.cpt h2 a').attr('href');
    alert ("Href is: "+a_href);

    });
});

See a working demo: http://jsfiddle.net/usmanhalalit/4Ea4k/1/

Combining Two Images with OpenCV

For cases where your images happen to be the same size (which is a common case for displaying image processing results), you can use numpy's concatenate to simplify your code.

To stack vertically (img1 over img2):

vis = np.concatenate((img1, img2), axis=0)

To stack horizontally (img1 to the left of img2):

vis = np.concatenate((img1, img2), axis=1)

To verify:

import cv2
import numpy as np
img1 = cv2.imread('img1.png')
img2 = cv2.imread('img2.png')
vis = np.concatenate((img1, img2), axis=1)
cv2.imwrite('out.png', vis)

The out.png image will contain img1 on the left and img2 on the right.

Add "Appendix" before "A" in thesis TOC

You can easily achieve what you want using the appendix package. Here's a sample file that shows you how. The key is the titletoc option when calling the package. It takes whatever value you've defined in \appendixname and the default value is Appendix.

\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents

\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
  \chapter{Consectetur adipiscing elit}
  \chapter{Mauris euismod}
\end{appendices}
\end{document}

The output looks like

enter image description here

How do I run a PowerShell script when the computer starts?

Prerequisite:

1. Start powershell with the "Run as Administrator" option

2. Enable running unsigned scripts with:

set-executionpolicy remotesigned

3. prepare your powershell script and know its path:

$path = "C:\Users\myname\myscript.ps1"

Steps:

1. setup a trigger, see also New-JobTrigger (PSScheduledJob) - PowerShell | Microsoft Docs

$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:30

2. register a scheduled job, see also Register-ScheduledJob (PSScheduledJob) - PowerShell | Microsoft Docs

Register-ScheduledJob -Trigger $trigger -FilePath $path -Name MyScheduledJob

you can check it with Get-ScheduledJob -Name MyScheduledJob

3. Reboot Windows (restart /r) and check the result with:

Get-Job -name MyScheduledJob

see also Get-Job (Microsoft.PowerShell.Core) - PowerShell | Microsoft Docs

References:

  1. How to enable execution of PowerShell scripts? - Super User
  2. Use PowerShell to Create Job that Runs at Startup | Scripting Blog

how to update spyder on anaconda

You can easily install update version if you use Anaconda by closing Spyder and then running the following command in a system terminal (Anaconda Prompt on Windows, xterm on Linux or Terminal.app on macOS):

conda install spyder= Your desire version

(For example, Version is 3.1)

conda install spyder=3.1

Or you can use pip with this command in a system terminal (cmd.exe on Windows, xterm on Linux or Terminal.app on macOS):

pip install --pre -U spyder

Note: Do not use this command if you are using Anaconda because it could break your installation.

Convert month int to month name

You can do something like this instead.

return new DateTime(2010, Month, 1).ToString("MMM");

How to run two jQuery animations simultaneously?

While it's true that consecutive calls to animate will give the appearance they are running at the same time, the underlying truth is they're distinct animations running very close to parallel.

To insure the animations are indeed running at the same time use:

$(function() {
    $('#first').animate({..., queue: 'my-animation'});
    $('#second').animate({..., queue: 'my-animation'}).dequeue('my-animation');
});

Further animations can be added to the 'my-animation' queue and all can be initiated provided the last animation dequeue's them.

Cheers, Anthony

Java - Access is denied java.io.FileNotFoundException

When you create a new File, you are supposed to provide the file name, not only the directory you want to put your file in.

Try with something like

File file = new File("D:/Data/" + item.getFileName());

Changing default startup directory for command prompt in Windows 7

My default dir was system32 when starting CMD. I then created a batch file in that directory to change dir to the one I was after.

This caused me to always call that bat when starting CMD every time. So I made a reg file & put this inside:

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"Autorun"="cd C:\\Users\\Me\\SomeFolder"

After saving it, I opened the file, clicked ok to merge with registry, and since then every time I open CMD, I get my dir

Node.js getaddrinfo ENOTFOUND

I tried it using the request module, and was able to print the body of that page out pretty easily. Unfortunately with the skills I have, I can't help other than that.

How to push both key and value into an Array in Jquery

I think you need to define an object and then push in array

var obj = {};
obj[name] = val;
ary.push(obj);

Listing files in a specific "folder" of a AWS S3 bucket

you can check the type. s3 has a special application/x-directory

bucket.objects({:delimiter=>"/", :prefix=>"f1/"}).each { |obj| p obj.object.content_type }

Multi value Dictionary

Here is an implementation of a single key to multi value map in C# which uses a set based key type:

https://github.com/ColmBhandal/CsharpExtras/blob/master/CsharpExtras/Dictionary/MultiValueMapImpl.cs

The dictionary behaves like a regular dictionary from the key type onto a set of the value type, but also provides functionality to directly add a single value of the value type, and in the background handles the creation of an underlying set and/or addition to that set.

In java how to get substring from a string till a character c?

You can just split the string..

public String[] split(String regex)

Note that java.lang.String.split uses delimiter's regular expression value. Basically like this...

String filename = "abc.def.ghi";     // full file name
String[] parts = filename.split("\\."); // String array, each element is text between dots

String beforeFirstDot = parts[0];    // Text before the first dot

Of course, this is split into multiple lines for clairity. It could be written as

String beforeFirstDot = filename.split("\\.")[0];

How can I show a combobox in Android?

In android it is called a Spinner you can take a look at the tutorial here.

Hello, Spinner

And this is a very vague question, you should try to be more descriptive of your problem.

Set value for particular cell in pandas DataFrame using index

In my example i just change it in selected cell

    for index, row in result.iterrows():
        if np.isnan(row['weight']):
            result.at[index, 'weight'] = 0.0

'result' is a dataField with column 'weight'

Express: How to pass app-instance to routes from a different file?

If you want to pass an app-instance to others in Node-Typescript :

Option 1: With the help of import (when importing)

//routes.ts
import { Application } from "express";
import { categoryRoute } from './routes/admin/category.route'
import { courseRoute } from './routes/admin/course.route';

const routing = (app: Application) => {
    app.use('/api/admin/category', categoryRoute)
    app.use('/api/admin/course', courseRoute)
}
export { routing }

Then import it and pass app:

import express, { Application } from 'express';

const app: Application = express();
import('./routes').then(m => m.routing(app))

Option 2: With the help of class

// index.ts
import express, { Application } from 'express';
import { Routes } from './routes';


const app: Application = express();
const rotues = new Routes(app)
...

Here we will access the app in the constructor of Routes Class

// routes.ts
import { Application } from 'express'
import { categoryRoute } from '../routes/admin/category.route'
import { courseRoute } from '../routes/admin/course.route';

class Routes {
    constructor(private app: Application) {
        this.apply();
    }

    private apply(): void {
       this.app.use('/api/admin/category', categoryRoute)
       this.app.use('/api/admin/course', courseRoute)
    }
}

export { Routes }

Android: android.content.res.Resources$NotFoundException: String resource ID #0x5

You are assigning a numeric value to a text field. You have to convert the numeric value to a string with:

String.valueOf(variable)

How to find file accessed/created just few minutes ago

Simply specify whether you want the time to be greater, smaller, or equal to the time you want, using, respectively:

find . -cmin +<time>
find . -cmin -<time>
find . -cmin  <time>

In your case, for example, the files with last edition in a maximum of 5 minutes, are given by:

find . -cmin -5

How to get First and Last record from a sql query?

I think this code gets the same and is easier to read.

SELECT <some columns> 
FROM mytable
<maybe some joins here>
WHERE date >= (SELECT date from mytable)
OR date <= (SELECT date from mytable);

Disabling enter key for form

if you use jQuery, its quite simple. Here you go

$(document).keypress(
  function(event){
    if (event.which == '13') {
      event.preventDefault();
    }
});

How to reload/refresh an element(image) in jQuery

It sounds like it's your browser caching the image (which I now notice you wrote in your question). You can force the browser to reload the image by passing an extra variable like so:

d = new Date();
$("#myimg").attr("src", "/myimg.jpg?"+d.getTime());

Get the current fragment object

Now at some point of time I need to identify which object is currently there

Call findFragmentById() on FragmentManager and determine which fragment is in your R.id.frameTitle container.

If you are using the androidx edition of Fragment — as you should in modern apps — , use getSupportFragmentManager() on your FragmentActivity/AppCompatActivity instead of getFragmentManager()

Combine hover and click functions (jQuery)?

You can use .bind() or .live() whichever is appropriate, but no need to name the function:

$('#target').bind('click hover', function () {
 // common operation
});

or if you were doing this on lots of element (not much sense for an IE unless the element changes):

$('#target').live('click hover', function () {
 // common operation
});

Note, this will only bind the first hover argument, the mouseover event, it won't hook anything to the mouseleave event.

Properly embedding Youtube video into bootstrap 3.0 page

I use bootstrap 3.x as well and the following code fore responsive youtube video embedding works like charm for me:

.videoWrapperOuter {
  max-width:640px; 
  margin-left:auto;
  margin-right:auto;
}
.videoWrapperInner {
  float: none;
  clear: both;
  width: 100%;
  position: relative;
  padding-bottom: 50%;
  padding-top: 25px;
  height: 0;
}
.videoWrapperInner iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
<div class="videoWrapperOuter">
  <div class="videoWrapperInner">
    <iframe src="//www.youtube.com/embed/C6-TWRn0k4I" 
      frameborder="0" allowfullscreen></iframe>
  </div>
</div>

I gave a similiar answer on another thread (Shrink a YouTube video to responsive width), but I guess my answers can help here as well.

Query based on multiple where clauses in Firebase

Frank's answer is good but Firestore introduced array-contains recently that makes it easier to do AND queries.

You can create a filters field to add you filters. You can add as many values as you need. For example to filter by comedy and Jack Nicholson you can add the value comedy_Jack Nicholson but if you also you want to by comedy and 2014 you can add the value comedy_2014 without creating more fields.

{
  "movies": {
    "movie1": {
      "genre": "comedy",
      "name": "As good as it gets",
      "lead": "Jack Nicholson",
      "year": 2014,
      "filters": [
        "comedy_Jack Nicholson",
        "comedy_2014"
      ]
    }
  }
}

How can I do an UPDATE statement with JOIN in SQL Server?

The simplest way is to use the Common Table Expression (CTE) introduced in SQL 2005

with cte as
(select u.assid col1 ,s.assid col2 from ud u inner join sale s on u.id = s.udid)
update cte set col1=col2

How to check if a string is a number?

#include <stdio.h>
#include <string.h>
char isNumber(char *text)
{
    int j;
    j = strlen(text);
    while(j--)
    {
        if(text[j] > 47 && text[j] < 58)
            continue;

        return 0;
    }
    return 1;
}
int main(){
    char tmp[16];
    scanf("%s", tmp);

    if(isNumber(tmp))
        return printf("is a number\n");

    return printf("is not a number\n");
}

You can also check its stringfied value, which could also work with non Ascii

char isNumber(char *text)
{
    int j;
    j = strlen(text);
    while(j--)
    {
        if(text[j] >= '0' && text[j] <= '9')
            continue;

        return 0;
    }
    return 1;
}

Is it possible in Java to access private fields via reflection

Yes it is possible.

You need to use the getDeclaredField method (instead of the getField method), with the name of your private field:

Field privateField = Test.class.getDeclaredField("str");

Additionally, you need to set this Field to be accessible, if you want to access a private field:

privateField.setAccessible(true);

Once that's done, you can use the get method on the Field instance, to access the value of the str field.

How can I apply styles to multiple classes at once?

You can have multiple CSS declarations for the same properties by separating them with commas:

.abc, .xyz {
   margin-left: 20px;
}

Laravel - Form Input - Multiple select for a one to many relationship

A multiple select is really just a select with a multiple attribute. With that in mind, it should be as easy as...

Form::select('sports[]', $sports, null, array('multiple'))

The first parameter is just the name, but post-fixing it with the [] will return it as an array when you use Input::get('sports').

The second parameter is an array of selectable options.

The third parameter is an array of options you want pre-selected.

The fourth parameter is actually setting this up as a multiple select dropdown by adding the multiple property to the actual select element..

How to reset (clear) form through JavaScript?

form.reset() is a DOM element method (not one on the jQuery object), so you need:

$("#client.frm")[0].reset();
//faster version:
$("#client")[0].reset();

Or without jQuery:

document.getElementById("client").reset();

Convert MFC CString to integer

A _ttoi function can convert CString to integer, both wide char and ansi char can work. Below is the details:

CString str = _T("123");
int i = _ttoi(str);

How to "Open" and "Save" using java

You want to use a JFileChooser object. It will open and be modal, and block in the thread that opened it until you choose a file.

Open:

JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) {
  File file = fileChooser.getSelectedFile();
  // load from file
}

Save:

JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) {
  File file = fileChooser.getSelectedFile();
  // save to file
}

There are more options you can set to set the file name extension filter, or the current directory. See the API for the javax.swing.JFileChooser for details. There is also a page for "How to Use File Choosers" on Oracle's site:

http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html

Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?

I know I told babay in 2012 that I thought it was unlikely that someone wouldn't realize that they weren't on a branch and commit. This just happened to me, so I guess I have to admit that I was wrong, but considering that it took until 2016 for this to happen to me, you could argue that it is in fact unlikely.

Anyway, creating a new branch is overkill in my opinion. All you have to do is:

git checkout some-branch
git merge commit-sha

If you didn't copy the commit-sha before checking out the other branch, you can easily find it by running:

git reflog

How to print the data in byte array as characters?

Try this one : new String(byte[])

Fixed page header overlaps in-page anchors

A very simple CSS only answer is to put this at the top of your stylesheet:

a{padding-top: 90px;}
a:link{padding-top: unset;}

The first style regulates all anchor tags where the second styles anchor tags with a hyperlink.

Note: This currently works in Firefox and Edge but nor in Chrome.

How to get < span > value?

Pure javascript would be like this

var children = document.getElementById('test').children;

If you are using jQuery it would be like this

$("#test").children()

What is the difference between ( for... in ) and ( for... of ) statements?

I found the following explanation from https://javascript.info/array very helpful:

One of the oldest ways to cycle array items is the for loop over indexes:

let arr = ["Apple", "Orange", "Pear"];

for (let i = 0; i < arr.length; i++) { alert( arr[i] ); } But for arrays there is another form of loop, for..of:

let fruits = ["Apple", "Orange", "Plum"];

// iterates over array elements for (let fruit of fruits) { alert( fruit ); } The for..of doesn’t give access to the number of the current element, just its value, but in most cases that’s enough. And it’s shorter.

Technically, because arrays are objects, it is also possible to use for..in:

let arr = ["Apple", "Orange", "Pear"];

for (let key in arr) { alert( arr[key] ); // Apple, Orange, Pear } But that’s actually a bad idea. There are potential problems with it:

The loop for..in iterates over all properties, not only the numeric ones.

There are so-called “array-like” objects in the browser and in other environments, that look like arrays. That is, they have length and indexes properties, but they may also have other non-numeric properties and methods, which we usually don’t need. The for..in loop will list them though. So if we need to work with array-like objects, then these “extra” properties can become a problem.

The for..in loop is optimized for generic objects, not arrays, and thus is 10-100 times slower. Of course, it’s still very fast. The speedup may only matter in bottlenecks. But still we should be aware of the difference.

Generally, we shouldn’t use for..in for arrays.

Reshape an array in NumPy

There are two possible result rearrangements (following example by @eumiro). Einops package provides a powerful notation to describe such operations non-ambigously

>> a = np.arange(18).reshape(9,2)

# this version corresponds to eumiro's answer
>> einops.rearrange(a, '(x y) z -> z y x', x=3)

array([[[ 0,  6, 12],
        [ 2,  8, 14],
        [ 4, 10, 16]],

       [[ 1,  7, 13],
        [ 3,  9, 15],
        [ 5, 11, 17]]])

# this has the same shape, but order of elements is different (note that each paer was trasnposed)
>> einops.rearrange(a, '(x y) z -> z x y', x=3)

array([[[ 0,  2,  4],
        [ 6,  8, 10],
        [12, 14, 16]],

       [[ 1,  3,  5],
        [ 7,  9, 11],
        [13, 15, 17]]])

How do I position a div relative to the mouse pointer using jQuery?

There are plenty of examples of using JQuery to retrieve the mouse coordinates, but none fixed my issue.

The Body of my webpage is 1000 pixels wide, and I centre it in the middle of the user's browser window.

body {
    position:absolute;
    width:1000px;
    left: 50%;
    margin-left:-500px;
}

Now, in my JavaScript code, when the user right-clicked on my page, I wanted a div to appear at the mouse position.

Problem is, just using e.pageX value wasn't quite right. It'd work fine if I resized my browser window to be about 1000 pixels wide. Then, the pop div would appear at the correct position.

But if increased the size of my browser window to, say, 1200 pixels wide, then the div would appear about 100 pixels to the right of where the user had clicked.

The solution is to combine e.pageX with the bounding rectangle of the body element. When the user changes the size of their browser window, the "left" value of body element changes, and we need to take this into account:

// Temporary variables to hold the mouse x and y position
var tempX = 0;
var tempY = 0;

jQuery(document).ready(function () {
    $(document).mousemove(function (e) {
        var bodyOffsets = document.body.getBoundingClientRect();
        tempX = e.pageX - bodyOffsets.left;
        tempY = e.pageY;
    });
}) 

Phew. That took me a while to fix ! I hope this is useful to other developers !

Datatable date sorting dd/mm/yyyy issue

Use the data-order attribute on the <td> tag like so (Ruby Example):

    <td data order='<%=rentroll.decorate.date%>'><%=rentroll.decorate.date%></td>

Your decorator function here would be:

    def date
    object.date&.strftime("%d/%m/%Y")
    end

JavaScript and getElementById for multiple elements with the same ID

Class is more than enough for refering anything you want, because it can have a naming with one of more words:

<input class="special use">
<input class="normal use">
<input class="no use">
<input class="special treatment">
<input class="normal treatment">
<input class="no special treatment">
<input class="use treatment">

that's the way you can apply different styles with css (and Bootstrap is the best example of it) and of course you may call

document.getElementsByClassName("special");
document.getElementsByClassName("use");
document.getElementsByClassName("treatment");
document.getElementsByClassName("no");
document.getElementsByClassName("normal");

and so on for any grouping you need.

Now, in the very last case you really want to group elements by id. You may use and refer to elements using a numerically similar, but not equal id:

<input id=1>
<input id="+1">
<input id="-1">
<input id="1 ">
<input id=" 1">
<input id="0x1">
<input id="1.">
<input id="1.0">
<input id="01.0">
<input id="001">

That way you can, knowing the numeric id, access and get an element by just adding extra non-invalidating numeric characters and calling a function to get (by parsing and so on) the original index from its legal string identifying value. It is useful for when you:

  • Have several rows with similar elements and want to handle its events coherently. No matter if you delete one or almost all of them. Since numeric reference is still present, you can then reuse them and reassign its deleted format.

  • Run out of class, name and tagname identifiers.

Although you can use spaces and other common signs even when it's a not a requirement strictly validated in browsers, it's not recommended to use them, specially if you are going to send that data in other formats like JSON. You may even handle such things with PHP, but this is a bad practice tending to filthy programming practices.

Best way to get child nodes

The cross browser way to do is to use childNodes to get NodeList, then make an array of all nodes with nodeType ELEMENT_NODE.

/**
 * Return direct children elements.
 *
 * @param {HTMLElement}
 * @return {Array}
 */
function elementChildren (element) {
    var childNodes = element.childNodes,
        children = [],
        i = childNodes.length;

    while (i--) {
        if (childNodes[i].nodeType == 1) {
            children.unshift(childNodes[i]);
        }
    }

    return children;
}

http://jsfiddle.net/s4kxnahu/

This is especially easy if you are using a utility library such as lodash:

/**
 * Return direct children elements.
 *
 * @param {HTMLElement}
 * @return {Array}
 */
function elementChildren (element) {
    return _.where(element.childNodes, {nodeType: 1});
}

Future:

You can use querySelectorAll in combination with :scope pseudo-class (matches the element that is the reference point of the selector):

parentElement.querySelectorAll(':scope > *');

At the time of writing this :scope is supported in Chrome, Firefox and Safari.

How to rename a table column in Oracle 10g

The syntax of the query is as follows:

Alter table <table name> rename column <column name> to <new column name>;

Example:

Alter table employee rename column eName to empName;

To rename a column name without space to a column name with space:

Alter table employee rename column empName to "Emp Name";

To rename a column with space to a column name without space:

Alter table employee rename column "emp name" to empName;

Border color on default input style

If it is an Angular application you can simply do this

input.ng-invalid.ng-touched
{
    border: 1px solid red !important; 
}

How to upgrade all Python packages with pip

I have tried the code of Ramana and I found out on Ubuntu you have to write sudo for each command. Here is my script which works fine on Ubuntu 13.10 (Saucy Salamander):

#!/usr/bin/env python
import pip
from subprocess import call

for dist in pip.get_installed_distributions():
    call("sudo pip install --upgrade " + dist.project_name, shell=True)

SVN repository backup strategies

For hosted repositories you can since svn version 1.7 use svnrdump, which is analogous to svnadmin dump for local repositories. This article provides a nice walk-through, which essentially boils down to:

svnrdump dump /URL/to/remote/repository > myRepository.dump

After you have downloaded the dump file you can import it locally

svnadmin load /path/to/local/repository < myRepository.dump

or upload it to the host of your choice.

How to Calculate Jump Target Address and Branch Target Address?

For small functions like this you could just count by hand how many hops it is to the target, from the instruction under the branch instruction. If it branches backwards make that hop number negative. if that number doesn't require all 16 bits, then for every number to the left of the most significant of your hop number, make them 1's, if the hop number is positive make them all 0's Since most branches are close to they're targets, this saves you a lot of extra arithmetic for most cases.

  • chris

How can I recover a lost commit in Git?

Sadly git is so unrelable :( I just lost 2 days of work :(

It's best to manual backup anything before doing commit. I just did "git commit" and git just destroy all my changes without saying anything.

I learned my lesson - next time backup first and only then commit. Never trust git for anything.

In nodeJs is there a way to loop through an array without using array size?

You can use Array.forEach

_x000D_
_x000D_
var myArray = ['1','2',3,4]_x000D_
_x000D_
myArray.forEach(function(value){_x000D_
  console.log(value);_x000D_
});
_x000D_
_x000D_
_x000D_

How can a query multiply 2 cell for each row MySQL?

Use this:

SELECT 
    Pieces, Price, 
    Pieces * Price as 'Total' 
FROM myTable

What are the differences between struct and class in C++?

It's worth remembering C++'s origins in, and compatibility with, C.

C has structs, it has no concept of encapsulation, so everything is public.

Being public by default is generally considered a bad idea when taking an object-oriented approach, so in making a form of C that is natively conducive to OOP (you can do OO in C, but it won't help you) which was the idea in C++ (originally "C With Classes"), it makes sense to make members private by default.

On the other hand, if Stroustrup had changed the semantics of struct so that its members were private by default, it would have broken compatibility (it is no longer as often true as the standards diverged, but all valid C programs were also valid C++ programs, which had a big effect on giving C++ a foothold).

So a new keyword, class was introduced to be exactly like a struct, but private by default.

If C++ had come from scratch, with no history, then it would probably have only one such keyword. It also probably wouldn't have made the impact it made.

In general, people will tend to use struct when they are doing something like how structs are used in C; public members, no constructor (as long as it isn't in a union, you can have constructors in structs, just like with classes, but people tend not to), no virtual methods, etc. Since languages are as much to communicate with people reading the code as to instruct machines (or else we'd stick with assembly and raw VM opcodes) it's a good idea to stick with that.

How to get the children of the $(this) selector?

If your DIV tag is immediately followed by the IMG tag, you can also use:

$(this).next();

How to change color of SVG image using CSS (jQuery SVG image replacement)?

Since SVG is basically code, you need just contents. I used PHP to obtain content, but you can use whatever you want.

<?php
$content    = file_get_contents($pathToSVG);
?>

Then, I've printed content "as is" inside a div container

<div class="fill-class"><?php echo $content;?></div>

To finnaly set rule to container's SVG childs on CSS

.fill-class > svg { 
    fill: orange;
}

I got this results with a material icon SVG:

  1. Mozilla Firefox 59.0.2 (64-bit) Linux

enter image description here

  1. Google Chrome66.0.3359.181 (Build oficial) (64 bits) Linux

enter image description here

  1. Opera 53.0.2907.37 Linux

enter image description here

Hosting a Maven repository on github

The best solution I've been able to find consists of these steps:

  1. Create a branch called mvn-repo to host your maven artifacts.
  2. Use the github site-maven-plugin to push your artifacts to github.
  3. Configure maven to use your remote mvn-repo as a maven repository.

There are several benefits to using this approach:

  • Maven artifacts are kept separate from your source in a separate branch called mvn-repo, much like github pages are kept in a separate branch called gh-pages (if you use github pages)
  • Unlike some other proposed solutions, it doesn't conflict with your gh-pages if you're using them.
  • Ties in naturally with the deploy target so there are no new maven commands to learn. Just use mvn deploy as you normally would

The typical way you deploy artifacts to a remote maven repo is to use mvn deploy, so let's patch into that mechanism for this solution.

First, tell maven to deploy artifacts to a temporary staging location inside your target directory. Add this to your pom.xml:

<distributionManagement>
    <repository>
        <id>internal.repo</id>
        <name>Temporary Staging Repository</name>
        <url>file://${project.build.directory}/mvn-repo</url>
    </repository>
</distributionManagement>

<plugins>
    <plugin>
        <artifactId>maven-deploy-plugin</artifactId>
        <version>2.8.1</version>
        <configuration>
            <altDeploymentRepository>internal.repo::default::file://${project.build.directory}/mvn-repo</altDeploymentRepository>
        </configuration>
    </plugin>
</plugins>

Now try running mvn clean deploy. You'll see that it deployed your maven repository to target/mvn-repo. The next step is to get it to upload that directory to GitHub.

Add your authentication information to ~/.m2/settings.xml so that the github site-maven-plugin can push to GitHub:

<!-- NOTE: MAKE SURE THAT settings.xml IS NOT WORLD READABLE! -->
<settings>
  <servers>
    <server>
      <id>github</id>
      <username>YOUR-USERNAME</username>
      <password>YOUR-PASSWORD</password>
    </server>
  </servers>
</settings>

(As noted, please make sure to chmod 700 settings.xml to ensure no one can read your password in the file. If someone knows how to make site-maven-plugin prompt for a password instead of requiring it in a config file, let me know.)

Then tell the GitHub site-maven-plugin about the new server you just configured by adding the following to your pom:

<properties>
    <!-- github server corresponds to entry in ~/.m2/settings.xml -->
    <github.global.server>github</github.global.server>
</properties>

Finally, configure the site-maven-plugin to upload from your temporary staging repo to your mvn-repo branch on Github:

<build>
    <plugins>
        <plugin>
            <groupId>com.github.github</groupId>
            <artifactId>site-maven-plugin</artifactId>
            <version>0.11</version>
            <configuration>
                <message>Maven artifacts for ${project.version}</message>  <!-- git commit message -->
                <noJekyll>true</noJekyll>                                  <!-- disable webpage processing -->
                <outputDirectory>${project.build.directory}/mvn-repo</outputDirectory> <!-- matches distribution management repository url above -->
                <branch>refs/heads/mvn-repo</branch>                       <!-- remote branch name -->
                <includes><include>**/*</include></includes>
                <repositoryName>YOUR-REPOSITORY-NAME</repositoryName>      <!-- github repo name -->
                <repositoryOwner>YOUR-GITHUB-USERNAME</repositoryOwner>    <!-- github username  -->
            </configuration>
            <executions>
              <!-- run site-maven-plugin's 'site' target as part of the build's normal 'deploy' phase -->
              <execution>
                <goals>
                  <goal>site</goal>
                </goals>
                <phase>deploy</phase>
              </execution>
            </executions>
        </plugin>
    </plugins>
</build>

The mvn-repo branch does not need to exist, it will be created for you.

Now run mvn clean deploy again. You should see maven-deploy-plugin "upload" the files to your local staging repository in the target directory, then site-maven-plugin committing those files and pushing them to the server.

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building DaoCore 1.3-SNAPSHOT
[INFO] ------------------------------------------------------------------------
...
[INFO] --- maven-deploy-plugin:2.5:deploy (default-deploy) @ greendao ---
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/greendao-1.3-20121223.182256-3.jar (77 KB at 2936.9 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/greendao-1.3-20121223.182256-3.pom (3 KB at 1402.3 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/maven-metadata.xml (768 B at 150.0 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/maven-metadata.xml (282 B at 91.8 KB/sec)
[INFO] 
[INFO] --- site-maven-plugin:0.7:site (default) @ greendao ---
[INFO] Creating 24 blobs
[INFO] Creating tree with 25 blob entries
[INFO] Creating commit with SHA-1: 0b8444e487a8acf9caabe7ec18a4e9cff4964809
[INFO] Updating reference refs/heads/mvn-repo from ab7afb9a228bf33d9e04db39d178f96a7a225593 to 0b8444e487a8acf9caabe7ec18a4e9cff4964809
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 8.595s
[INFO] Finished at: Sun Dec 23 11:23:03 MST 2012
[INFO] Final Memory: 9M/81M
[INFO] ------------------------------------------------------------------------

Visit github.com in your browser, select the mvn-repo branch, and verify that all your binaries are now there.

enter image description here

Congratulations!

You can now deploy your maven artifacts to a poor man's public repo simply by running mvn clean deploy.

There's one more step you'll want to take, which is to configure any poms that depend on your pom to know where your repository is. Add the following snippet to any project's pom that depends on your project:

<repositories>
    <repository>
        <id>YOUR-PROJECT-NAME-mvn-repo</id>
        <url>https://github.com/YOUR-USERNAME/YOUR-PROJECT-NAME/raw/mvn-repo/</url>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
        </snapshots>
    </repository>
</repositories>

Now any project that requires your jar files will automatically download them from your github maven repository.

Edit: to avoid the problem mentioned in the comments ('Error creating commit: Invalid request. For 'properties/name', nil is not a string.'), make sure you state a name in your profile on github.

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

You have two records in your json file, and json.loads() is not able to decode more than one. You need to do it record by record.

See Python json.loads shows ValueError: Extra data

OR you need to reformat your json to contain an array:

{
    "foo" : [
       {"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
       {"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
    ]
}

would be acceptable again. But there cannot be several top level objects.