Programs & Examples On #Control adapter

Virtualbox "port forward" from Guest to Host

Network communication Host -> Guest

Connect to the Guest and find out the ip address:

ifconfig 

example of result (ip address is 10.0.2.15):

eth0      Link encap:Ethernet  HWaddr 08:00:27:AE:36:99
          inet addr:10.0.2.15  Bcast:10.0.2.255  Mask:255.255.255.0

Go to Vbox instance window -> Menu -> Network adapters:

  • adapter should be NAT
  • click on "port forwarding"
  • insert new record (+ icon)
    • for host ip enter 127.0.0.1, and for guest ip address you got from prev. step (in my case it is 10.0.2.15)
    • in your case port is 8000 - put it on both, but you can change host port if you prefer

Go to host system and try it in browser:

http://127.0.0.1:8000

or your network ip address (find out on the host machine by running: ipconfig).

Network communication Guest -> Host

In this case port forwarding is not needed, the communication goes over the LAN back to the host.

On the host machine - find out your netw ip address:

ipconfig

example of result:

IP Address. . . . . . . . . . . . : 192.168.5.1

On the guest machine you can communicate directly with the host, e.g. check it with ping:

# ping 192.168.5.1
PING 192.168.5.1 (192.168.5.1) 56(84) bytes of data.
64 bytes from 192.168.5.1: icmp_seq=1 ttl=128 time=2.30 ms
...

Firewall issues?

@Stranger suggested that in some cases it would be necessary to open used port (8000 or whichever is used) in firewall like this (example for ufw firewall, I haven't tested):

sudo ufw allow 8000 

The remote end hung up unexpectedly while git cloning

If you are using https and you are getting the error.

I used https instead of http and it solved my problem

git config --global https.postBuffer 524288000

Angular 4 default radio button checked by default

You can use [(ngModel)], but you'll need to update your value to [value] otherwise the value is evaluating as a string. It would look like this:

<label>This rule is true if:</label>
<label class="form-check-inline">
    <input class="form-check-input" type="radio" name="mode" [value]="true" [(ngModel)]="rule.mode">
</label>
<label class="form-check-inline">
    <input class="form-check-input" type="radio" name="mode" [value]="false" [(ngModel)]="rule.mode">
</label>

If rule.mode is true, then that radio is selected. If it's false, then the other.

The difference really comes down to the value. value="true" really evaluates to the string 'true', whereas [value]="true" evaluates to the boolean true.

Switch firefox to use a different DNS than what is in the windows.host file

What about having different names for your dev and prod servers? That should avoid any confusions and you'd not have to edit the hosts file every time.

Increasing the maximum post size

We can Increasing the maximum limit using .htaccess file.

php_value session.gc_maxlifetime 10800
php_value max_input_time         10800
php_value max_execution_time     10800
php_value upload_max_filesize    110M
php_value post_max_size          120M

If sometimes other way are not working, this way is working perfect.

Python, creating objects

Create a class and give it an __init__ method:

class Student:
    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major

    def is_old(self):
        return self.age > 100

Now, you can initialize an instance of the Student class:

>>> s = Student('John', 88, None)
>>> s.name
    'John'
>>> s.age
    88

Although I'm not sure why you need a make_student student function if it does the same thing as Student.__init__.

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

A Brief and Maybe Incorrect History of Java Versions

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

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

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

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

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

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

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

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

Notes

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

  • SO seems to have trouble rendering nested lists.

References

Epilogue

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

How to find if a native DLL file is compiled as x64 or x86?

Apparently you can find it in the header of the portable executable. The corflags.exe utility is able to show you whether or not it targets x64. Hopefully this helps you find more information about it.

Get all unique values in a JavaScript array (remove duplicates)

I use this extrem simple one and I am pretty sure it is compatible to every browser but it is obsolete in modern browsers:

_x000D_
_x000D_
var keys = [1,3,3,3,3,2,2,1,4,4,'aha','aha'];
for (var uniqueIdx = 0; uniqueIdx < keys.length; uniqueIdx++) {
  for (var duplicateCandidateIdx=0; duplicateCandidateIdx < keys.length; duplicateCandidateIdx++) {
    if(uniqueIdx != duplicateCandidateIdx) {
      var candidateIsFullDuplicate = keys[uniqueIdx] == keys[duplicateCandidateIdx];
      if (candidateIsFullDuplicate){
        keys.splice(duplicateCandidateIdx, 1);
      }
    }
  }
}
document.write(keys); // gives: 1,3,2,4,aha
_x000D_
_x000D_
_x000D_

What should my Objective-C singleton look like?

A thorough explanation of the Singleton macro code is on the blog Cocoa With Love

http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html.

What should I use to open a url instead of urlopen in urllib3

In urlip3 there's no .urlopen, instead try this:

import requests
html = requests.get(url)

What is a good regular expression to match a URL?

These are the droids you're looking for. This is taken from validator.js which is the library you should really use to do this. But if you want to roll your own, who am I to stop you? If you want pure regex then you can just take out the length check. I think it's a good idea to test the length of the URL though if you really want to determine compliance with the spec.

 function isURL(str) {
     var urlRegex = '^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$';
     var url = new RegExp(urlRegex, 'i');
     return str.length < 2083 && url.test(str);
}

Reference to non-static member function must be called

You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?

curl_exec() always returns false

This happened to me yesterday and in my case was because I was following a PDF manual to develop some module to communicate with an API and while copying the link directly from the manual, for some odd reason, the hyphen from the copied link was in a different encoding and hence the curl_exec() was always returning false because it was unable to communicate with the server.

It took me a couple hours to finally understand the diference in the characters bellow:

https://www.e-example.com/api
https://www.e-example.com/api

Every time I tried to access the link directly from a browser it converted to something likehttps://www.xn--eexample-0m3d.com/api.

It may seem to you that they are equal but if you check the encoding of the hyphens here you'll see that the first hyphen is a unicode characters U+2010 and the other is a U+002D.

Hope this helps someone.

Convert DataTable to CSV stream

I don't know if this converted from VB to C# ok but if you don't want quotes around your numbers, you might compare the data type as follows..

public string DataTableToCSV(DataTable dt)
{
    StringBuilder sb = new StringBuilder();
    if (dt == null)
        return "";

    try {
        // Create the header row
        for (int i = 0; i <= dt.Columns.Count - 1; i++) {
            // Append column name in quotes
            sb.Append("\"" + dt.Columns[i].ColumnName + "\"");
            // Add carriage return and linefeed if last column, else add comma
            sb.Append(i == dt.Columns.Count - 1 ? "\n" : ",");
        }


        foreach (DataRow row in dt.Rows) {
            for (int i = 0; i <= dt.Columns.Count - 1; i++) {
                // Append value in quotes
                //sb.Append("""" & row.Item(i) & """")

                // OR only quote items that that are equivilant to strings
                sb.Append(object.ReferenceEquals(dt.Columns[i].DataType, typeof(string)) || object.ReferenceEquals(dt.Columns[i].DataType, typeof(char)) ? "\"" + row[i] + "\"" : row[i]);

                // Append CR+LF if last field, else add Comma
                sb.Append(i == dt.Columns.Count - 1 ? "\n" : ",");
            }
        }
        return sb.ToString;
    } catch (Exception ex) {
        // Handle the exception however you want
        return "";
    }

}

How to easily get network path to the file you are working on?

I realise this is a slightly old question, but it was driving me crazy too - and today I've found the solution that I believe the questioner was looking for (i.e. a direct mapping of Excel 2003's Web-->Address to the Excel 2010 Ribbon).

To customise the Ribbon, right-click on it and choose 'Customise the Ribbon'. You can make a new tab/group, or add this to an existing one. Choose to look in "All commands" and then the one you are after is simply called "Address". This puts a box with the full network path in it (that can be selected to copy) into the ribbon, just like Excel 2003.

How to find the Number of CPU Cores via .NET/C#?

There are many answers here already, but some have heavy upvotes and are incorrect.

The .NET Environment.ProcessorCount WILL return incorrect values and can fail critically if your system WMI is configured incorrectly.

If you want a RELIABLE way to count the cores, the only way is Win32 API.

Here is a C++ snippet:

#include <Windows.h>
#include <vector>

int num_physical_cores()
{
    static int num_cores = []
    {
        DWORD bytes = 0;
        GetLogicalProcessorInformation(nullptr, &bytes);
        std::vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> coreInfo(bytes / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION));
        GetLogicalProcessorInformation(coreInfo.data(), &bytes);

        int cores = 0;
        for (auto& info : coreInfo)
        {
            if (info.Relationship == RelationProcessorCore)
                ++cores;
        }
        return cores > 0 ? cores : 1;
    }();
    return num_cores;
}

And since this is a .NET C# Question, here's the ported version:

[StructLayout(LayoutKind.Sequential)]
struct CACHE_DESCRIPTOR
{
    public byte Level;
    public byte Associativity;
    public ushort LineSize;
    public uint Size;
    public uint Type;
}

[StructLayout(LayoutKind.Explicit)]
struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION_UNION
{
    [FieldOffset(0)] public byte ProcessorCore;
    [FieldOffset(0)] public uint NumaNode;
    [FieldOffset(0)] public CACHE_DESCRIPTOR Cache;
    [FieldOffset(0)] private UInt64 Reserved1;
    [FieldOffset(8)] private UInt64 Reserved2;
}

public enum LOGICAL_PROCESSOR_RELATIONSHIP
{
    RelationProcessorCore,
    RelationNumaNode,
    RelationCache,
    RelationProcessorPackage,
    RelationGroup,
    RelationAll = 0xffff
}

struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION
{
    public UIntPtr ProcessorMask;
    public LOGICAL_PROCESSOR_RELATIONSHIP Relationship;
    public SYSTEM_LOGICAL_PROCESSOR_INFORMATION_UNION ProcessorInformation;
}

[DllImport("kernel32.dll")]
static extern unsafe bool GetLogicalProcessorInformation(SYSTEM_LOGICAL_PROCESSOR_INFORMATION* buffer, out int bufferSize);

static unsafe int GetProcessorCoreCount()
{
    GetLogicalProcessorInformation(null, out int bufferSize);
    int numEntries = bufferSize / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
    var coreInfo = new SYSTEM_LOGICAL_PROCESSOR_INFORMATION[numEntries];

    fixed (SYSTEM_LOGICAL_PROCESSOR_INFORMATION* pCoreInfo = coreInfo)
    {
        GetLogicalProcessorInformation(pCoreInfo, out bufferSize);
        int cores = 0;
        for (int i = 0; i < numEntries; ++i)
        {
            ref SYSTEM_LOGICAL_PROCESSOR_INFORMATION info = ref pCoreInfo[i];
            if (info.Relationship == LOGICAL_PROCESSOR_RELATIONSHIP.RelationProcessorCore)
                ++cores;
        }
        return cores > 0 ? cores : 1;
    }
}

public static readonly int NumPhysicalCores = GetProcessorCoreCount();

CURRENT_DATE/CURDATE() not working as default DATE value

I came to this page with the same question in mind, but it worked for me!, Just thought to update here , may be helpful for someone later!!

MariaDB [niffdb]> desc invoice;
+---------+--------+------+-----+---------+----------------+
| Field   | Type   | Null | Key | Default | Extra          |
+---------+--------+------+-----+---------+----------------+
| inv_id  | int(4) | NO   | PRI | NULL    | auto_increment |
| cust_id | int(4) | NO   | MUL | NULL    |                |
| inv_dt  | date   | NO   |     | NULL    |                |
| smen_id | int(4) | NO   | MUL | NULL    |                |
+---------+--------+------+-----+---------+----------------+
4 rows in set (0.003 sec)

MariaDB [niffdb]> ALTER TABLE invoice MODIFY inv_dt DATE NOT NULL DEFAULT (CURRENT_DATE);
Query OK, 0 rows affected (0.003 sec)
Records: 0  Duplicates: 0  Warnings: 0

MariaDB [niffdb]> desc invoice;
+---------+--------+------+-----+-----------+----------------+
| Field   | Type   | Null | Key | Default   | Extra          |
+---------+--------+------+-----+-----------+----------------+
| inv_id  | int(4) | NO   | PRI | NULL      | auto_increment |
| cust_id | int(4) | NO   | MUL | NULL      |                |
| inv_dt  | date   | NO   |     | curdate() |                |
| smen_id | int(4) | NO   | MUL | NULL      |                |
+---------+--------+------+-----+-----------+----------------+
4 rows in set (0.002 sec)

MariaDB [niffdb]> SELECT VERSION();
+---------------------------+
| VERSION()                 |
+---------------------------+
| 10.3.18-MariaDB-0+deb10u1 |
+---------------------------+
1 row in set (0.010 sec)

MariaDB [niffdb]>

Add colorbar to existing axis

This technique is usually used for multiple axis in a figure. In this context it is often required to have a colorbar that corresponds in size with the result from imshow. This can be achieved easily with the axes grid tool kit:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

data = np.arange(100, 0, -1).reshape(10, 10)

fig, ax = plt.subplots()
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)

im = ax.imshow(data, cmap='bone')

fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()

Image with proper colorbar in size

How to set default values in Go structs

One possible idea is to write separate constructor function

//Something is the structure we work with
type Something struct {
     Text string 
     DefaultText string 
} 
// NewSomething create new instance of Something
func NewSomething(text string) Something {
   something := Something{}
   something.Text = text
   something.DefaultText = "default text"
   return something
}

How can I create an observable with a delay

In RxJS 5+ you can do it like this

import { Observable } from "rxjs/Observable";
import { of } from "rxjs/observable/of";
import { delay } from "rxjs/operators";

fakeObservable = of('dummy').pipe(delay(5000));

In RxJS 6+

import { of } from "rxjs";
import { delay } from "rxjs/operators";

fakeObservable = of('dummy').pipe(delay(5000));

If you want to delay each emitted value try

from([1, 2, 3]).pipe(concatMap(item => of(item).pipe(delay(1000))));

How can I check if some text exist or not in the page using Selenium?

This will help you to check whether required text is there in webpage or not.

driver.getPageSource().contains("Text which you looking for");

Excel Date Conversion from yyyymmdd to mm/dd/yyyy

Do you have ROWS of data (horizontal) as you stated or COLUMNS (vertical)?

If it's the latter you can use "Text to columns" functionality to convert a whole column "in situ" - to do that:

Select column > Data > Text to columns > Next > Next > Choose "Date" under "column data format" and "YMD" from dropdown > Finish

....otherwise you can convert with a formula by using

=TEXT(A1,"0000-00-00")+0

and format in required date format

remove / reset inherited css from an element

One simple approach would be to use the !important modifier in css, but this can be overridden in the same way from users.

Maybe a solution can be achieved with jquery by traversing the entire DOM to find your (re)defined classes and removing / forcing css styles.

String Comparison in Java

Below Algo "compare two strings lexicographically"

  1. Input two strings string 1 and string 2.

  2. for (int i = 0; i < str1.length() && i < str2.length(); i ++)

    (Loop through each character of both strings comparing them until one of the string terminates):

    a. If unicode value of both the characters is same then continue;

    b. If unicode value of character of string 1 and unicode value of string 2 is different then return (str1[i]-str2[i])

  3. if length of string 1 is less than string2

    return str2[str1.length()]

    else

    return str1[str2.length()]

    // This method compares two strings lexicographically

    public static int compareCustom(String s1, String s2) {
        for (int i = 0; i < s1.length() && i< s2.length(); i++) {
            if(s1.charAt(i) == s2.charAt(i)){
                //System.out.println("Equal");
                continue;
            }
            else{
                return s1.charAt(i) - s2.charAt(i);
            }   
        }
        if(s1.length()<s2.length()){
            return s2.length() - s1.length();
        }
        else if(s1.length()>s2.length()){
            return s1.length()-s2.length();
        }
        else{
            return 0;
        }
    }
    

if two String are equal it will return 0 otherwise return Negative or positive value

Source : - Source

SQL Not Like Statement not working

Just come across this, the answer is simple, use ISNULL. SQL won't return rows if the field you are testing has no value (in some of the records) when doing a text comparison search, eg:

WHERE wpp.comment NOT LIKE '%CORE%'

So, you have temporarily substitute a value in the null (empty) records by using the ISNULL command, eg

WHERE (ISNULL(wpp.comment,'')) NOT LIKE '%CORE%'

This will then show all your records that have nulls and omit any that have your matching criteria. If you wanted, you could put something in the commas to help you remember, eg

WHERE (ISNULL(wpp.comment,'some_records_have_no_value')) NOT LIKE '%CORE%'

Dynamic array in C#

Use the array list which is actually implement array. It takes initially array of size 4 and when it gets full, a new array is created with its double size and the data of first array get copied into second array, now the new item is inserted into new array. Also the name of second array creates an alias of first so that it can be accessed by the same name as previous and the first array gets disposed

Fragment transaction animation: slide in and slide out

Have the same problem with white screen during transition from one fragment to another. Have navigation and animations set in action in navigation.xml.

enter image description here

Background in all fragments the same but white blank screen. So i set navOptions in fragment during executing transition

          //Transition options
        val options = navOptions {
            anim {
                enter = R.anim.slide_in_right
                exit = R.anim.slide_out_left
                popEnter = R.anim.slide_in_left
                popExit = R.anim.slide_out_right
            }
        }

.......................

  this.findNavController().navigate(SampleFragmentDirections.actionSampleFragmentToChartFragment(it),
                    options)

It worked for me. No white screen between transistion. Magic )

How can I run a directive after the dom has finished rendering?

Here is how I do it:

app.directive('example', function() {

    return function(scope, element, attrs) {
        angular.element(document).ready(function() {
                //MANIPULATE THE DOM
        });
    };

});

how to make a specific text on TextView BOLD

You can use this code to set part of your text to bold. For whatever is in between the bold html tags, it will make it bold.

String myText = "make this <b>bold</b> and <b>this</b> too";
textView.setText(makeSpannable(myText, "<b>(.+?)</b>", "<b>", "</b>"));

public SpannableStringBuilder makeSpannable(String text, String regex, String startTag, String endTag) {

            StringBuffer sb = new StringBuffer();
            SpannableStringBuilder spannable = new SpannableStringBuilder();

            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(text);
            while (matcher.find()) {
                sb.setLength(0);
                String group = matcher.group();
                String spanText = group.substring(startTag.length(), group.length() - endTag.length());
                matcher.appendReplacement(sb, spanText);

                spannable.append(sb.toString());
                int start = spannable.length() - spanText.length();

                spannable.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD), start, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            sb.setLength(0);
            matcher.appendTail(sb);
            spannable.append(sb.toString());
            return spannable;
        }

How to open URL in Microsoft Edge from the command line?

Looks like things have changed and the previous solution doesn't work anymore.

However, here is the working command to launch CNN.com on Microsoft Edge:

microsoft-edge:http://www.cnn.com

Python string.replace regular expression

As a summary

import sys
import re

f = sys.argv[1]
find = sys.argv[2]
replace = sys.argv[3]
with open (f, "r") as myfile:
     s=myfile.read()
ret = re.sub(find,replace, s)   # <<< This is where the magic happens
print ret

Jackson JSON: get node name from json-tree

Clarification Here:

While this will work:

 JsonNode rootNode = objectMapper.readTree(file);
 Iterator<Map.Entry<String, JsonNode>> fields = rootNode.fields();
 while (fields.hasNext()) {
    Map.Entry<String, JsonNode> entry = fields.next();
    log.info(entry.getKey() + ":" + entry.getValue())
 }

This will not:

JsonNode rootNode = objectMapper.readTree(file);

while (rootNode.fields().hasNext()) {
    Map.Entry<String, JsonNode> entry = rootNode.fields().next();
    log.info(entry.getKey() + ":" + entry.getValue())
}

So be careful to declare the Iterator as a variable and use that.

Be sure to use the fasterxml library rather than codehaus.

How to generate a unique hash code for string input in android...?

It depends on what you mean:

  • As mentioned String.hashCode() gives you a 32 bit hash code.

  • If you want (say) a 64-bit hashcode you can easily implement it yourself.

  • If you want a cryptographic hash of a String, the Java crypto libraries include implementations of MD5, SHA-1 and so on. You'll typically need to turn the String into a byte array, and then feed that to the hash generator / digest generator. For example, see @Bryan Kemp's answer.

  • If you want a guaranteed unique hash code, you are out of luck. Hashes and hash codes are non-unique.

A Java String of length N has 65536 ^ N possible states, and requires an integer with 16 * N bits to represent all possible values. If you write a hash function that produces integer with a smaller range (e.g. less than 16 * N bits), you will eventually find cases where more than one String hashes to the same integer; i.e. the hash codes cannot be unique. This is called the Pigeonhole Principle, and there is a straight forward mathematical proof. (You can't fight math and win!)

But if "probably unique" with a very small chance of non-uniqueness is acceptable, then crypto hashes are a good answer. The math will tell you how big (i.e. how many bits) the hash has to be to achieve a given (low enough) probability of non-uniqueness.

Reset select value to default

$('#my_select').get(0).selectedIndex = 1;

But, In my opinion, the better way is using HTML only (with <input type="reset" />):

<form>
    <select id="my_select">
        <option value="a">a</option>
        <option value="b" selected="selected">b</option>
        <option value="c">c</option>
    </select>
    <input type="reset" value="reset" />
</form>

PostgreSQL error: Fatal: role "username" does not exist

Use the operating system user postgres to create your database - as long as you haven't set up a database role with the necessary privileges that corresponds to your operating system user of the same name (h9uest in your case):

sudo -u postgres -i

As recommended here or here.

Then try again. Type exit when done with operating as system user postgres.

Or execute the single command createuser as postgres with sudo, like demonstrated by drees in another answer.

The point is to use the operating system user matching the database role of the same name to be granted access via ident authentication. postgres is the default operating system user to have initialized the database cluster. The manual:

In order to bootstrap the database system, a freshly initialized system always contains one predefined role. This role is always a “superuser”, and by default (unless altered when running initdb) it will have the same name as the operating system user that initialized the database cluster. Customarily, this role will be named postgres. In order to create more roles you first have to connect as this initial role.

I have heard of odd setups with non-standard user names or where the operating system user does not exist. You'd need to adapt your strategy there.

Read about database roles and client authentication in the manual.

How to display Base64 images in HTML?

you can put your data directly in a url statment like

src = 'url(imageData)' ;

and to get the image data u can use the php function

$imageContent = file_get_contents("imageDir/".$imgName);

$imageData = base64_encode($imageContent);

so you can copy paste the value of imageData and paste it directly to your url and assign it to the src attribute of your image

Accessing localhost (xampp) from another computer over LAN network - how to?

If you are connected to Wi-Fi network, then it is much simpler. Just find the Ip in which you have connected to the Wi-Fi. Eg:

your-ip is "10.10.55.67".

Then start the xampp server in your machine.

Then in anyother computer connected to the same Wi-Fi n/w, type

http://your-ip

Eg:http://10.10.55.67

android TextView: setting the background color dynamically doesn't work

here is in little detail,

if you are in activity use this

textview.setBackground(ContextCompat.getColor(this,R.color.yourcolor));

if you are in fragment use below code

textview.setBackground(ContextCompat.getColor(getActivity(),R.color.yourcolor));

if you are in recyclerview adapter use below code

textview.setBackground(ContextCompat.getColor(context,R.color.yourcolor));

// use holder.textview if you are in onBindviewholder
//here context is passed from fragment

How to convert a string to integer in C?

//I think this way we could go :
int my_atoi(const char* snum)
{
 int nInt(0);
 int index(0);
 while(snum[index])
 {
    if(!nInt)
        nInt= ( (int) snum[index]) - 48;
    else
    {
        nInt = (nInt *= 10) + ((int) snum[index] - 48);
    }
    index++;
 }
 return(nInt);
}

int main()
{
    printf("Returned number is: %d\n", my_atoi("676987"));
    return 0;
}

Header div stays at top, vertical scrolling div below with scrollbar only attached to that div

Here is a demo. Use position:fixed; top:0; left:0; so the header always stay on top.

?#header {
    background:red;
    height:50px;
    width:100%;
    position:fixed;
    top:0;
    left:0;    
}.scroller {
    height:300px; 
    overflow:scroll;    
}

Is there a way to ignore a single FindBugs warning?

The FindBugs initial approach involves XML configuration files aka filters. This is really less convenient than the PMD solution but FindBugs works on bytecode, not on the source code, so comments are obviously not an option. Example:

<Match>
   <Class name="com.mycompany.Foo" />
   <Method name="bar" />
   <Bug pattern="DLS_DEAD_STORE_OF_CLASS_LITERAL" />
</Match>

However, to solve this issue, FindBugs later introduced another solution based on annotations (see SuppressFBWarnings) that you can use at the class or at the method level (more convenient than XML in my opinion). Example (maybe not the best one but, well, it's just an example):

@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
    value="HE_EQUALS_USE_HASHCODE", 
    justification="I know what I'm doing")

Note that since FindBugs 3.0.0 SuppressWarnings has been deprecated in favor of @SuppressFBWarnings because of the name clash with Java's SuppressWarnings.

Alternative to deprecated getCellType

You can do this:

private String cellToString(HSSFCell cell) {
    CellType type;
    Object result;
    type = cell.getCellType();

    switch (type) {
        case NUMERIC :  //numeric value in excel
            result = cell.getNumericCellValue();
            break;
        case STRING : //String Value in Excel
            result = cell.getStringCellValue();
            break;
        default :
            throw new RuntimeException("There is no support for this type of value in Apche POI");
    }
    return result.toString();
}

How to fire AJAX request Periodically?

Yes, you could use either the JavaScript setTimeout() method or setInterval() method to invoke the code that you would like to run. Here's how you might do it with setTimeout:

function executeQuery() {
  $.ajax({
    url: 'url/path/here',
    success: function(data) {
      // do something with the return value here if you like
    }
  });
  setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}

$(document).ready(function() {
  // run the first time; all subsequent calls will take care of themselves
  setTimeout(executeQuery, 5000);
});

How do I empty an input value with jQuery?

Usual way to empty textbox using jquery is:

$('#txtInput').val('');

If above code is not working than please check that you are able to get the input element.

console.log($('#txtInput')); // should return element in the console.

If still facing the same problem, please post your code.

copying all contents of folder to another folder using batch file?

FYI...if you use TortoiseSVN and you want to create a simple batch file to xcopy (or directory mirror) entire repositories into a "safe" location on a periodic basis, then this is the specific code that you might want to use. It copies over the hidden directories/files, maintains read-only attributes, and all subdirectories and best of all, doesn't prompt for input. Just make sure that you assign folder1 (safe repo) and folder2 (usable repo) correctly.

@echo off
echo "Setting variables..."
set folder1="Z:\Path\To\Backup\Repo\Directory"
set folder2="\\Path\To\Usable\Repo\Directory"
echo "Removing sandbox version..."
IF EXIST %folder1% (
    rmdir %folder1% /s /q
)
echo "Copying official repository into backup location..."
xcopy /e /i /v /h /k %folder2% %folder1%

And, that's it folks!

Add to your scheduled tasks and never look back.

function to return a string in java

In Java, a String is a reference to heap-allocated storage. Returning "ans" only returns the reference so there is no need for stack-allocated storage. In fact, there is no way in Java to allocate objects in stack storage.

I would change to this, though. You don't need "ans" at all.

return String.format("%d:%d", mins, secs);

How to check programmatically if an application is installed or not in Android?

You can do it using Kotlin extensions :

fun Context.getInstalledPackages(): List<String> {
    val packagesList = mutableListOf<String>()
    packageManager.getInstalledPackages(0).forEach {
        if ( it.applicationInfo.sourceDir.startsWith("/data/app/") && it.versionName != null)
            packagesList.add(it.packageName)
    }
    return packagesList
}

fun Context.isInDevice(packageName: String): Boolean {
    return getInstalledPackages().contains(packageName)
}

Return JsonResult from web api without its properties

When using WebAPI, you should just return the Object rather than specifically returning Json, as the API will either return JSON or XML depending on the request.

I am not sure why your WebAPI is returning an ActionResult, but I would change the code to something like;

public IEnumerable<ListItems> GetAllNotificationSettings()
{
    var result = new List<ListItems>();
    // Filling the list with data here...

    // Then I return the list
    return result;
}

This will result in JSON if you are calling it from some AJAX code.

P.S WebAPI is supposed to be RESTful, so your Controller should be called ListItemController and your Method should just be called Get. But that is for another day.

What is a classpath and how do I set it?

CLASSPATH is an environment variable (i.e., global variables of the operating system available to all the processes) needed for the Java compiler and runtime to locate the Java packages used in a Java program. (Why not call PACKAGEPATH?) This is similar to another environment variable PATH, which is used by the CMD shell to find the executable programs.

CLASSPATH can be set in one of the following ways:

CLASSPATH can be set permanently in the environment: In Windows, choose control panel ? System ? Advanced ? Environment Variables ? choose "System Variables" (for all the users) or "User Variables" (only the currently login user) ? choose "Edit" (if CLASSPATH already exists) or "New" ? Enter "CLASSPATH" as the variable name ? Enter the required directories and JAR files (separated by semicolons) as the value (e.g., ".;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar"). Take note that you need to include the current working directory (denoted by '.') in the CLASSPATH.

To check the current setting of the CLASSPATH, issue the following command:

> SET CLASSPATH

CLASSPATH can be set temporarily for that particular CMD shell session by issuing the following command:

> SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar

Instead of using the CLASSPATH environment variable, you can also use the command-line option -classpath or -cp of the javac and java commands, for example,

> java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3

How to remove responsive features in Twitter Bootstrap 3?

Look at www.goo.gl/2SIOJj it is a work in progress but it may help you.

I use cookie to define if i want desktop or responsive version. In the footer of the page you can find two spans and in general.js is the script to handle the clicks.

        <div class="col-xs-6" style="text-align:center;"><span class="make_desktop">Desktop</span></div>
        <div class="col-xs-6" style="text-align:center;"><span class="make_responsive">Mobile</span></div>

function setMobDeskCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays === null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value + "; path=/";
    window.location.reload();
}

$(function() {
    $(".make_desktop").click(function() {
        setMobDeskCookie('deskmob', 1, 3650);
    });
    $(".make_responsive").click(function() {
        setMobDeskCookie('deskmob', 0, 3650);
    });
});`enter code here`

i ended up splitting all my custom css into two files i don't use bootstrap navigation but my own so that is majority of my custom styles, so it will not resolve your entire problem but it works for me

and i also created non-responsive.css that forces the grid to maintain the large screen version

in case u select mobile i would load / echo

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">  
<!-- Bootstrap core CSS and JS -->
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <link href="/themes/responsive_lime/bootstrap-3_1_1/css/bootstrap.css" rel="stylesheet">
        <script src="/themes/responsive_lime/bootstrap-3_1_1/js/bootstrap.min.js"></script>

and load these stylesheets
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style.css?modified=14-06-2014-12-27-40" />
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style-responsive.css?modified=1402758346" />

in case you select desktop i would load /echo

<meta name="viewport" content="width=1024">    


        <!-- Bootstrap core CSS and JS -->
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <link href="/themes/responsive_lime/bootstrap-3_1_1/css/bootstrap.css" rel="stylesheet">
        <script src="/themes/responsive_lime/bootstrap-3_1_1/js/bootstrap.min.js"></script>

        <!-- Main CSS -->
        <link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style.css?modified=14-06-2014-12-27-40" />
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/non-responsive.css?modified=1402758635" />

the non-responsive.css is the one that has overrides for bootstrap my concern is layout so there is not much in there, given that i handle the navigation in my own way so css for it and the other bits is in my other css files

please note that my setup does behave as desktop even on desktop browsers unlike some other solutions i have seen that will only ignore the viewport that seems to have wotked only on mobile devices for me

String contains another two strings

public static class StringExtensions
{
    public static bool Contains(this string s, params string[] predicates)
    {
        return predicates.All(s.Contains);
    }
}

string d = "You hit someone for 50 damage";
string a = "damage";
string b = "someone";
string c = "you";

if (d.Contains(a, b))
{
    Console.WriteLine("d contains a and b");
}

Ruby 'require' error: cannot load such file

Ruby 1.9 has removed the current directory from the load path, and so you will need to do a relative require on this file, as David Grayson says:

require_relative 'tokenizer'

There's no need to suffix it with .rb, as Ruby's smart enough to know that's what you mean anyway.

Hibernate JPA Sequence (non-Id)

Looking for answers to this problem, I stumbled upon this link

It seems that Hibernate/JPA isn't able to automatically create a value for your non-id-properties. The @GeneratedValue annotation is only used in conjunction with @Id to create auto-numbers.

The @GeneratedValue annotation just tells Hibernate that the database is generating this value itself.

The solution (or work-around) suggested in that forum is to create a separate entity with a generated Id, something like this:

@Entity
public class GeneralSequenceNumber {
  @Id
  @GeneratedValue(...)
  private Long number;
}

@Entity 
public class MyEntity {
  @Id ..
  private Long id;

  @OneToOne(...)
  private GeneralSequnceNumber myVal;
}

Simple example of threading in C++

There is also a POSIX library for POSIX operating systems. Check for compatability

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream>

void *task(void *argument){
      char* msg;
      msg = (char*)argument;
      std::cout<<msg<<std::endl;
}

int main(){
    pthread_t thread1, thread2;
    int i1,i2;
    i1 = pthread_create( &thread1, NULL, task, (void*) "thread 1");
    i2 = pthread_create( &thread2, NULL, task, (void*) "thread 2");

    pthread_join(thread1,NULL);
    pthread_join(thread2,NULL);
    return 0;

}

compile with -lpthread

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

How to use an array list in Java?

Java 8 introduced default implementation of forEach() inside the Iterable interface , you can easily do it by declarative approach .

  List<String> values = Arrays.asList("Yasir","Shabbir","Choudhary");

  values.forEach( value -> System.out.println(value));

Here is the code of Iterable interface

  default void forEach(Consumer<? super T> action) {
    Objects.requireNonNull(action);
    for (T t : this) {
        action.accept(t);
    }
}

Reference

How to dock "Tool Options" to "Toolbox"?

In the detached 'Tool Options' window, click on the red 'X' in the upper right corner to get rid of the window. Then on the main Gimp screen, click on 'Windows,' then 'Dockable Dialogs.' The first entry on its list will be 'Tool Options,' so click on that. Then, Tool Options will appear as a tab in the window on the right side of the screen, along with layers and undo history. Click and drag that tab over to the toolbox window on hte left and drop it inside. The tool options will again be docked in the toolbox.

How can you represent inheritance in a database?

Alternatively, consider using a document databases (such as MongoDB) which natively support rich data structures and nesting.

Getting an option text/value with JavaScript

In jquery you could try this $("#select_id>option:selected").text()

Add a string of text into an input field when user clicks a button

this will do it with just javascript - you can also put the function in a .js file and call it with onclick

//button
<div onclick="
   document.forms['name_of_the_form']['name_of_the_input'].value += 'text you want to add to it'"
>button</div>

Plot smooth line with PyPlot

For this example spline works well, but if the function is not smooth inherently and you want to have smoothed version you can also try:

from scipy.ndimage.filters import gaussian_filter1d

ysmoothed = gaussian_filter1d(y, sigma=2)
plt.plot(x, ysmoothed)
plt.show()

if you increase sigma you can get a more smoothed function.

Proceed with caution with this one. It modifies the original values and may not be what you want.

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

That true,Mustafa....its working..its point to two layout

  1. setContentView(R.layout.your_layout)
  2. v23(your_layout).

You should take Button both activity layout...
solve this problem successfully

How do I make an input field accept only letters in javaScript?

function alphaOnly(event) {
  var key = event.keyCode;
  return ((key >= 65 && key <= 90) || key == 8);
};

or

function lettersOnly(evt) {
       evt = (evt) ? evt : event;
       var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
          ((evt.which) ? evt.which : 0));
       if (charCode > 31 && (charCode < 65 || charCode > 90) &&
          (charCode < 97 || charCode > 122)) {
          alert("Enter letters only.");
          return false;
       }
       return true;
     }

How to get current foreground activity context in android?

Knowing that ActivityManager manages Activity, so we can gain information from ActivityManager. We get the current foreground running Activity by

ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;

UPDATE 2018/10/03
getRunningTasks() is DEPRECATED. see the solutions below.

This method was deprecated in API level 21. As of Build.VERSION_CODES.LOLLIPOP, this method is no longer available to third party applications: the introduction of document-centric recents means it can leak person information to the caller. For backwards compatibility, it will still return a small subset of its data: at least the caller's own tasks, and possibly some other tasks such as home that are known to not be sensitive.

How can I use regex to get all the characters after a specific character, e.g. comma (",")

.+,(.+)

Explanation:

.+,

will search for everything before the comma, including the comma.

(.+) 

will search for everything after the comma, and depending on your regex environment,

\1

is the reference for the first parentheses captured group that you need, in this example, everything after the comma.

Autoincrement VersionCode with gradle extra properties

The First Commented code will increment the number while each "Rebuild Project" and save the the value in the "Version Property" file.

The Second Commented code will generate new version name of APK file while "Build APKs".

android {
    compileSdkVersion 28
    buildToolsVersion "29.0.0"
    //==========================START==================================
    def Properties versionProps = new Properties()
    def versionPropsFile = file('version.properties')
    if(versionPropsFile.exists())
        versionProps.load(new FileInputStream(versionPropsFile))
    def code = (versionProps['VERSION_CODE'] ?: "0").toInteger() + 1
    versionProps['VERSION_CODE'] = code.toString()
    versionProps.store(versionPropsFile.newWriter(), null)
    //===========================END===================================
    defaultConfig {
        applicationId "com.example.myapp"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "0.19"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            //=======================================START===============================================
            android.applicationVariants.all { variant ->
                variant.outputs.all {
                    def appName = "MyAppSampleName"
                    outputFileName = appName+"_v${variant.versionName}.${versionProps['VERSION_CODE']}.apk"
                }
            }
            //=======================================END===============================================
        }
    }
}

How do you push a tag to a remote repository using Git?

To push a single tag:

git push origin <tag_name>

And the following command should push all tags (not recommended):

git push --tags

How to set JFrame to appear centered, regardless of monitor resolution?

You can use this method, which allows the JFrame to be centered and full screen at the same time.

yourframe.setExtendedState(JFrame.MAXIMIZED_BOTH);

how to convert java string to Date object

You basically effectively converted your date in a string format to a date object. If you print it out at that point, you will get the standard date formatting output. In order to format it after that, you then need to convert it back to a date object with a specified format (already specified previously)

String startDateString = "06/27/2007";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 
Date startDate;
try {
    startDate = df.parse(startDateString);
    String newDateString = df.format(startDate);
    System.out.println(newDateString);
} catch (ParseException e) {
    e.printStackTrace();
}

Can HTML checkboxes be set to readonly?

What none of you are thinking about here is that you are all using JavaScript, which can be very easily bypassed by any user.

Simply disabling it disables all JQuery/Return False statements.

Your only option for readonly checkboxes is server side.

Display them, let them change them but don't accept the new post data from them.

Using :before CSS pseudo element to add image to modal

http://caniuse.com/#search=::after

::after and ::before with content are better to use as they're supported in every major browser other than Internet Explorer at least 5 versions back. Internet Explorer has complete support in version 9+ and partial support in version 8.

Is this what you're looking for?

.Modal::after{
  content:url('blackCarrot.png'); /* with class ModalCarrot ??*/
  position:relative; /*or absolute*/
  z-index:100000; /*a number that's more than the modal box*/
  left:-50px;
  top:10px;
}

.ModalCarrot{
   position:absolute;
   left:50%;
   margin-left:-8px;
   top:-16px;
}

If not, can you explain a little better?

or you could use jQuery, like Joshua said:

$(".Modal").before("<img src='blackCarrot.png' class='ModalCarrot' />");

When should iteritems() be used instead of items()?

future.utils allows for python 2 and 3 compatibility.

# Python 2 and 3: option 3
from future.utils import iteritems
heights = {'man': 185,'lady': 165}
for (key, value) in iteritems(heights):
    print(key,value)

>>> ('lady', 165)
>>> ('man', 185)

See this link: https://python-future.org/compatible_idioms.html

How do I find the last column with data?

I think we can modify the UsedRange code from @Readify's answer above to get the last used column even if the starting columns are blank or not.

So this lColumn = ws.UsedRange.Columns.Count modified to

this lColumn = ws.UsedRange.Column + ws.UsedRange.Columns.Count - 1 will give reliable results always

enter image description here

?Sheet1.UsedRange.Column + Sheet1.UsedRange.Columns.Count - 1

Above line Yields 9 in the immediate window.

Check whether user has a Chrome extension installed

Chrome now has the ability to send messages from the website to the extension.

So in the extension background.js (content.js will not work) add something like:

chrome.runtime.onMessageExternal.addListener(
    function(request, sender, sendResponse) {
        if (request) {
            if (request.message) {
                if (request.message == "version") {
                    sendResponse({version: 1.0});
                }
            }
        }
        return true;
    });

This will then let you make a call from the website:

var hasExtension = false;

chrome.runtime.sendMessage(extensionId, { message: "version" },
    function (reply) {
        if (reply) {
            if (reply.version) {
                if (reply.version >= requiredVersion) {
                    hasExtension = true;
                }
            }
        }
        else {
          hasExtension = false;
        }
    });

You can then check the hasExtension variable. The only drawback is the call is asynchronous, so you have to work around that somehow.

Edit: As mentioned below, you'll need to add an entry to the manifest.json listing the domains that can message your addon. Eg:

"externally_connectable": {
    "matches": ["*://localhost/*", "*://your.domain.com/*"]
},

How to import a jar in Eclipse

In eclipse I included a compressed jar file i.e. zip file. Eclipse allowed me to add this zip file as an external jar but when I tried to access the classes in the jar they weren't showing up.

After a lot of trial and error I found that using a zip format doesn't work. When I added a jar file then it worked for me.

Align a div to center

This worked for me.

I included an unordered list on my page twice. One div class="menu" id="vertical" the other to be centered was div class="menu" id="horizontal". Since the list was floated left, I needed an inner div to center it. See below.

<div class=menu id="horizontal">
<div class="fix">
  Centered stuff
</div>
</div>

.menu#horizontal { display: block;  float: left; margin: 0px; padding: 0 10px; position: relative; left: 50%; }
#fix { float: right; position: relative; left: -50%; margin: 0px auto; }

How can I access Google Sheet spreadsheets only with Javascript?

'JavaScript accessing Google Docs' would be tedious to implement and moreover Google documentation is also not that simple to get it. I have some good links to share by which you can achieve js access to gdoc:

http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#UploadingDocs

http://code.google.com/apis/spreadsheets/gadgets/

http://code.google.com/apis/gdata/docs/js.html

http://www.mail-archive.com/[email protected]/msg01924.html

May be these would help you out..

Where can I get a list of Countries, States and Cities?

Geonames has a lot of data on places (including towns and cities) but it seems to be contributed and perhaps not complete.

Perhaps also try SQL Dumpster, I've used this website a lot for these kinds of databases, cities, provinces, etc. Unfortunately it's not free but only appears to be a one-time fee.

java Compare two dates

Try using this Function.It Will help You:-

public class Main {   
public static void main(String args[]) 
 {        
  Date today=new Date();                     
  Date myDate=new Date(today.getYear(),today.getMonth()-1,today.getDay());
  System.out.println("My Date is"+myDate);    
  System.out.println("Today Date is"+today);
  if(today.compareTo(myDate)<0)
     System.out.println("Today Date is Lesser than my Date");
  else if(today.compareTo(myDate)>0)
     System.out.println("Today Date is Greater than my date"); 
  else
     System.out.println("Both Dates are equal");      
  }
}

How to convert datatype:object to float64 in python?

Or you can use regular expression to handle multiple items as the general case of this issue,

df['2nd'] = pd.to_numeric(df['2nd'].str.replace(r'[,.%]','')) 
df['CTR'] = pd.to_numeric(df['CTR'].str.replace(r'[^\d%]',''))

Best way to convert string to bytes in Python 3?

It's easier than it is thought:

my_str = "hello world"
my_str_as_bytes = str.encode(my_str)
type(my_str_as_bytes) # ensure it is byte representation
my_decoded_str = my_str_as_bytes.decode()
type(my_decoded_str) # ensure it is string representation

How To Set A JS object property name from a variable

It does not matter where the variable comes from. Main thing we have one ... Set the variable name between square brackets "[ .. ]".

var optionName = 'nameA';
var JsonVar = {
[optionName] : 'some value'
}

Ansible: how to get output to display

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

---
- hosts: localhost
  tasks:
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [
        "play.yml"
    ]
}

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
(...)
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        },
        "module_name": "command"
    },
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
        "play.retry",
        "play.yml"
    ],
    "warnings": []
}

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

tasks:
  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output

Python - difference between two strings

You can use ndiff in the difflib module to do this. It has all the information necessary to convert one string into another string.

A simple example:

import difflib

cases=[('afrykanerskojezyczny', 'afrykanerskojezycznym'),
       ('afrykanerskojezyczni', 'nieafrykanerskojezyczni'),
       ('afrykanerskojezycznym', 'afrykanerskojezyczny'),
       ('nieafrykanerskojezyczni', 'afrykanerskojezyczni'),
       ('nieafrynerskojezyczni', 'afrykanerskojzyczni'),
       ('abcdefg','xac')] 

for a,b in cases:     
    print('{} => {}'.format(a,b))  
    for i,s in enumerate(difflib.ndiff(a, b)):
        if s[0]==' ': continue
        elif s[0]=='-':
            print(u'Delete "{}" from position {}'.format(s[-1],i))
        elif s[0]=='+':
            print(u'Add "{}" to position {}'.format(s[-1],i))    
    print()      

prints:

afrykanerskojezyczny => afrykanerskojezycznym
Add "m" to position 20

afrykanerskojezyczni => nieafrykanerskojezyczni
Add "n" to position 0
Add "i" to position 1
Add "e" to position 2

afrykanerskojezycznym => afrykanerskojezyczny
Delete "m" from position 20

nieafrykanerskojezyczni => afrykanerskojezyczni
Delete "n" from position 0
Delete "i" from position 1
Delete "e" from position 2

nieafrynerskojezyczni => afrykanerskojzyczni
Delete "n" from position 0
Delete "i" from position 1
Delete "e" from position 2
Add "k" to position 7
Add "a" to position 8
Delete "e" from position 16

abcdefg => xac
Add "x" to position 0
Delete "b" from position 2
Delete "d" from position 4
Delete "e" from position 5
Delete "f" from position 6
Delete "g" from position 7

How to "scan" a website (or page) for info, and bring it into my program?

I would use JTidy - it is simlar to JSoup, but I don't know JSoup well. JTidy handles broken HTML and returns a w3c Document, so you can use this as a source to XSLT to extract the content you are really interested in. If you don't know XSLT, then you might as well go with JSoup, as the Document model is nicer to work with than w3c.

EDIT: A quick look on the JSoup website shows that JSoup may indeed be the better choice. It seems to support CSS selectors out the box for extracting stuff from the document. This may be a lot easier to work with than getting into XSLT.

HTTP POST using JSON in Java

Java 8 with apache httpClient 4

CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("www.site.com");


String json = "details={\"name\":\"myname\",\"age\":\"20\"} ";

        try {
            StringEntity entity = new StringEntity(json);
            httpPost.setEntity(entity);

            // set your POST request headers to accept json contents
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            try {
                // your closeablehttp response
                CloseableHttpResponse response = client.execute(httpPost);

                // print your status code from the response
                System.out.println(response.getStatusLine().getStatusCode());

                // take the response body as a json formatted string 
                String responseJSON = EntityUtils.toString(response.getEntity());

                // convert/parse the json formatted string to a json object
                JSONObject jobj = new JSONObject(responseJSON);

                //print your response body that formatted into json
                System.out.println(jobj);

            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {

                e.printStackTrace();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

How to fix HTTP 404 on Github Pages?

I bound my domain before this problem appeared. I committed and pushed the branch gh-pages and it solved my problem. New commits force jekyll to rebuild your pages.

Split function equivalent in T-SQL?

CREATE FUNCTION Split
(
  @delimited nvarchar(max),
  @delimiter nvarchar(100)
) RETURNS @t TABLE
(
-- Id column can be commented out, not required for sql splitting string
  id int identity(1,1), -- I use this column for numbering splitted parts
  val nvarchar(max)
)
AS
BEGIN
  declare @xml xml
  set @xml = N'<root><r>' + replace(@delimited,@delimiter,'</r><r>') + '</r></root>'

  insert into @t(val)
  select
    r.value('.','varchar(max)') as item
  from @xml.nodes('//root/r') as records(r)

  RETURN
END
GO

usage

Select * from dbo.Split(N'1,2,3,4,6',',')

Should I use pt or px?

Have a look at this excellent article at CSS-Tricks:

Taken from the article:


pt

The final unit of measurement that it is possible to declare font sizes in is point values (pt). Point values are only for print CSS! A point is a unit of measurement used for real-life ink-on-paper typography. 72pts = one inch. One inch = one real-life inch like-on-a-ruler. Not an inch on a screen, which is totally arbitrary based on resolution.

Just like how pixels are dead-accurate on monitors for font-sizing, point sizes are dead-accurate on paper. For the best cross-browser and cross-platform results while printing pages, set up a print stylesheet and size all fonts with point sizes.

For good measure, the reason we don't use point sizes for screen display (other than it being absurd), is that the cross-browser results are drastically different:

px

If you need fine-grained control, sizing fonts in pixel values (px) is an excellent choice (it's my favorite). On a computer screen, it doesn't get any more accurate than a single pixel. With sizing fonts in pixels, you are literally telling browsers to render the letters exactly that number of pixels in height:

Windows, Mac, aliased, anti-aliased, cross-browsers, doesn't matter, a font set at 14px will be 14px tall. But that isn't to say there won't still be some variation. In a quick test below, the results were slightly more consistent than with keywords but not identical:

Due to the nature of pixel values, they do not cascade. If a parent element has an 18px pixel size and the child is 16px, the child will be 16px. However, font-sizing settings can be using in combination. For example, if the parent was set to 16px and the child was set to larger, the child would indeed come out larger than the parent. A quick test showed me this:

"Larger" bumped the 16px of the parent into 20px, a 25% increase.

Pixels have gotten a bad wrap in the past for accessibility and usability concerns. In IE 6 and below, font-sizes set in pixels cannot be resized by the user. That means that us hip young healthy designers can set type in 12px and read it on the screen just fine, but when folks a little longer in the tooth go to bump up the size so they can read it, they are unable to. This is really IE 6's fault, not ours, but we gots what we gots and we have to deal with it.

Setting font-size in pixels is the most accurate (and I find the most satisfying) method, but do take into consideration the number of visitors still using IE 6 on your site and their accessibility needs. We are right on the bleeding edge of not needing to care about this anymore.


How to get the return value from a thread in python?

Define your target to
1) take an argument q
2) replace any statements return foo with q.put(foo); return

so a function

def func(a):
    ans = a * a
    return ans

would become

def func(a, q):
    ans = a * a
    q.put(ans)
    return

and then you would proceed as such

from Queue import Queue
from threading import Thread

ans_q = Queue()
arg_tups = [(i, ans_q) for i in xrange(10)]

threads = [Thread(target=func, args=arg_tup) for arg_tup in arg_tups]
_ = [t.start() for t in threads]
_ = [t.join() for t in threads]
results = [q.get() for _ in xrange(len(threads))]

And you can use function decorators/wrappers to make it so you can use your existing functions as target without modifying them, but follow this basic scheme.

Adjusting HttpWebRequest Connection Timeout in C#

No matter what we tried we couldn't manage to get the timeout below 21 seconds when the server we were checking was down.

To work around this we combined a TcpClient check to see if the domain was alive followed by a separate check to see if the URL was active

public static bool IsUrlAlive(string aUrl, int aTimeoutSeconds)
{
    try
    {
        //check the domain first
        if (IsDomainAlive(new Uri(aUrl).Host, aTimeoutSeconds))
        {
            //only now check the url itself
            var request = System.Net.WebRequest.Create(aUrl);
            request.Method = "HEAD";
            request.Timeout = aTimeoutSeconds * 1000;
            var response = (HttpWebResponse)request.GetResponse();
            return response.StatusCode == HttpStatusCode.OK;
        }
    }
    catch
    {
    }
    return false;

}

private static bool IsDomainAlive(string aDomain, int aTimeoutSeconds)
{
    try
    {
        using (TcpClient client = new TcpClient())
        {
            var result = client.BeginConnect(aDomain, 80, null, null);

            var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(aTimeoutSeconds));

            if (!success)
            {
                return false;
            }

            // we have connected
            client.EndConnect(result);
            return true;
        }
    }
    catch
    {
    }
    return false;
}

Pointers in Python?

>> id(1)
1923344848  # identity of the location in memory where 1 is stored
>> id(1)
1923344848  # always the same
>> a = 1
>> b = a  # or equivalently b = 1, because 1 is immutable
>> id(a)
1923344848
>> id(b)  # equal to id(a)
1923344848

As you can see a and b are just two different names that reference to the same immutable object (int) 1. If later you write a = 2, you reassign the name a to a different object (int) 2, but the b continues referencing to 1:

>> id(2)
1923344880
>> a = 2
>> id(a)
1923344880  # equal to id(2)
>> b
1           # b hasn't changed
>> id(b)
1923344848  # equal to id(1)

What would happen if you had a mutable object instead, such as a list [1]?

>> id([1])
328817608
>> id([1])
328664968  # different from the previous id, because each time a new list is created
>> a = [1]
>> id(a)
328817800
>> id(a)
328817800 # now same as before
>> b = a
>> id(b)
328817800  # same as id(a)

Again, we are referencing to the same object (list) [1] by two different names a and b. However now we can mutate this list while it remains the same object, and a, b will both continue referencing to it

>> a[0] = 2
>> a
[2]
>> b
[2]
>> id(a)
328817800  # same as before
>> id(b)
328817800  # same as before

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

You have to find the right user that needs to use temp folder. In my computer I follow the above link and find the special folder c:\inetpub, that iis use to execute her web services. I check what users could use these folder and find something like these: computername\iis_isusrs

The main issue comes when you try to add it to all permit on temp folder I was going to properties, security tab, edit button, add user button then i put iis_isusrs

and "check names" button

It doesn´t find anything The reason is the in my case it looks ( windows 2008 r2 iis 7 ) on pdgs.local location You have to go to "Select Users or Groups" form, click on Advanced button, click on Locations button and will see a specific hierarchy

  • computername
  • Entire Directory
    • pdgs.local

So when you try to add an user, its search name on pdgs.local. You have to select computername and click ok, Click on "Find Now"

Look for IIS_IUSRS on Name(RDN) column, click ok. So we go back to "Select Users or Groups" form with new and right user underline

click ok, allow full control, and click ok again.

That´s all folks, Hope it helps,

Jose from Moralzarzal ( Madrid )

Link to add to Google calendar

For the next person Googling this topic, I've written a small NPM package to make it simple to generate Google Calendar URLs. It includes TypeScript type definitions, for those who need that. Hope it helps!

https://www.npmjs.com/package/google-calendar-url

split string in two on given index and return both parts

function splitText(value, index) {
  if (value.length < index) {return value;} 
  return [value.substring(0, index)].concat(splitText(value.substring(index), index));
}
console.log(splitText('this is a testing peace of text',10));
// ["this is a ", "testing pe", "ace of tex", "t"] 

For those who want to split a text into array using the index.

How do I add the Java API documentation to Eclipse?

Eclipse doesn't pull the tooltips from the javadoc location. It only uses the javadoc location to prepend to the link if you say open in browser, you need to download and attach the source for the JDK in order to get the tooltips. For all the JARs under the JRE you should have the following for the javadoc location: http://java.sun.com/javase/6/docs/api/. For resources.jar, rt.jar, jsse.jar, jce.jar and charsets.jar you should attach the source available here.

What are the different usecases of PNG vs. GIF vs. JPEG vs. SVG?

GIF based on a palette of 256 colours per image (at least in its basic incarnation). PNG can do "TrueColour", i.e. 16.7 Million colours out of the box. Lossless PNG compresses better than lossless GIFs. GIF can do "binary" transparency (0% opacity or 100% opacity). PNG can handle alpha transparencies.

All in all, if you don't need to use Alpha-transparent images and support IE6, PNG is probably the better choice when you need pixel-perfect images for vector illustrations and such. JPG is unbeatable for photographs.

How to subtract date/time in JavaScript?

You can use getTime() method to convert the Date to the number of milliseconds since January 1, 1970. Then you can easy do any arithmetic operations with the dates. Of course you can convert the number back to the Date with setTime(). See here an example.

Use of "this" keyword in formal parameters for static methods in C#

This is an extension method. See here for an explanation.

Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type. Extension Methods help blend the flexibility of "duck typing" support popular within dynamic languages today with the performance and compile-time validation of strongly-typed languages.

Extension Methods enable a variety of useful scenarios, and help make possible the really powerful LINQ query framework... .

it means that you can call

MyClass myClass = new MyClass();
int i = myClass.Foo();

rather than

MyClass myClass = new MyClass();
int i = Foo(myClass);

This allows the construction of fluent interfaces as stated below.

How do I specify C:\Program Files without a space in it for programs that can't handle spaces in file paths?

No.

Sometimes you can quote the filename.

"C:\Program Files\Something"

Some programs will tolerate the quotes. Since you didn't provide any specific program, it's impossible to tell if quotes will work for you.

100% width Twitter Bootstrap 3 template

In BOOTSTRAP 4 you can use

<div class="row m-0">
my fullwidth div
</div>

... if you just use a .row without the .m-0 as a top level div, you will have unwanted margin, which makes the page wider than the browser window and cause a horizontal scrollbar.

pip install - locale.Error: unsupported locale setting

For Dockerfile, this works for me:

RUN locale-gen en_US.UTF-8  
ENV LANG en_US.UTF-8  
ENV LANGUAGE en_US:en  
ENV LC_ALL en_US.UTF-8  

How to install locale-gen?

docker ubuntu /bin/sh: 1: locale-gen: not found

How do I convert between big-endian and little-endian values in C++?

Seriously... I don't understand why all solutions are that complicated! How about the simplest, most general template function that swaps any type of any size under any circumstances in any operating system????

template <typename T>
void SwapEnd(T& var)
{
    static_assert(std::is_pod<T>::value, "Type must be POD type for safety");
    std::array<char, sizeof(T)> varArray;
    std::memcpy(varArray.data(), &var, sizeof(T));
    for(int i = 0; i < static_cast<int>(sizeof(var)/2); i++)
        std::swap(varArray[sizeof(var) - 1 - i],varArray[i]);
    std::memcpy(&var, varArray.data(), sizeof(T));
}

It's the magic power of C and C++ together! Simply swap the original variable character by character.

Point 1: No operators: Remember that I didn't use the simple assignment operator "=" because some objects will be messed up when the endianness is flipped and the copy constructor (or assignment operator) won't work. Therefore, it's more reliable to copy them char by char.

Point 2: Be aware of alignment issues: Notice that we're copying to and from an array, which is the right thing to do because the C++ compiler doesn't guarantee that we can access unaligned memory (this answer was updated from its original form for this). For example, if you allocate uint64_t, your compiler cannot guarantee that you can access the 3rd byte of that as a uint8_t. Therefore, the right thing to do is to copy this to a char array, swap it, then copy it back (so no reinterpret_cast). Notice that compilers are mostly smart enough to convert what you did back to a reinterpret_cast if they're capable of accessing individual bytes regardless of alignment.

To use this function:

double x = 5;
SwapEnd(x);

and now x is different in endianness.

AngularJS passing data to $http.get request

You can pass params directly to $http.get() The following works fine

$http.get(user.details_path, {
    params: { user_id: user.id }
});

LISTAGG in Oracle to return distinct values

I implemented this stored function :

CREATE TYPE LISTAGG_DISTINCT_PARAMS AS OBJECT (ELEMENTO VARCHAR2(2000), SEPARATORE VARCHAR2(10));

CREATE TYPE T_LISTA_ELEMENTI AS TABLE OF VARCHAR2(2000);

CREATE TYPE T_LISTAGG_DISTINCT AS OBJECT (

    LISTA_ELEMENTI T_LISTA_ELEMENTI,
        SEPARATORE VARCHAR2(10),

    STATIC FUNCTION ODCIAGGREGATEINITIALIZE(SCTX  IN OUT            T_LISTAGG_DISTINCT) 
                    RETURN NUMBER,

    MEMBER FUNCTION ODCIAGGREGATEITERATE   (SELF  IN OUT            T_LISTAGG_DISTINCT, 
                                            VALUE IN                    LISTAGG_DISTINCT_PARAMS ) 
                    RETURN NUMBER,

    MEMBER FUNCTION ODCIAGGREGATETERMINATE (SELF         IN     T_LISTAGG_DISTINCT,
                                            RETURN_VALUE OUT    VARCHAR2, 
                                            FLAGS        IN     NUMBER      )
                    RETURN NUMBER,

    MEMBER FUNCTION ODCIAGGREGATEMERGE       (SELF               IN OUT T_LISTAGG_DISTINCT,
                                                                                        CTX2                 IN         T_LISTAGG_DISTINCT    )
                    RETURN NUMBER
);

CREATE OR REPLACE TYPE BODY T_LISTAGG_DISTINCT IS 

    STATIC FUNCTION ODCIAGGREGATEINITIALIZE(SCTX IN OUT T_LISTAGG_DISTINCT) RETURN NUMBER IS 
    BEGIN
                SCTX := T_LISTAGG_DISTINCT(T_LISTA_ELEMENTI() , ',');
        RETURN ODCICONST.SUCCESS;
    END;

    MEMBER FUNCTION ODCIAGGREGATEITERATE(SELF IN OUT T_LISTAGG_DISTINCT, VALUE IN LISTAGG_DISTINCT_PARAMS) RETURN NUMBER IS
    BEGIN

                IF VALUE.ELEMENTO IS NOT NULL THEN
                        SELF.LISTA_ELEMENTI.EXTEND;
                        SELF.LISTA_ELEMENTI(SELF.LISTA_ELEMENTI.LAST) := TO_CHAR(VALUE.ELEMENTO);
                        SELF.LISTA_ELEMENTI:= SELF.LISTA_ELEMENTI MULTISET UNION DISTINCT SELF.LISTA_ELEMENTI;
                        SELF.SEPARATORE := VALUE.SEPARATORE;
                END IF;
        RETURN ODCICONST.SUCCESS;
    END;

    MEMBER FUNCTION ODCIAGGREGATETERMINATE(SELF IN T_LISTAGG_DISTINCT, RETURN_VALUE OUT VARCHAR2, FLAGS IN NUMBER) RETURN NUMBER IS
      STRINGA_OUTPUT            CLOB:='';
            LISTA_OUTPUT                T_LISTA_ELEMENTI;
            TERMINATORE                 VARCHAR2(3):='...';
            LUNGHEZZA_MAX           NUMBER:=4000;
    BEGIN

                IF SELF.LISTA_ELEMENTI.EXISTS(1) THEN -- se esiste almeno un elemento nella lista

                        -- inizializza una nuova lista di appoggio
                        LISTA_OUTPUT := T_LISTA_ELEMENTI();

                        -- riversamento dei soli elementi in DISTINCT
                        LISTA_OUTPUT := SELF.LISTA_ELEMENTI MULTISET UNION DISTINCT SELF.LISTA_ELEMENTI;

                        -- ordinamento degli elementi
                        SELECT CAST(MULTISET(SELECT * FROM TABLE(LISTA_OUTPUT) ORDER BY 1 ) AS T_LISTA_ELEMENTI ) INTO LISTA_OUTPUT FROM DUAL;

                        -- concatenazione in una stringa                        
                        FOR I IN LISTA_OUTPUT.FIRST .. LISTA_OUTPUT.LAST - 1
                        LOOP
                            STRINGA_OUTPUT := STRINGA_OUTPUT || LISTA_OUTPUT(I) || SELF.SEPARATORE;
                        END LOOP;
                        STRINGA_OUTPUT := STRINGA_OUTPUT || LISTA_OUTPUT(LISTA_OUTPUT.LAST);

                        -- se la stringa supera la dimensione massima impostata, tronca e termina con un terminatore
                        IF LENGTH(STRINGA_OUTPUT) > LUNGHEZZA_MAX THEN
                                    RETURN_VALUE := SUBSTR(STRINGA_OUTPUT, 0, LUNGHEZZA_MAX - LENGTH(TERMINATORE)) || TERMINATORE;
                        ELSE
                                    RETURN_VALUE:=STRINGA_OUTPUT;
                        END IF;

                ELSE -- se non esiste nessun elemento, restituisci NULL

                        RETURN_VALUE := NULL;

                END IF;

        RETURN ODCICONST.SUCCESS;
    END;

    MEMBER FUNCTION ODCIAGGREGATEMERGE(SELF IN OUT T_LISTAGG_DISTINCT, CTX2 IN T_LISTAGG_DISTINCT) RETURN NUMBER IS
    BEGIN
        RETURN ODCICONST.SUCCESS;
    END;

END; -- fine corpo

CREATE
FUNCTION LISTAGG_DISTINCT (INPUT LISTAGG_DISTINCT_PARAMS) RETURN VARCHAR2
    PARALLEL_ENABLE AGGREGATE USING T_LISTAGG_DISTINCT;

// Example
SELECT LISTAGG_DISTINCT(LISTAGG_DISTINCT_PARAMS(OWNER, ', ')) AS LISTA_OWNER
FROM SYS.ALL_OBJECTS;

I'm sorry, but in some case (for a very big set), Oracle could return this error:

Object or Collection value was too large. The size of the value
might have exceeded 30k in a SORT context, or the size might be
too big for available memory.

but I think this is a good point of start ;)

Detect merged cells in VBA Excel with MergeArea

There are several helpful bits of code for this.

Place your cursor in a merged cell and ask these questions in the Immidiate Window:

Is the activecell a merged cell?

? Activecell.Mergecells
 True

How many cells are merged?

? Activecell.MergeArea.Cells.Count
 2

How many columns are merged?

? Activecell.MergeArea.Columns.Count
 2

How many rows are merged?

? Activecell.MergeArea.Rows.Count
  1

What's the merged range address?

? activecell.MergeArea.Address
  $F$2:$F$3

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

The solution to change the encoding to Latin1 / ISO-8859-1 solves an issue I observed with html2text.py as invoked on an output of tex4ht. I use that for an automated word count on LaTeX documents: tex4ht converts them to HTML, and then html2text.py strips them down to pure text for further counting through wc -w. Now, if, for example, a German "Umlaut" comes in through a literature database entry, that process would fail as html2text.py would complain e.g.

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 32243-32245: invalid data

Now these errors would then subsequently be particularly hard to track down, and essentially you want to have the Umlaut in your references section. A simple change inside html2text.py from

data = data.decode(encoding)

to

data = data.decode("ISO-8859-1")

solves that issue; if you're calling the script using the HTML file as first parameter, you can also pass the encoding as second parameter and spare the modification.

Calling C/C++ from Python?

pybind11 minimal runnable example

pybind11 was previously mentioned at https://stackoverflow.com/a/38542539/895245 but I would like to give here a concrete usage example and some further discussion about implementation.

All and all, I highly recommend pybind11 because it is really easy to use: you just include a header and then pybind11 uses template magic to inspect the C++ class you want to expose to Python and does that transparently.

The downside of this template magic is that it slows down compilation immediately adding a few seconds to any file that uses pybind11, see for example the investigation done on this issue. PyTorch agrees. A proposal to remediate this problem has been made at: https://github.com/pybind/pybind11/pull/2445

Here is a minimal runnable example to give you a feel of how awesome pybind11 is:

class_test.cpp

#include <string>

#include <pybind11/pybind11.h>

struct ClassTest {
    ClassTest(const std::string &name) : name(name) { }
    void setName(const std::string &name_) { name = name_; }
    const std::string &getName() const { return name; }
    std::string name;
};

namespace py = pybind11;

PYBIND11_PLUGIN(class_test) {
    py::module m("my_module", "pybind11 example plugin");
    py::class_<ClassTest>(m, "ClassTest")
        .def(py::init<const std::string &>())
        .def("setName", &ClassTest::setName)
        .def("getName", &ClassTest::getName)
        .def_readwrite("name", &ClassTest::name);
    return m.ptr();
}

class_test_main.py

#!/usr/bin/env python3

import class_test

my_class_test = class_test.ClassTest("abc");
print(my_class_test.getName())
my_class_test.setName("012")
print(my_class_test.getName())
assert(my_class_test.getName() == my_class_test.name)

Compile and run:

#!/usr/bin/env bash
set -eux
g++ `python3-config --cflags` -shared -std=c++11 -fPIC class_test.cpp \
  -o class_test`python3-config --extension-suffix` `python3-config --libs`
./class_test_main.py

This example shows how pybind11 allows you to effortlessly expose the ClassTest C++ class to Python! Compilation produces a file named class_test.cpython-36m-x86_64-linux-gnu.so which class_test_main.py automatically picks up as the definition point for the class_test natively defined module.

Perhaps the realization of how awesome this is only sinks in if you try to do the same thing by hand with the native Python API, see for example this example of doing that, which has about 10x more code: https://github.com/cirosantilli/python-cheat/blob/4f676f62e87810582ad53b2fb426b74eae52aad5/py_from_c/pure.c On that example you can see how the C code has to painfully and explicitly define the Python class bit by bit with all the information it contains (members, methods, further metadata...). See also:

pybind11 claims to be similar to Boost.Python which was mentioned at https://stackoverflow.com/a/145436/895245 but more minimal because it is freed from the bloat of being inside the Boost project:

pybind11 is a lightweight header-only library that exposes C++ types in Python and vice versa, mainly to create Python bindings of existing C++ code. Its goals and syntax are similar to the excellent Boost.Python library by David Abrahams: to minimize boilerplate code in traditional extension modules by inferring type information using compile-time introspection.

The main issue with Boost.Python—and the reason for creating such a similar project—is Boost. Boost is an enormously large and complex suite of utility libraries that works with almost every C++ compiler in existence. This compatibility has its cost: arcane template tricks and workarounds are necessary to support the oldest and buggiest of compiler specimens. Now that C++11-compatible compilers are widely available, this heavy machinery has become an excessively large and unnecessary dependency.

Think of this library as a tiny self-contained version of Boost.Python with everything stripped away that isn't relevant for binding generation. Without comments, the core header files only require ~4K lines of code and depend on Python (2.7 or 3.x, or PyPy2.7 >= 5.7) and the C++ standard library. This compact implementation was possible thanks to some of the new C++11 language features (specifically: tuples, lambda functions and variadic templates). Since its creation, this library has grown beyond Boost.Python in many ways, leading to dramatically simpler binding code in many common situations.

pybind11 is also the only non-native alternative hightlighted by the current Microsoft Python C binding documentation at: https://docs.microsoft.com/en-us/visualstudio/python/working-with-c-cpp-python-in-visual-studio?view=vs-2019 (archive).

Tested on Ubuntu 18.04, pybind11 2.0.1, Python 3.6.8, GCC 7.4.0.

Convert double/float to string

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

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

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

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

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

How to set environment via `ng serve` in Angular 6

This answer seems good.
however, it lead me towards an error as it resulted with
Configuration 'xyz' could not be found in project ...
error in build.
It is requierd not only to updated build configurations, but also serve ones.

So just to leave no confusions:

  1. --env is not supported in angular 6
  2. --env got changed into --configuration || -c (and is now more powerful)
  3. to manage various envs, in addition to adding new environment file, it is now required to do some changes in angular.json file:
    • add new configuration in the build { ... "build": "configurations": ... property
    • new build configuration may contain only fileReplacements part, (but more options are available)
    • add new configuration in the serve { ... "serve": "configurations": ... property
    • new serve configuration shall contain of browserTarget="your-project-name:build:staging"

Could not autowire field in spring. why?

I've faced the same issue today. Turned out to be I forgot to mention @Service/@Component annotation for my service implementation file, for which spring is not able autowire and failing to create the bean.

Using jQuery to compare two arrays of Javascript objects

My approach was quite different - I flattened out both collections using JSON.stringify and used a normal string compare to check for equality.

I.e.

var arr1 = [
             {Col: 'a', Val: 1}, 
             {Col: 'b', Val: 2}, 
             {Col: 'c', Val: 3}
           ];

var arr2 = [
             {Col: 'x', Val: 24}, 
             {Col: 'y', Val: 25}, 
             {Col: 'z', Val: 26}
           ];

if(JSON.stringify(arr1) == JSON.stringify(arr2)){
    alert('Collections are equal');
}else{
    alert('Collections are not equal');
}

NB: Please note that his method assumes that both Collections are sorted in a similar fashion, if not, it would give you a false result!

Byte[] to ASCII

Encoding.ASCII.GetString(buf);

MySQL/Writing file error (Errcode 28)

For xampp users: on my experience, the problem was caused by a file, named '0' and located in the 'mysql' folder. The size was tooooo huge (mine exploded to about 256 Gb). Its removal fixed the problem.

Send XML data to webservice using php curl

Previous anwser works fine. I would just add that you dont need to specify CURLOPT_POSTFIELDS as "xmlRequest=" . $input_xml to read your $_POST. You can use file_get_contents('php://input') to get the raw post data as plain XML.

How to get correlation of two vectors in python

The docs indicate that numpy.correlate is not what you are looking for:

numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
  Cross-correlation of two 1-dimensional sequences.
  This function computes the correlation as generally defined in signal processing texts:
     z[k] = sum_n a[n] * conj(v[n+k])
  with a and v sequences being zero-padded where necessary and conj being the conjugate.

Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

from scipy.stats.stats import pearsonr   
a = [1,4,6]
b = [1,2,3]   
print pearsonr(a,b)

This gives

(0.99339926779878274, 0.073186395040328034)

You can also use numpy.corrcoef:

import numpy
print numpy.corrcoef(a,b)

This gives:

[[ 1.          0.99339927]
 [ 0.99339927  1.        ]]

Postgresql Select rows where column = array

   $array[0] = 1;
   $array[2] = 2;
   $arrayTxt = implode( ',', $array);
   $sql = "SELECT * FROM table WHERE some_id in ($arrayTxt)"

Override back button to act like home button

If you want to catch the Back Button have a look at this post on the Android Developer Blog. It covers the easier way to do this in Android 2.0 and the best way to do this for an application that runs on 1.x and 2.0.

However, if your Activity is Stopped it still may be killed depending on memory availability on the device. If you want a process to run with no UI you should create a Service. The documentation says the following about Services:

A service doesn't have a visual user interface, but rather runs in the background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it.

These seems appropriate for your requirements.

Get first letter of a string from column

.str.get

This is the simplest to specify string methods

# Setup
df = pd.DataFrame({'A': ['xyz', 'abc', 'foobar'], 'B': [123, 456, 789]})
df

        A    B
0     xyz  123
1     abc  456
2  foobar  789

df.dtypes

A    object
B     int64
dtype: object

For string (read:object) type columns, use

df['C'] = df['A'].str[0]
# Similar to,
df['C'] = df['A'].str.get(0)

.str handles NaNs by returning NaN as the output.

For non-numeric columns, an .astype conversion is required beforehand, as shown in @Ed Chum's answer.

# Note that this won't work well if the data has NaNs. 
# It'll return lowercase "n"
df['D'] = df['B'].astype(str).str[0]

df
        A    B  C  D
0     xyz  123  x  1
1     abc  456  a  4
2  foobar  789  f  7

List Comprehension and Indexing

There is enough evidence to suggest a simple list comprehension will work well here and probably be faster.

# For string columns
df['C'] = [x[0] for x in df['A']]

# For numeric columns
df['D'] = [str(x)[0] for x in df['B']]

df
        A    B  C  D
0     xyz  123  x  1
1     abc  456  a  4
2  foobar  789  f  7

If your data has NaNs, then you will need to handle this appropriately with an if/else in the list comprehension,

df2 = pd.DataFrame({'A': ['xyz', np.nan, 'foobar'], 'B': [123, 456, np.nan]})
df2

        A      B
0     xyz  123.0
1     NaN  456.0
2  foobar    NaN

# For string columns
df2['C'] = [x[0] if isinstance(x, str) else np.nan for x in df2['A']]

# For numeric columns
df2['D'] = [str(x)[0] if pd.notna(x) else np.nan for x in df2['B']]

        A      B    C    D
0     xyz  123.0    x    1
1     NaN  456.0  NaN    4
2  foobar    NaN    f  NaN

Let's do some timeit tests on some larger data.

df_ = df.copy()
df = pd.concat([df_] * 5000, ignore_index=True) 

%timeit df.assign(C=df['A'].str[0])
%timeit df.assign(D=df['B'].astype(str).str[0])

%timeit df.assign(C=[x[0] for x in df['A']])
%timeit df.assign(D=[str(x)[0] for x in df['B']])

12 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
27.1 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

3.77 ms ± 110 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
7.84 ms ± 145 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

List comprehensions are 4x faster.

how do I get a new line, after using float:left?

Try the clear property.

Remember that float removes an element from the document layout - so yes, in a way it is "interfering" with br and p tags, in the sense that it would basically be ignoring anything in the main flow layout.

Sequence contains no elements?

Reason for error:

  1. The query from p in dc.BlogPosts where p.BlogPostID == ID select p returns a sequence.

  2. Single() tries to retrieve an element from the sequence returned in step1.

  3. As per the exception - The sequence returned in step1 contains no elements.

  4. Single() tries to retrieve an element from the sequence returned in step1 which contains no elements.

  5. Since Single() is not able to fetch a single element from the sequence returned in step1, it throws an error.

Fix:

Make sure the query (from p in dc.BlogPosts where p.BlogPostID == ID select p)

returns a sequence with at least one element.

Remove the complete styling of an HTML button/submit

I think this provides a more thorough approach:

_x000D_
_x000D_
button, input[type="submit"], input[type="reset"] {_x000D_
 background: none;_x000D_
 color: inherit;_x000D_
 border: none;_x000D_
 padding: 0;_x000D_
 font: inherit;_x000D_
 cursor: pointer;_x000D_
 outline: inherit;_x000D_
}
_x000D_
<button>Example</button>
_x000D_
_x000D_
_x000D_

Pip error: Microsoft Visual C++ 14.0 is required

I faced the same problem. Found the fix here.

Basically just install this.

shasum output:

3e0de8af516c15547602977db939d8c2e44fcc0b  visualcppbuildtools_full.exe

md5sum output:

MD5 (visualcppbuildtools_full.exe) = 8d4afd3b226babecaa4effb10d69eb2e

Run your pip installation command again. If everything works fine, its good. Or you might face the following error like me:

Finished generating code
    LINK : fatal error LNK1158: cannot run 'rc.exe'
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1158

Found the fix for the above problem here: Visual Studio can't build due to rc.exe

That basically says

Add this to your PATH environment variables:

C:\Program Files (x86)\Windows Kits\8.1\bin\x86

Copy these files:

rc.exe
rcdll.dll

From

C:\Program Files (x86)\Windows Kits\8.1\bin\x86

To

C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin

It works like a charm

What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

It is up to the browser but they behave in similar ways.

I have tested FF, IE7, Opera and Chrome.

F5 usually updates the page only if it is modified. The browser usually tries to use all types of cache as much as possible and adds an "If-modified-since" header to the request. Opera differs by sending a "Cache-Control: no-cache".

CTRL-F5 is used to force an update, disregarding any cache. IE7 adds an "Cache-Control: no-cache", as does FF, which also adds "Pragma: no-cache". Chrome does a normal "If-modified-since" and Opera ignores the key.

If I remember correctly it was Netscape which was the first browser to add support for cache-control by adding "Pragma: No-cache" when you pressed CTRL-F5.

Edit: Updated table

The table below is updated with information on what will happen when the browser's refresh-button is clicked (after a request by Joel Coehoorn), and the "max-age=0" Cache-control-header.

Updated table, 27 September 2010

+------------------------------------------------------------+
¦  UPDATED   ¦                Firefox 3.x                    ¦
¦27 SEP 2010 ¦  +--------------------------------------------¦
¦            ¦  ¦             MSIE 8, 7                      ¦
¦ Version 3  ¦  ¦  +-----------------------------------------¦
¦            ¦  ¦  ¦          Chrome 6.0                     ¦
¦            ¦  ¦  ¦  +--------------------------------------¦
¦            ¦  ¦  ¦  ¦       Chrome 1.0                     ¦
¦            ¦  ¦  ¦  ¦  +-----------------------------------¦
¦            ¦  ¦  ¦  ¦  ¦    Opera 10, 9                    ¦
¦            ¦  ¦  ¦  ¦  ¦  +--------------------------------¦
¦            ¦  ¦  ¦  ¦  ¦  ¦                                ¦
+------------+--+--+--+--+--+--------------------------------¦
¦          F5¦IM¦I ¦IM¦IM¦C ¦                                ¦
¦    SHIFT-F5¦- ¦- ¦CP¦IM¦- ¦ Legend:                        ¦
¦     CTRL-F5¦CP¦C ¦CP¦IM¦- ¦ I = "If-Modified-Since"        ¦
¦      ALT-F5¦- ¦- ¦- ¦- ¦*2¦ P = "Pragma: No-cache"         ¦
¦    ALTGR-F5¦- ¦I ¦- ¦- ¦- ¦ C = "Cache-Control: no-cache"  ¦
+------------+--+--+--+--+--¦ M = "Cache-Control: max-age=0" ¦
¦      CTRL-R¦IM¦I ¦IM¦IM¦C ¦ - = ignored                    ¦
¦CTRL-SHIFT-R¦CP¦- ¦CP¦- ¦- ¦                                ¦
+------------+--+--+--+--+--¦                                ¦
¦       Click¦IM¦I ¦IM¦IM¦C ¦ With 'click' I refer to a      ¦
¦ Shift-Click¦CP¦I ¦CP¦IM¦C ¦ mouse click on the browsers    ¦
¦  Ctrl-Click¦*1¦C ¦CP¦IM¦C ¦ refresh-icon.                  ¦
¦   Alt-Click¦IM¦I ¦IM¦IM¦C ¦                                ¦
¦ AltGr-Click¦IM¦I ¦- ¦IM¦- ¦                                ¦
+------------------------------------------------------------+

Versions tested:

  • Firefox 3.1.6 and 3.0.6 (WINXP)
  • MSIE 8.0.6001 and 7.0.5730.11 (WINXP)
  • Chrome 6.0.472.63 and 1.0.151.48 (WINXP)
  • Opera 10.62 and 9.61 (WINXP)

Notes:

  1. Version 3.0.6 sends I and C, but 3.1.6 opens the page in a new tab, making a normal request with only "I".

  2. Version 10.62 does nothing. 9.61 might do C unless it was a typo in my old table.

Note about Chrome 6.0.472: If you do a forced reload (like CTRL-F5) it behaves like the url is internally marked to always do a forced reload. The flag is cleared if you go to the address bar and press enter.

Vim: faster way to select blocks of text in visual mode

v%

will select the whole block.

Play with also:

v}, vp, vs, etc.

See help:

:help text-objects

which lists the different ways to select letters, words, sentences, paragraphs, blocks, and so on.

How do you reverse a string in place in JavaScript?

Here's a basic ES6 immutable example without using Array.prototype.reverse:

_x000D_
_x000D_
// :: reverse = String -> String_x000D_
const reverse = s => [].reduceRight.call(s, (a, b) => a + b)_x000D_
_x000D_
console.log(reverse('foo')) // => 'oof'_x000D_
console.log(reverse('bar')) // => 'rab'_x000D_
console.log(reverse('foo-bar')) // => 'rab-oof'
_x000D_
_x000D_
_x000D_

Is it possible to reference one CSS rule within another?

I had this problem yesterday. @Quentin's answer is ok:

No, you cannot reference one rule-set from another.

but I made a javascript function to simulate inheritance in css (like .Net):

_x000D_
_x000D_
    var inherit_array;_x000D_
    var inherit;_x000D_
    inherit_array = [];_x000D_
    Array.from(document.styleSheets).forEach(function (styleSheet_i, index) {_x000D_
        Array.from(styleSheet_i.cssRules).forEach(function (cssRule_i, index) {_x000D_
            if (cssRule_i.style != null) {_x000D_
                inherit = cssRule_i.style.getPropertyValue("--inherits").trim();_x000D_
            } else {_x000D_
                inherit = "";_x000D_
            }_x000D_
            if (inherit != "") {_x000D_
                inherit_array.push({ selector: cssRule_i.selectorText, inherit: inherit });_x000D_
            }_x000D_
        });_x000D_
    });_x000D_
    Array.from(document.styleSheets).forEach(function (styleSheet_i, index) {_x000D_
        Array.from(styleSheet_i.cssRules).forEach(function (cssRule_i, index) {_x000D_
            if (cssRule_i.selectorText != null) {_x000D_
                inherit_array.forEach(function (inherit_i, index) {_x000D_
                    if (cssRule_i.selectorText.split(", ").includesMember(inherit_i.inherit.split(", ")) == true) {_x000D_
                        cssRule_i.selectorText = cssRule_i.selectorText + ", " + inherit_i.selector;_x000D_
                    }_x000D_
                });_x000D_
            }_x000D_
        });_x000D_
    });
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
Array.prototype.includesMember = function (arr2) {_x000D_
    var arr1;_x000D_
    var includes;_x000D_
    arr1 = this;_x000D_
    includes = false;_x000D_
    arr1.forEach(function (arr1_i, index) {_x000D_
        if (arr2.includes(arr1_i) == true) {_x000D_
            includes = true;_x000D_
        }_x000D_
    });_x000D_
    return includes;_x000D_
}
_x000D_
_x000D_
_x000D_

and equivalent css:

_x000D_
_x000D_
.test {_x000D_
    background-color: yellow;_x000D_
}_x000D_
_x000D_
.productBox, .imageBox {_x000D_
    --inherits: .test;_x000D_
    display: inline-block;_x000D_
}
_x000D_
_x000D_
_x000D_

and equivalent HTML :

_x000D_
_x000D_
<div class="imageBox"></div>
_x000D_
_x000D_
_x000D_

I tested it and worked for me, even if rules are in different css files.

Update: I found a bug in hierarchichal inheritance in this solution, and am solving the bug very soon .

How to open the second form?

//To open the form

Form2 form2 = new Form2();

form2.Show();
// And to close
form2.Close();

Hope this helps

How do you extract IP addresses from files using a regex in a linux shell?

You could use grep to pull them out.

grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' file.txt

JQuery .each() backwards

I prefer creating a reverse plug-in eg

jQuery.fn.reverse = function(fn) {       
   var i = this.length;

   while(i--) {
       fn.call(this[i], i, this[i])
   }
};

Usage eg:

$('#product-panel > div').reverse(function(i, e) {
    alert(i);
    alert(e);
});

Script to Change Row Color when a cell changes text

I think simpler (though without a script) assuming the Status column is ColumnS.

Select ColumnS and clear formatting from it. Select entire range to be formatted and Format, Conditional formatting..., Format cells if... Custom formula is and:

=and($S1<>"",search("Complete",$S1)>0)

with fill of choice and Done.

This is not case sensitive (change search to find for that) and will highlight a row where ColumnS contains the likes of Now complete (though also Not yet complete).

Adding a Method to an Existing Object Instance

What you're looking for is setattr I believe. Use this to set an attribute on an object.

>>> def printme(s): print repr(s)
>>> class A: pass
>>> setattr(A,'printme',printme)
>>> a = A()
>>> a.printme() # s becomes the implicit 'self' variable
< __ main __ . A instance at 0xABCDEFG>

iterating over and removing from a map

As of Java 8 you could do this as follows:

map.entrySet().removeIf(e -> <boolean expression>);

Oracle Docs: entrySet()

The set is backed by the map, so changes to the map are reflected in the set, and vice-versa

Delete all rows with timestamp older than x days

DELETE FROM on_search 
WHERE search_date < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 180 DAY))

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

I had the same problem, and all the solutions from SO or Google didn't work for me. Usually, setNeedsDisplay does work, but when it doesn't...
I've tried calling setNeedsDisplay of the view just every possible way from every possible threads and stuff - still no success. We know, as Rob said, that

"this needs to be drawn in the next draw cycle."

But for some reason it wouldn't draw this time. And the only solution I've found is calling it manually after some time, to let anything that blocks the draw pass away, like this:

dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 
                                        (int64_t)(0.005 * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
    [viewToRefresh setNeedsDisplay];
});

It's a good solution if you don't need the view to redraw really often. Otherwise, if you're doing some moving (action) stuff, there is usually no problems with just calling setNeedsDisplay.

I hope it will help someone who is lost there, like I was.

How to create Password Field in Model Django

Use widget as PasswordInput

from django import forms
class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)
    class Meta:
        model = User

What is the difference between a symbolic link and a hard link?

I add on Nick's question: when are hard links useful or necessary? The only application that comes to my mind, in which symbolic links wouldn't do the job, is providing a copy of a system file in a chrooted environment.

ActionBarCompat: java.lang.IllegalStateException: You need to use a Theme.AppCompat

I encountered this error when I was trying to create a DialogBox when some action is taken inside the CustomAdapter class. This was not an Activity but an Adapter class. After 36 hrs of efforts and looking up for solutions, I came up with this.

Send the Activity as a parameter while calling the CustomAdapter.

CustomAdapter ca = new CustomAdapter(MyActivity.this,getApplicationContext(),records);

Define the variables in the custom Adapter.

Activity parentActivity;
Context context;

Call the constructor like this.

public CustomAdapter(Activity parentActivity,Context context,List<Record> records){
    this.parentActivity=parentActivity;
    this.context=context;
    this.records=records;
}

And finally when creating the dialog box inside the adapter class, do it like this.

AlertDialog ad = new AlertDialog.Builder(parentActivity).setTitle("Your title");

and so on..

I hope this helps you

Is a view faster than a simple query?

Definitely a view is better than a nested query for SQL Server. Without knowing exactly why it is better (until I read Mark Brittingham's post), I had run some tests and experienced almost shocking performance improvements when using a view versus a nested query. After running each version of the query several hundred times in a row, the view version of the query completed in half the time. I'd say that's proof enough for me.

How to use Fiddler to monitor WCF service

This is straightforward if you have control over the client that is sending the communications. All you need to do is set the HttpProxy on the client-side service class.

I did this, for example, to trace a web service client running on a smartphone. I set the proxy on that client-side connection to the IP/port of Fiddler, which was running on a PC on the network. The smartphone app then sent all of its outgoing communication to the web service, through Fiddler.

This worked perfectly.

If your client is a WCF client, then see this Q&A for how to set the proxy.

Even if you don't have the ability to modify the code of the client-side app, you may be able to set the proxy administratively, depending on the webservices stack your client uses.

How to detect Adblock on my website?

I understand your tension and you can check if element has been created by script or element is hidden. And if we speak about ad-blocking you can count only on the element visibility, not on the element presence.

Element created with third-party script will never be present, that if script is not reachable at the moment (DNS error, remote web server error, offline web page preload, etc), and you'll always get false positive.

All other answers with checks are correct, but keep this in mind.

Two dimensional array list

A 2d array is simply an array of arrays. The analog for lists is simply a List of Lists.

ArrayList<ArrayList<String>> myList = new ArrayList<ArrayList<String>>();

I'll admit, it's not a pretty solution, especially if you go for a 3 or more dimensional structure.

How can I listen for a click-and-hold in jQuery?

Presumably you could kick off a setTimeout call in mousedown, and then cancel it in mouseup (if mouseup happens before your timeout completes).

However, looks like there is a plugin: longclick.

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

How to change the Push and Pop animations in a navigation based app

This is how I've always managed to complete this task.

For Push:

MainView *nextView=[[MainView alloc] init];
[UIView  beginAnimations:nil context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:0.75];
[self.navigationController pushViewController:nextView animated:NO];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:NO];
[UIView commitAnimations];
[nextView release];

For Pop:

[UIView  beginAnimations:nil context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:0.75];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.navigationController.view cache:NO];
[UIView commitAnimations];

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelay:0.375];
[self.navigationController popViewControllerAnimated:NO];
[UIView commitAnimations];


I still get a lot of feedback from this so I'm going to go ahead and update it to use animation blocks which is the Apple recommended way to do animations anyway.

For Push:

MainView *nextView = [[MainView alloc] init];
[UIView animateWithDuration:0.75
                         animations:^{
                             [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
                             [self.navigationController pushViewController:nextView animated:NO];
                             [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:NO];
                         }];

For Pop:

[UIView animateWithDuration:0.75
                         animations:^{
                             [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
                             [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.navigationController.view cache:NO];
                         }];
[self.navigationController popViewControllerAnimated:NO];

How do I view Android application specific cache?

You may use this command for listing the files for your own debuggable apk:

adb shell run-as com.corp.appName ls /data/data/com.corp.appName/cache

And this script for pulling from cache:

#!/bin/sh
adb shell "run-as com.corp.appName cat '/data/data/com.corp.appNamepp/$1' > '/sdcard/$1'"
adb pull "/sdcard/$1"
adb shell "rm '/sdcard/$1'"

Then you can pull a file from cache like this:

./pull.sh cache/someCachedData.txt

Root is not required.

Tracing XML request/responses with JAX-WS

Following options enable logging of all communication to the console (technically, you only need one of these, but that depends on the libraries you use, so setting all four is safer option). You can set it in the code like in example, or as command line parameter using -D or as environment variable as Upendra wrote.

System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump", "true");
System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dumpTreshold", "999999");

See question Tracing XML request/responses with JAX-WS when error occurs for details.

Is quitting an application frowned upon?

You have probably spent many years writing "proper" programs for "proper" computers. You say you are learning to program in Android. This is just one of the things you have to learn. You can't spent years doing watercolour painting and assume that oil painting works exactly the same way. This was the very least of the things that were new concepts to me when I wrote my first app eight years ago.

How to check encoding of a CSV file

Or you can execute in python console or in Jupyter Notebook:

import csv
data = open("file.csv","r") 
data

You will see information about the data object like this:

<_io.TextIOWrapper name='arch.csv' mode='r' encoding='cp1250'>

As you can see it contains encoding infotmation.

How do I enable C++11 in gcc?

I think you could do it using a specs file.

Under MinGW you could run
gcc -dumpspecs > specs

Where it says

*cpp:
%{posix:-D_POSIX_SOURCE} %{mthreads:-D_MT}

You change it to

*cpp:
%{posix:-D_POSIX_SOURCE} %{mthreads:-D_MT} -std=c++11

And then place it in
/mingw/lib/gcc/mingw32/<version>/specs

I'm sure you could do the same without a MinGW build. Not sure where to place the specs file though.

The folder is probably either /gcc/lib/ or /gcc/.

How to get the selected index of a RadioGroup in Android

try this

        RadioGroup  group= (RadioGroup) getView().findViewById(R.id.radioGroup);
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                View radioButton = radioGroup.findViewById(i);
                int index = radioGroup.indexOfChild(radioButton);
            }
        });

Setting background-image using jQuery CSS property

You probably want this (to make it like a normal CSS background-image declaration):

$('myObject').css('background-image', 'url(' + imageUrl + ')');

Should I use PATCH or PUT in my REST API?

The R in REST stands for resource

(Which isn't true, because it stands for Representational, but it's a good trick to remember the importance of Resources in REST).

About PUT /groups/api/v1/groups/{group id}/status/activate: you are not updating an "activate". An "activate" is not a thing, it's a verb. Verbs are never good resources. A rule of thumb: if the action, a verb, is in the URL, it probably is not RESTful.

What are you doing instead? Either you are "adding", "removing" or "updating" an activation on a Group, or if you prefer: manipulating a "status"-resource on a Group. Personally, I'd use "activations" because they are less ambiguous than the concept "status": creating a status is ambiguous, creating an activation is not.

  • POST /groups/{group id}/activation Creates (or requests the creation of) an activation.
  • PATCH /groups/{group id}/activation Updates some details of an existing activation. Since a group has only one activation, we know what activation-resource we are referring to.
  • PUT /groups/{group id}/activation Inserts-or-replaces the old activation. Since a group has only one activation, we know what activation-resource we are referring to.
  • DELETE /groups/{group id}/activation Will cancel, or remove the activation.

This pattern is useful when the "activation" of a Group has side-effects, such as payments being made, mails being sent and so on. Only POST and PATCH may have such side-effects. When e.g. a deletion of an activation needs to, say, notify users over mail, DELETE is not the right choice; in that case you probably want to create a deactivation resource: POST /groups/{group_id}/deactivation.

It is a good idea to follow these guidelines, because this standard contract makes it very clear for your clients, and all the proxies and layers between the client and you, know when it is safe to retry, and when not. Let's say the client is somewhere with flaky wifi, and its user clicks on "deactivate", which triggers a DELETE: If that fails, the client can simply retry, until it gets a 404, 200 or anything else it can handle. But if it triggers a POST to deactivation it knows not to retry: the POST implies this.
Any client now has a contract, which, when followed, will protect against sending out 42 emails "your group has been deactivated", simply because its HTTP-library kept retrying the call to the backend.

Updating a single attribute: use PATCH

PATCH /groups/{group id}

In case you wish to update an attribute. E.g. the "status" could be an attribute on Groups that can be set. An attribute such as "status" is often a good candidate to limit to a whitelist of values. Examples use some undefined JSON-scheme:

PATCH /groups/{group id} { "attributes": { "status": "active" } }
response: 200 OK

PATCH /groups/{group id} { "attributes": { "status": "deleted" } }
response: 406 Not Acceptable

Replacing the resource, without side-effects use PUT.

PUT /groups/{group id}

In case you wish to replace an entire Group. This does not necessarily mean that the server actually creates a new group and throws the old one out, e.g. the ids might remain the same. But for the clients, this is what PUT can mean: the client should assume he gets an entirely new item, based on the server's response.

The client should, in case of a PUT request, always send the entire resource, having all the data that is needed to create a new item: usually the same data as a POST-create would require.

PUT /groups/{group id} { "attributes": { "status": "active" } }
response: 406 Not Acceptable

PUT /groups/{group id} { "attributes": { "name": .... etc. "status": "active" } }
response: 201 Created or 200 OK, depending on whether we made a new one.

A very important requirement is that PUT is idempotent: if you require side-effects when updating a Group (or changing an activation), you should use PATCH. So, when the update results in e.g. sending out a mail, don't use PUT.

lvalue required as left operand of assignment

You are trying to assign a value to a function, which is not possible in C. Try the comparison operator instead:

if (strcmp("hello", "hello") == 0)

cannot call member function without object

If you want to call them like that, you should declare them static.

how to remove the bold from a headline?

The heading looks bold because of its large size, if you have applied bold or want to change behaviour, you can do:

h1 { font-weight:normal; }

More: http://www.w3.org/TR/css3-fonts/#font-weight-prop

How to pull specific directory with git

It's not possible. You need pull all repository or nothing.

How to check View Source in Mobile Browsers (Both Android && Feature Phone)

The view-source url prefix trick didn't work for me using chrome on an iphone. There are apps I could have installed to do this I guess but for whatever reason I just preferred to do it myself rather than install 'yet another app'.

I found this nice quick tutorial for how to setup a bookmark on mobile safari that will automatically open the view source of a page: https://appletoolbox.com/2014/03/how-to-view-webpage-html-source-codes-on-ipad-iphone-no-app-required/

It worked flawlessly for me and now I have it set as a permanent bookmark any time I want, with no app installed.

Edit: There are basically 6 steps which should work for either Chrome or Safari. Instructions for Safari are:

  1. Open Safari and browse to an arbitrary page.
  2. Select the "Share" (or action") button in Safari (looks like a square with an arrow coming out of the top).
  3. Select "Add Bookmark"
  4. Delete the page title and replace it with something useful like "Show Page Source". Click Save.
  5. Next browse to this exact Stack Overflow answer on your phone and copy the javascript code below to your phone clipboard (code credit: Rob Flaherty):
javascript:(function(){var a=window.open('about:blank').document;a.write('<!DOCTYPE html><html><head><title>Source of '+location.href+'</title><meta name="viewport" content="width=device-width" /></head><body></body></html>');a.close();var b=a.body.appendChild(a.createElement('pre'));b.style.overflow='auto';b.style.whiteSpace='pre-wrap';b.appendChild(a.createTextNode(document.documentElement.innerHTML))})();
  1. Open the "Bookmarks" in Safari and opt to Edit the newly created Show Page Source bookmark. Delete whatever was previously saved in the Address field and instead paste in the Javascript code. Save it.
  2. (Optional) Profit!

How to change CSS using jQuery?

To clear things up a little, since some of the answers are providing incorrect information:


The jQuery .css() method allows the use of either DOM or CSS notation in many cases. So, both backgroundColor and background-color will get the job done.

Additionally, when you call .css() with arguments you have two choices as to what the arguments can be. They can either be 2 comma separated strings representing a css property and its value, or it can be a Javascript object containing one or more key value pairs of CSS properties and values.

In conclusion the only thing wrong with your code is a missing }. The line should read:

$("#myParagraph").css({"backgroundColor":"black","color":"white"});

You cannot leave the curly brackets out, but you may leave the quotes out from around backgroundColor and color. If you use background-color you must put quotes around it because of the hyphen.

In general, it's a good habit to quote your Javascript objects, since problems can arise if you do not quote an existing keyword.


A final note is that about the jQuery .ready() method

$(handler);

is synonymous with:

$(document).ready(handler);

as well as with a third not recommended form.

This means that $(init) is completely correct, since init is the handler in that instance. So, init will be fired when the DOM is constructed.

dlib installation on Windows 10

It is basically a two-step process:

  1. install cmap
pip install cmap
  1. install dlib
pip install https://pypi.python.org/packages/da/06/bd3e241c4eb0a662914b3b4875fc52dd176a9db0d4a2c915ac2ad8800e9e/dlib-19.7.0-cp36-cp36m-win_amd64.whl#md5=b7330a5b2d46420343fbed5df69e6a3f

How to JSON serialize sets?

Shortened version of @AnttiHaapala:

json.dumps(dict_with_sets, default=lambda x: list(x) if isinstance(x, set) else x)

How to _really_ programmatically change primary and accent color in Android Lollipop?

USE A TOOLBAR

You can set a custom toolbar item color dynamically by creating a custom toolbar class:

package view;

import android.app.Activity;
import android.content.Context;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.support.v7.internal.view.menu.ActionMenuItemView;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomToolbar extends Toolbar{

    public CustomToolbar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // TODO Auto-generated constructor stub
    }

    public CustomToolbar(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public CustomToolbar(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        ctxt = context;
    }

    int itemColor;
    Context ctxt;

    @Override 
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        Log.d("LL", "onLayout");
        super.onLayout(changed, l, t, r, b);
        colorizeToolbar(this, itemColor, (Activity) ctxt);
    } 

    public void setItemColor(int color){
        itemColor = color;
        colorizeToolbar(this, itemColor, (Activity) ctxt);
    }



    /**
     * Use this method to colorize toolbar icons to the desired target color
     * @param toolbarView toolbar view being colored
     * @param toolbarIconsColor the target color of toolbar icons
     * @param activity reference to activity needed to register observers
     */
    public static void colorizeToolbar(Toolbar toolbarView, int toolbarIconsColor, Activity activity) {
        final PorterDuffColorFilter colorFilter
                = new PorterDuffColorFilter(toolbarIconsColor, PorterDuff.Mode.SRC_IN);

        for(int i = 0; i < toolbarView.getChildCount(); i++) {
            final View v = toolbarView.getChildAt(i);

            doColorizing(v, colorFilter, toolbarIconsColor);
        }

      //Step 3: Changing the color of title and subtitle.
        toolbarView.setTitleTextColor(toolbarIconsColor);
        toolbarView.setSubtitleTextColor(toolbarIconsColor);
    }

    public static void doColorizing(View v, final ColorFilter colorFilter, int toolbarIconsColor){
        if(v instanceof ImageButton) {
            ((ImageButton)v).getDrawable().setAlpha(255);
            ((ImageButton)v).getDrawable().setColorFilter(colorFilter);
        }

        if(v instanceof ImageView) {
            ((ImageView)v).getDrawable().setAlpha(255);
            ((ImageView)v).getDrawable().setColorFilter(colorFilter);
        }

        if(v instanceof AutoCompleteTextView) {
            ((AutoCompleteTextView)v).setTextColor(toolbarIconsColor);
        }

        if(v instanceof TextView) {
            ((TextView)v).setTextColor(toolbarIconsColor);
        }

        if(v instanceof EditText) {
            ((EditText)v).setTextColor(toolbarIconsColor);
        }

        if (v instanceof ViewGroup){
            for (int lli =0; lli< ((ViewGroup)v).getChildCount(); lli ++){
                doColorizing(((ViewGroup)v).getChildAt(lli), colorFilter, toolbarIconsColor);
            }
        }

        if(v instanceof ActionMenuView) {
            for(int j = 0; j < ((ActionMenuView)v).getChildCount(); j++) {

                //Step 2: Changing the color of any ActionMenuViews - icons that
                //are not back button, nor text, nor overflow menu icon.
                final View innerView = ((ActionMenuView)v).getChildAt(j);

                if(innerView instanceof ActionMenuItemView) {
                    int drawablesCount = ((ActionMenuItemView)innerView).getCompoundDrawables().length;
                    for(int k = 0; k < drawablesCount; k++) {
                        if(((ActionMenuItemView)innerView).getCompoundDrawables()[k] != null) {
                            final int finalK = k;

                            //Important to set the color filter in seperate thread, 
                            //by adding it to the message queue
                            //Won't work otherwise. 
                            //Works fine for my case but needs more testing

                            ((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter);

//                              innerView.post(new Runnable() {
//                                  @Override
//                                  public void run() {
//                                      ((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter);
//                                  }
//                              });
                        }
                    }
                }
            }
        }
    }



}

then refer to it in your layout file. Now you can set a custom color using

toolbar.setItemColor(Color.Red);

Sources:

I found the information to do this here: How to dynamicaly change Android Toolbar icons color

and then I edited it, improved upon it, and posted it here: GitHub:AndroidDynamicToolbarItemColor

ASP.NET MVC controller actions that return JSON or partial html

    public ActionResult GetExcelColumn()
    {            
            List<string> lstAppendColumn = new List<string>();
            lstAppendColumn.Add("First");
            lstAppendColumn.Add("Second");
            lstAppendColumn.Add("Third");
  return Json(new { lstAppendColumn = lstAppendColumn,  Status = "Success" }, JsonRequestBehavior.AllowGet);
            }
        }

Select method of Range class failed via VBA

Here is a solution worked for me and also, I found all of the above solutions are correct. My excel model got corrupted and which is why my code (similar to this one) stopped working. Here is what worked for me and is working every time-

  1. Calculate the workbook- Formulas->Calculate Now (under calculation section)
  2. Save the workbook
  3. Close and re-open the file. It was fixed and works every time.

How to use ClassLoader.getResources() correctly?

There is no way to recursively search through the classpath. You need to know the Full pathname of a resource to be able to retrieve it in this way. The resource may be in a directory in the file system or in a jar file so it is not as simple as performing a directory listing of "the classpath". You will need to provide the full path of the resource e.g. '/com/mypath/bla.xml'.

For your second question, getResource will return the first resource that matches the given resource name. The order that the class path is searched is given in the javadoc for getResource.

Thymeleaf using path variables to th:href

I think your problem was a typo:

<a th:href="@{'/category/edit/' + ${category.id}}">view</a>

You are using category.id, but in your code is idCategory, as Eddie already pointed out.

This would work for you:

<a th:href="@{'/category/edit/' + ${category.idCategory}}">view</a>

How to track down access violation "at address 00000000"

The accepted answer does not tell the entire story.

Yes, whenever you see zeros, a NULL pointer is involved. That is because NULL is by definition zero. So calling zero NULL may not be saying much.

What is interesting about the message you get is the fact that NULL is mentioned twice. In fact, the message you report looks a little bit like the messages Windows-brand operating systems show the user.

The message says the address NULL tried to read NULL. So what does that mean? Specifically, how does an address read itself?

We typically think of the instructions at an address reading and writing from memory at certain addresses. Knowing that allows us to parse the error message. The message is trying to articulate that the instruction at address NULL tried to read NULL.

Of course, there is no instruction at address NULL, that is why we think of NULL as special in our code. But every instruction can be thought of as commencing with the attempt to read itself. If the CPUs EIP register is at address NULL, then the CPU will attempt to read the opcode for an instruction from address 0x00000000 (NULL). This attempt to read NULL will fail, and generate the message you have received.

In the debugger, notice that EIP equals 0x00000000 when you receive this message. This confirms the description I have given you.

The question then becomes, "why does my program attempt to execute the NULL address." There are three possibilities which spring to mind:

  • You have attempt to make a function call via a function pointer which you have declared, assigned to NULL, never initialized otherwise, and are dereferencing.
  • Similarly, you may be calling an "abstract" C++ method which has a NULL entry in the object's vtable. These are created in your code with the syntax virtual function_name()=0.
  • In your code, a stack buffer has been overflowed while writing zeros. The zeros have been written beyond the end of the stack buffer, over the preserved return address. When the function later executes its ret instruction, the value 0x00000000 (NULL) is loaded from the overwritten memory spot. This type of error, stack overflow, is the eponym of our forum.

Since you mention that you are calling a third-party library, I will point out that it may be a situation of the library expecting you to provide a non-NULL function pointer as input to some API. These are sometimes known as "call back" functions.

You will have to use the debugger to narrow down the cause of your problem further, but the above possiblities should help you solve the riddle.

How to display the function, procedure, triggers source code in postgresql?

Here are few examples from PostgreSQL-9.5

Display list:

  1. Functions: \df+
  2. Triggers : \dy+

Display Definition:

postgres=# \sf
function name is required

postgres=# \sf pg_reload_conf()
CREATE OR REPLACE FUNCTION pg_catalog.pg_reload_conf()
 RETURNS boolean
 LANGUAGE internal
 STRICT
AS $function$pg_reload_conf$function$

postgres=# \sf pg_encoding_to_char
CREATE OR REPLACE FUNCTION pg_catalog.pg_encoding_to_char(integer)
 RETURNS name
 LANGUAGE internal
 STABLE STRICT
AS $function$PG_encoding_to_char$function$

Clear text from textarea with selenium

driver.find_element_by_id('foo').clear()

How to generate class diagram from project in Visual Studio 2013?

Right click on the project in solution explorer or class view window --> "View" --> "View Class Diagram"

Visualizing decision tree in scikit-learn

If, like me, you have a problem installing graphviz, you can visualize the tree by

  1. exporting it with export_graphviz as shown in previous answers
  2. Open the .dot file in a text editor
  3. Copy the piece of code and paste it @ webgraphviz.com

Configuring diff tool with .gitconfig

Adding one of the blocks below works for me to use KDiff3 for my Windows and Linux development environments. It makes for a nice consistent cross-platform diff and merge tool.

Linux

[difftool "kdiff3"]
    path = /usr/bin/kdiff3
    trustExitCode = false
[difftool]
    prompt = false
[diff]
    tool = kdiff3
[mergetool "kdiff3"]
    path = /usr/bin/kdiff3
    trustExitCode = false
[mergetool]
    keepBackup = false
[merge]
    tool = kdiff3

Windows

[difftool "kdiff3"]
    path = C:/Progra~1/KDiff3/kdiff3.exe
    trustExitCode = false
[difftool]
    prompt = false
[diff]
    tool = kdiff3
[mergetool "kdiff3"]
    path = C:/Progra~1/KDiff3/kdiff3.exe
    trustExitCode = false
[mergetool]
    keepBackup = false
[merge]
    tool = kdiff3

How is the java memory pool divided?

Java Heap Memory is part of memory allocated to JVM by Operating System.

Objects reside in an area called the heap. The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected.

enter image description here

You can find more details about Eden Space, Survivor Space, Tenured Space and Permanent Generation in below SE question:

Young , Tenured and Perm generation

PermGen has been replaced with Metaspace since Java 8 release.

Regarding your queries:

  1. Eden Space, Survivor Space, Tenured Space are part of heap memory
  2. Metaspace and Code Cache are part of non-heap memory.

Codecache: The Java Virtual Machine (JVM) generates native code and stores it in a memory area called the codecache. The JVM generates native code for a variety of reasons, including for the dynamically generated interpreter loop, Java Native Interface (JNI) stubs, and for Java methods that are compiled into native code by the just-in-time (JIT) compiler. The JIT is by far the biggest user of the codecache.

Online Internet Explorer Simulators

If you have enough space on your hard-disk in your OS-X of Apple, then you could install virtualbox for Mac-OS-X after download at http://virtualbox.org

Then you would need "only" 100 GB to create with this virtualbox as virtual harddisk. Then install for intentions of tests simply for 1 month-free-testtime a Windows of your choice - Vista or 7 or 8 - together with internet explorer ...

You dont need to buy Windows for this as long as you dont test longer than one month - when testing time is expired it is not tragic at all, you simply can repeat a new testing-time ...

This looks trivial but with virtualbox you have a real-time-testing-area in this case with IE - no matter which version of IE !

extracting days from a numpy.timedelta64 value

You can convert it to a timedelta with a day precision. To extract the integer value of days you divide it with a timedelta of one day.

>>> x = np.timedelta64(2069211000000000, 'ns')
>>> days = x.astype('timedelta64[D]')
>>> days / np.timedelta64(1, 'D')
23

Or, as @PhillipCloud suggested, just days.astype(int) since the timedelta is just a 64bit integer that is interpreted in various ways depending on the second parameter you passed in ('D', 'ns', ...).

You can find more about it here.

Undoing a 'git push'

git revert is less dangerous than some of the approaches suggested here:

prompt> git revert 35f6af6f77f116ef922e3d75bc80a4a466f92650
[master 71738a9] Revert "Issue #482 - Fixed bug."
 4 files changed, 30 insertions(+), 42 deletions(-)
prompt> git status
# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
nothing to commit (working directory clean)
prompt>

Replace 35f6af6f77f116ef922e3d75bc80a4a466f92650 with your own commit.

reading from stdin in c++

You have not defined the variable input_line.

Add this:

string input_line;

And add this include.

#include <string>

Here is the full example. I also removed the semi-colon after the while loop, and you should have getline inside the while to properly detect the end of the stream.

#include <iostream>
#include <string>

int main() {
    for (std::string line; std::getline(std::cin, line);) {
        std::cout << line << std::endl;
    }
    return 0;
}

Append a Lists Contents to another List C#

With Linq

var newList = GlobalStrings.Append(localStrings)

Session variables in ASP.NET MVC

If you are using asp.net mvc, here is a simple way to access the session.

From a Controller:

{Controller}.ControllerContext.HttpContext.Session["{name}"]

From a View:

<%=Session["{name}"] %>

This is definitely not the best way to access your session variables, but it is a direct route. So use it with caution (preferably during rapid prototyping), and use a Wrapper/Container and OnSessionStart when it becomes appropriate.

HTH

How to set corner radius of imageView?

import UIKit

class BorderImage: UIImageView {

    override func awakeFromNib() {
        self.layoutIfNeeded()
        layer.cornerRadius = self.frame.height / 10.0
        layer.masksToBounds = true
    }
}

Based on @DCDC's answer

C dynamically growing array

These posts apparently are in the wrong order! This is #1 in a series of 3 posts. Sorry.

In attempting to use Lie Ryan's code, I had problems retrieving stored information. The vector's elements are not stored contiguously,as you can see by "cheating" a bit and storing the pointer to each element's address (which of course defeats the purpose of the dynamic array concept) and examining them.

With a bit of tinkering, via:

ss_vector* vector; // pull this out to be a global vector

// Then add the following to attempt to recover stored values.

int return_id_value(int i,apple* aa) // given ptr to component,return data item
{   printf("showing apple[%i].id = %i and  other_id=%i\n",i,aa->id,aa->other_id);
    return(aa->id);
}

int Test(void)  // Used to be "main" in the example
{   apple* aa[10]; // stored array element addresses
    vector = ss_init_vector(sizeof(apple));
    // inserting some items
    for (int i = 0; i < 10; i++)
    {   aa[i]=init_apple(i);
        printf("apple id=%i and  other_id=%i\n",aa[i]->id,aa[i]->other_id);
        ss_vector_append(vector, aa[i]);
     }   
 // report the number of components
 printf("nmbr of components in vector = %i\n",(int)vector->size);
 printf(".*.*array access.*.component[5] = %i\n",return_id_value(5,aa[5]));
 printf("components of size %i\n",(int)sizeof(apple));
 printf("\n....pointer initial access...component[0] = %i\n",return_id_value(0,(apple *)&vector[0]));
 //.............etc..., followed by
 for (int i = 0; i < 10; i++)
 {   printf("apple[%i].id = %i at address %i, delta=%i\n",i,    return_id_value(i,aa[i]) ,(int)aa[i],(int)(aa[i]-aa[i+1]));
 }   
// don't forget to free it
ss_vector_free(vector);
return 0;
}

It's possible to access each array element without problems, as long as you know its address, so I guess I'll try adding a "next" element and use this as a linked list. Surely there are better options, though. Please advise.

How to call window.alert("message"); from C#?

I'm not sure if I understand but I'm guessing that you're trying to show a MessageBox from ASP.Net?

If so, this code project article might be helpful: Simple MessageBox functionality in ASP.NET

How to add a single item to a Pandas Series

TLDR: do not append items to a series one by one, better extend with an ordered collection

I think the question in its current form is a bit tricky. And the accepted answer does answer the question. But the more I use pandas, the more I understand that it's a bad idea to append items to a Series one by one. I'll try to explain why for pandas beginners.

You might think that appending data to a given Series might allow you to reuse some resources, but in reality a Series is just a container that stores a relation between an index and a values array. Each is a numpy.array under the hood, and the index is immutable. When you add to Series an item with a label that is missing in the index, a new index with size n+1 is created, and a new values values array of the same size. That means that when you append items one by one, you create two more arrays of the n+1 size on each step.

By the way, you can not append a new item by position (you will get an IndexError) and the label in an index does not have to be unique, that is when you assign a value with a label, you assign the value to all existing items with the the label, and a new row is not appended in this case. This might lead to subtle bugs.

The moral of the story is that you should not append data one by one, you should better extend with an ordered collection. The problem is that you can not extend a Series inplace. That is why it is better to organize your code so that you don't need to update a specific instance of a Series by reference.

If you create labels yourself and they are increasing, the easiest way is to add new items to a dictionary, then create a new Series from the dictionary (it sorts the keys) and append the Series to an old one. If the keys are not increasing, then you will need to create two separate lists for the new labels and the new values.

Below are some code samples:

In [1]: import pandas as pd
In [2]: import numpy as np

In [3]: s = pd.Series(np.arange(4)**2, index=np.arange(4))

In [4]: s
Out[4]:
0    0
1    1
2    4
3    9
dtype: int64

In [6]: id(s.index), id(s.values)
Out[6]: (4470549648, 4470593296)

When we update an existing item, the index and the values array stay the same (if you do not change the type of the value)

In [7]: s[2] = 14  

In [8]: id(s.index), id(s.values)
Out[8]: (4470549648, 4470593296)

But when you add a new item, a new index and a new values array is generated:

In [9]: s[4] = 16

In [10]: s
Out[10]:
0     0
1     1
2    14
3     9
4    16
dtype: int64

In [11]: id(s.index), id(s.values)
Out[11]: (4470548560, 4470595056)

That is if you are going to append several items, collect them in a dictionary, create a Series, append it to the old one and save the result:

In [13]: new_items = {item: item**2 for item in range(5, 7)}

In [14]: s2 = pd.Series(new_items)

In [15]: s2  # keys are guaranteed to be sorted!
Out[15]:
5    25
6    36
dtype: int64

In [16]: s = s.append(s2); s
Out[16]:
0     0
1     1
2    14
3     9
4    16
5    25
6    36
dtype: int64

Get current time in seconds since the Epoch on Linux, Bash

Just to add.

Get the seconds since epoch(Jan 1 1970) for any given date(e.g Oct 21 1973).

date -d "Oct 21 1973" +%s


Convert the number of seconds back to date

date --date @120024000


The command date is pretty versatile. Another cool thing you can do with date(shamelessly copied from date --help). Show the local time for 9AM next Friday on the west coast of the US

date --date='TZ="America/Los_Angeles" 09:00 next Fri'

Better yet, take some time to read the man page http://man7.org/linux/man-pages/man1/date.1.html

What is Domain Driven Design?

I do not want to repeat others' answers, so, in short I explain some common misunderstanding

  • Practical resource: PATTERNS, PRINCIPLES, AND PRACTICES OF DOMAIN-DRIVEN DESIGN by Scott Millett
  • It is a methodology for complicated business systems. It takes all the technical matters out when communicating with business experts
  • It provides an extensive understanding of (simplified and distilled model of) business across the whole dev team.
  • it keeps business model in sync with code model by using ubiquitous language (the language understood by the whole dev team, business experts, business analysts, ...), which is used for communication within the dev team or dev with other teams
  • It has nothing to do with Project Management. Although it can be perfectly used in project management methods like Agile.
  • You should avoid using it all across your project

    DDD stresses the need to focus the most effort on the core subdomain. The core subdomain is the area of your product that will be the difference between it being a success and it being a failure. It’s the product’s unique selling point, the reason it is being built rather than bought.

    Basically, it is because it takes too much time and effort. So, it is suggested to break down the whole domain into subdomain and just apply it in those with high business value. (ex not in generic subdomain like email, ...)

  • It is not object oriented programming. It is mostly problem solving approach and (sometimes) you do not need to use OO patterns (such as Gang of Four) in your domain models. Simply because it can not be understood by Business Experts (they do not know much about Factory, Decorator, ...). There are even some patterns in DDD (such as The Transaction Script, Table Module) which are not 100% in line with OO concepts.

How to store Configuration file and read it using React

If you used Create React App, you can set an environment variable using a .env file. The documentation is here:

https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

Basically do something like this in the .env file at the project root.

REACT_APP_NOT_SECRET_CODE=abcdef

Note that the variable name must start with REACT_APP_

You can access it from your component with

process.env.REACT_APP_NOT_SECRET_CODE

"unadd" a file to svn before commit

Full process (Unix svn package):

Check files are not in SVN:

> svn st -u folder 
? folder

Add all (including ignored files):

> svn add folder
A   folder
A   folder/file1.txt
A   folder/folder2
A   folder/folder2/file2.txt
A   folder/folderToIgnore
A   folder/folderToIgnore/fileToIgnore1.txt
A   fileToIgnore2.txt

Remove "Add" Flag to All * Ignore * files:

> cd folder

> svn revert --recursive folderToIgnore
Reverted 'folderToIgnore'
Reverted 'folderToIgnore/fileToIgnore1.txt'


> svn revert fileToIgnore2.txt
Reverted 'fileToIgnore2.txt'

Edit svn ignore on folder

svn propedit svn:ignore .

Add two singles lines with just the following:

folderToIgnore
fileToIgnore2.txt

Check which files will be upload and commit:

> cd ..

> svn st -u
A   folder
A   folder/file1.txt
A   folder/folder2
A   folder/folder2/file2.txt


> svn ci -m "Commit message here"

Take the content of a list and append it to another list

You probably want

list2.extend(list1)

instead of

list2.append(list1)

Here's the difference:

>>> a = range(5)
>>> b = range(3)
>>> c = range(2)
>>> b.append(a)
>>> b
[0, 1, 2, [0, 1, 2, 3, 4]]
>>> c.extend(a)
>>> c
[0, 1, 0, 1, 2, 3, 4]

Since list.extend() accepts an arbitrary iterable, you can also replace

for line in mylog:
    list1.append(line)

by

list1.extend(mylog)

Add Insecure Registry to Docker

For me the solution was to add the registry to here:

/etc/sysconfig/docker-registries

DOCKER_REGISTRIES=''
DOCKER_EXTRA_REGISTRIES='--insecure-registry  b.example.com'

How can I make an entire HTML form "readonly"?

I'd rather use jQuery:

$('#'+formID).find(':input').attr('disabled', 'disabled');

find() would go much deeper till nth nested child than children(), which looks for immediate children only.

Concatenate two slices in Go

Nothing against the other answers, but I found the brief explanation in the docs more easily understandable than the examples in them:

func append

func append(slice []Type, elems ...Type) []Type The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice. It is therefore necessary to store the result of append, often in the variable holding the slice itself:

slice = append(slice, elem1, elem2)
slice = append(slice, anotherSlice...)

As a special case, it is legal to append a string to a byte slice, like this:

slice = append([]byte("hello "), "world"...)

react button onClick redirect page

if you want to redirect to a route on a Click event.

Just do this

In Functional Component

props.history.push('/link')

In Class Component

this.props.history.push('/link')

Example:

<button onClick={()=>{props.history.push('/link')}} >Press</button>

Tested on:

react-router-dom: 5.2.0,

react: 16.12.0

How to connect SQLite with Java?

    import java.sql.ResultSet;
    import java.sql.SQLException;
    import javax.swing.JOptionPane;
    import org.sqlite.SQLiteDataSource;
    import org.sqlite.SQLiteJDBCLoader;

    public class Test {

        public static final boolean Connected() {
            boolean initialize = SQLiteJDBCLoader.initialize();

            SQLiteDataSource dataSource = new SQLiteDataSource();
            dataSource.setUrl("jdbc:sqlite:/home/users.sqlite");
            int i=0;
            try {
                ResultSet executeQuery = dataSource.getConnection()
                        .createStatement().executeQuery("select * from \"Table\"");
                while (executeQuery.next()) {
i++;
                    System.out.println("out: "+executeQuery.getMetaData().getColumnLabel(i));

                }



            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, ex);
            }

            return initialize;

        }

How do I convert from stringstream to string in C++?

From memory, you call stringstream::str() to get the std::string value out.