Programs & Examples On #C++ standard library

In the C++ programming language, the C++ Standard Library is a collection of classes and functions, which may or may not be written in the core language, and are part of the C++

std::string formatting like sprintf

UPDATE 1: added fmt::format tests

I've took my own investigation around methods has introduced here and gain diametrically opposite results versus mentioned here.

I have used 4 functions over 4 methods:

  • variadic function + vsnprintf + std::unique_ptr
  • variadic function + vsnprintf + std::string
  • variadic template function + std::ostringstream + std::tuple + utility::for_each
  • fmt::format function from fmt library

For the test backend the googletest has used.

#include <string>
#include <cstdarg>
#include <cstdlib>
#include <memory>
#include <algorithm>

#include <fmt/format.h>

inline std::string string_format(size_t string_reserve, const std::string fmt_str, ...)
{
    size_t str_len = (std::max)(fmt_str.size(), string_reserve);

    // plain buffer is a bit faster here than std::string::reserve
    std::unique_ptr<char[]> formatted;

    va_list ap;
    va_start(ap, fmt_str);

    while (true) {
        formatted.reset(new char[str_len]);

        const int final_n = vsnprintf(&formatted[0], str_len, fmt_str.c_str(), ap);

        if (final_n < 0 || final_n >= int(str_len))
            str_len += (std::abs)(final_n - int(str_len) + 1);
        else
            break;
    }

    va_end(ap);

    return std::string(formatted.get());
}

inline std::string string_format2(size_t string_reserve, const std::string fmt_str, ...)
{
    size_t str_len = (std::max)(fmt_str.size(), string_reserve);
    std::string str;

    va_list ap;
    va_start(ap, fmt_str);

    while (true) {
        str.resize(str_len);

        const int final_n = vsnprintf(const_cast<char *>(str.data()), str_len, fmt_str.c_str(), ap);

        if (final_n < 0 || final_n >= int(str_len))
            str_len += (std::abs)(final_n - int(str_len) + 1);
        else {
            str.resize(final_n); // do not forget to shrink the size!
            break;
        }
    }

    va_end(ap);

    return str;
}

template <typename... Args>
inline std::string string_format3(size_t string_reserve, Args... args)
{
    std::ostringstream ss;
    if (string_reserve) {
        ss.rdbuf()->str().reserve(string_reserve);
    }
    std::tuple<Args...> t{ args... };
    utility::for_each(t, [&ss](auto & v)
    {
        ss << v;
    });
    return ss.str();
}

The for_each implementation is taken from here: iterate over tuple

#include <type_traits>
#include <tuple>

namespace utility {

    template <std::size_t I = 0, typename FuncT, typename... Tp>
    inline typename std::enable_if<I == sizeof...(Tp), void>::type
        for_each(std::tuple<Tp...> &, const FuncT &)
    {
    }

    template<std::size_t I = 0, typename FuncT, typename... Tp>
    inline typename std::enable_if<I < sizeof...(Tp), void>::type
        for_each(std::tuple<Tp...> & t, const FuncT & f)
    {
        f(std::get<I>(t));
        for_each<I + 1, FuncT, Tp...>(t, f);
    }

}

The tests:

TEST(ExternalFuncs, test_string_format_on_unique_ptr_0)
{
    for (size_t i = 0; i < 1000000; i++) {
        const std::string v = string_format(0, "%s+%u\n", "test test test", 12345);
        UTILITY_SUPPRESS_OPTIMIZATION_ON_VAR(v);
    }
}

TEST(ExternalFuncs, test_string_format_on_unique_ptr_256)
{
    for (size_t i = 0; i < 1000000; i++) {
        const std::string v = string_format(256, "%s+%u\n", "test test test", 12345);
        UTILITY_SUPPRESS_OPTIMIZATION_ON_VAR(v);
    }
}

TEST(ExternalFuncs, test_string_format_on_std_string_0)
{
    for (size_t i = 0; i < 1000000; i++) {
        const std::string v = string_format2(0, "%s+%u\n", "test test test", 12345);
        UTILITY_SUPPRESS_OPTIMIZATION_ON_VAR(v);
    }
}

TEST(ExternalFuncs, test_string_format_on_std_string_256)
{
    for (size_t i = 0; i < 1000000; i++) {
        const std::string v = string_format2(256, "%s+%u\n", "test test test", 12345);
        UTILITY_SUPPRESS_OPTIMIZATION_ON_VAR(v);
    }
}

TEST(ExternalFuncs, test_string_format_on_string_stream_on_variadic_tuple_0)
{
    for (size_t i = 0; i < 1000000; i++) {
        const std::string v = string_format3(0, "test test test", "+", 12345, "\n");
        UTILITY_SUPPRESS_OPTIMIZATION_ON_VAR(v);
    }
}

TEST(ExternalFuncs, test_string_format_on_string_stream_on_variadic_tuple_256)
{
    for (size_t i = 0; i < 1000000; i++) {
        const std::string v = string_format3(256, "test test test", "+", 12345, "\n");
        UTILITY_SUPPRESS_OPTIMIZATION_ON_VAR(v);
    }
}

TEST(ExternalFuncs, test_string_format_on_string_stream_inline_0)
{
    for (size_t i = 0; i < 1000000; i++) {
        std::ostringstream ss;
        ss << "test test test" << "+" << 12345 << "\n";
        const std::string v = ss.str();
        UTILITY_SUPPRESS_OPTIMIZATION_ON_VAR(v);
    }
}

TEST(ExternalFuncs, test_string_format_on_string_stream_inline_256)
{
    for (size_t i = 0; i < 1000000; i++) {
        std::ostringstream ss;
        ss.rdbuf()->str().reserve(256);
        ss << "test test test" << "+" << 12345 << "\n";
        const std::string v = ss.str();
        UTILITY_SUPPRESS_OPTIMIZATION_ON_VAR(v);
    }
}

TEST(ExternalFuncs, test_fmt_format_positional)
{
    for (size_t i = 0; i < 1000000; i++) {
        const std::string v = fmt::format("{0:s}+{1:d}\n", "test test test", 12345);
        UTILITY_SUPPRESS_OPTIMIZATION_ON_VAR(v);
    }
}

TEST(ExternalFuncs, test_fmt_format_named)
{
    for (size_t i = 0; i < 1000000; i++) {
        const std::string v = fmt::format("{first:s}+{second:d}\n", fmt::arg("first", "test test test"), fmt::arg("second", 12345));
        UTILITY_SUPPRESS_OPTIMIZATION_ON_VAR(v);
    }
}

The UTILITY_SUPPRESS_OPTIMIZATION_ON_VAR.

unsued.hpp:

#define UTILITY_SUPPRESS_OPTIMIZATION_ON_VAR(var)   ::utility::unused_param(&var)

namespace utility {

    extern const volatile void * volatile g_unused_param_storage_ptr;

    extern void
#ifdef __GNUC__
    __attribute__((optimize("O0")))
#endif
        unused_param(const volatile void * p);

}

unused.cpp:

namespace utility {

    const volatile void * volatile g_unused_param_storage_ptr = nullptr;

    void
#ifdef __GNUC__
    __attribute__((optimize("O0")))
#endif
        unused_param(const volatile void * p)
    {
        g_unused_param_storage_ptr = p;
    }

}

RESULTS:

[ RUN      ] ExternalFuncs.test_string_format_on_unique_ptr_0
[       OK ] ExternalFuncs.test_string_format_on_unique_ptr_0 (556 ms)
[ RUN      ] ExternalFuncs.test_string_format_on_unique_ptr_256
[       OK ] ExternalFuncs.test_string_format_on_unique_ptr_256 (331 ms)
[ RUN      ] ExternalFuncs.test_string_format_on_std_string_0
[       OK ] ExternalFuncs.test_string_format_on_std_string_0 (457 ms)
[ RUN      ] ExternalFuncs.test_string_format_on_std_string_256
[       OK ] ExternalFuncs.test_string_format_on_std_string_256 (279 ms)
[ RUN      ] ExternalFuncs.test_string_format_on_string_stream_on_variadic_tuple_0
[       OK ] ExternalFuncs.test_string_format_on_string_stream_on_variadic_tuple_0 (1214 ms)
[ RUN      ] ExternalFuncs.test_string_format_on_string_stream_on_variadic_tuple_256
[       OK ] ExternalFuncs.test_string_format_on_string_stream_on_variadic_tuple_256 (1325 ms)
[ RUN      ] ExternalFuncs.test_string_format_on_string_stream_inline_0
[       OK ] ExternalFuncs.test_string_format_on_string_stream_inline_0 (1208 ms)
[ RUN      ] ExternalFuncs.test_string_format_on_string_stream_inline_256
[       OK ] ExternalFuncs.test_string_format_on_string_stream_inline_256 (1302 ms)
[ RUN      ] ExternalFuncs.test_fmt_format_positional
[       OK ] ExternalFuncs.test_fmt_format_positional (288 ms)
[ RUN      ] ExternalFuncs.test_fmt_format_named
[       OK ] ExternalFuncs.test_fmt_format_named (392 ms)

As you can see implementation through the vsnprintf+std::string is equal to fmt::format, but faster than through the vsnprintf+std::unique_ptr, which is faster than through the std::ostringstream.

The tests compiled in Visual Studio 2015 Update 3 and run at Windows 7 x64 / Intel Core i7-4820K CPU @ 3.70GHz / 16GB.

How to convert std::string to lower case?

Boost provides a string algorithm for this:

#include <boost/algorithm/string.hpp>

std::string str = "HELLO, WORLD!";
boost::algorithm::to_lower(str); // modifies str

Or, for non-in-place:

#include <boost/algorithm/string.hpp>

const std::string str = "HELLO, WORLD!";
const std::string lower_str = boost::algorithm::to_lower_copy(str);

Deleting elements from std::set while iterating

I came across same old issue and found below code more understandable which is in a way per above solutions.

std::set<int*>::iterator beginIt = listOfInts.begin();
while(beginIt != listOfInts.end())
{
    // Use your member
    std::cout<<(*beginIt)<<std::endl;

    // delete the object
    delete (*beginIt);

    // erase item from vector
    listOfInts.erase(beginIt );

    // re-calculate the begin
    beginIt = listOfInts.begin();
}

std::queue iteration

you can save the original queue to a temporary queue. Then you simply do your normal pop on the temporary queue to go through the original one, for example:

queue tmp_q = original_q; //copy the original queue to the temporary queue

while (!tmp_q.empty())
{
    q_element = tmp_q.front();
    std::cout << q_element <<"\n";
    tmp_q.pop();
} 

At the end, the tmp_q will be empty but the original queue is untouched.

What does string::npos mean in this code?

The document for string::npos says:

npos is a static member constant value with the greatest possible value for an element of type size_t.

As a return value it is usually used to indicate failure.

This constant is actually defined with a value of -1 (for any trait), which because size_t is an unsigned integral type, becomes the largest possible representable value for this type.

How to change options of <select> with jQuery?

For some odd reason this part

$el.empty(); // remove old options

from CMS solution didn't work for me, so instead of that I've simply used this

el.html(' ');

And it's works. So my working code now looks like that:

var newOptions = {
    "Option 1":"option-1",
    "Option 2":"option-2"
};

var $el = $('.selectClass');
$el.html(' ');
$.each(newOptions, function(key, value) {
    $el.append($("<option></option>")
    .attr("value", value).text(key));
});

How to convert a python numpy array to an RGB image with Opencv 2.4?

You are looking for scipy.misc.toimage:

import scipy.misc
rgb = scipy.misc.toimage(np_array)

It seems to be also in scipy 1.0, but has a deprecation warning. Instead, you can use pillow and PIL.Image.fromarray

Simple logical operators in Bash

A very portable version (even to legacy bourne shell):

if [ "$varA" = 1 -a \( "$varB" = "t1" -o "$varB" = "t2" \) ]
then    do-something
fi

This has the additional quality of running only one subprocess at most (which is the process [), whatever the shell flavor.

Replace = with -eq if variables contain numeric values, e.g.

  • 3 -eq 03 is true, but
  • 3 = 03 is false. (string comparison)

How to escape a while loop in C#

If you need to continue with additional logic use...

break;

or if you have a value to return...

return my_value_to_be_returned;

However, looking at your code, I believe you will control the loop with the revised example below without using a break or return...

private void CheckLog()
        {
            bool continueLoop = true;
            while (continueLoop)
            {
                Thread.Sleep(5000);
                if (!System.IO.File.Exists("Command.bat")) continue;
                using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
                {
                    string s = "";
                    while (continueLoop && (s = sr.ReadLine()) != null)
                    {
                        if (s.Contains("mp4:production/CATCHUP/"))
                        {
                            RemoveEXELog();

                            Process p = new Process();
                            p.StartInfo.WorkingDirectory = "dump";
                            p.StartInfo.FileName = "test.exe"; 
                            p.StartInfo.Arguments = s; 
                            p.Start();
                            continueLoop = false;
                        }
                    }
                }
            }
        }

Can I delete data from the iOS DeviceSupport directory?

The ~/Library/Developer/Xcode/iOS DeviceSupport folder is basically only needed to symbolicate crash logs.

You could completely purge the entire folder. Of course the next time you connect one of your devices, Xcode would redownload the symbol data from the device.

I clean out that folder once a year or so by deleting folders for versions of iOS I no longer support or expect to ever have to symbolicate a crash log for.

jQuery checkbox change and click event

// this works on all browsers.

$(document).ready(function() {
    //set initial state.
    $('#textbox1').val($(this).is(':checked'));

    $('#checkbox1').change(function(e) {
        this.checked =  $(this).is(":checked") && !!confirm("Are you sure?");
        $('#textbox1').val(this.checked);
        return true;
    });
});

MySQL table is marked as crashed and last (automatic?) repair failed

This was my experience resolving this issue. I'm using XAMPP. I was getting the error below

 Fatal error: Can't open and lock privilege tables: Table '.\mysql\db' is marked as crashed and last (automatic?) repair failed  

This is what I did to resolve it, step by step:

  1. went to location C:\xampp\mysql, For you, location may be different, make sure you are in right file location.
  2. created backup of the data folder as data-old.
  3. copied folder "mysql" from C:\xampp\mysql\backup
  4. pasted it inside C:\xampp\mysql\data\ replacing the old mysql folder.

And it worked. Keep in mind, I have already tried around 10 solutions and they didnt work for me. This solutions may or may not work for you but regardless, make backup of your data folder before you do anything.

Note: I would always opt to resolve this with repair command but in my case, i wasnt able to get mysql started at all and i wasnt able to get myisamchk command to work.

Regardless of what you do, create a periodic backup of your database.

Convert .class to .java

I'm guessing that either the class name is wrong - be sure to use the fully-resolved class name, with all packages - or it's not in the CLASSPATH so javap can't find it.

Find row number of matching value

For your first method change ws.Range("A") to ws.Range("A:A") which will search the entirety of column a, like so:

Sub Find_Bingo()

        Dim wb As Workbook
        Dim ws As Worksheet
        Dim FoundCell As Range
        Set wb = ActiveWorkbook
        Set ws = ActiveSheet

            Const WHAT_TO_FIND As String = "Bingo"

            Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
            If Not FoundCell Is Nothing Then
                MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
            Else
                MsgBox (WHAT_TO_FIND & " not found")
            End If
End Sub

For your second method, you are using Bingo as a variable instead of a string literal. This is a good example of why I add Option Explicit to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.

Additionally, when you are using With...End With you need a period . before you reference Cells, so Cells should be .Cells. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)

Change Bingo to "Bingo" and change Cells to .Cells

With Sheet1
        Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
        LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
    End With

If Not FoundCell Is Nothing Then
        MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
        MsgBox ("Bingo not found")
End If

Update

In my

With Sheet1
    .....
End With

The Sheet1 refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1. I can refer to that in code either with the code name of Sheet1 or I can refer to it with the index of Sheets("Sheet1"). The advantage to using a codename is that it does not change if you change the name of the worksheet.

Continuing this example, let's say I renamed Sheet1 to Data. Using Sheet1 would continue to work, as the code name doesn't change, but now using Sheets("Sheet1") would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data").

In the VB Editor you would see something like this:

code object explorer example

Notice how, even though I changed the name to Data, there is still a Sheet1 to the left. That is what I mean by codename.

The Data worksheet can be referenced in two ways:

Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name

Both should return Data

More discussion on worksheet code names can be found here.

Which loop is faster, while or for?

Isn't a For Loop technically a Do While?

E.g.

for (int i = 0; i < length; ++i)
{
   //Code Here.
}

would be...

int i = 0;
do 
{
  //Code Here.
} while (++i < length);

I could be wrong though...

Also when it comes to for loops. If you plan to only retrieve data and never modify data you should use a foreach. If you require the actual indexes for some reason you'll need to increment so you should use the regular for loop.

for (Data d : data)
{
       d.doSomething();
}

should be faster than...

for (int i = 0; i < data.length; ++i)
{
      data[i].doSomething();
}

Get Line Number of certain phrase in file Python

f = open('some_file.txt','r')
line_num = 0
search_phrase = "the dog barked"
for line in f.readlines():
    line_num += 1
    if line.find(search_phrase) >= 0:
        print line_num

EDIT 1.5 years later (after seeing it get another upvote): I'm leaving this as is; but if I was writing today would write something closer to Ash/suzanshakya's solution:

def line_num_for_phrase_in_file(phrase='the dog barked', filename='file.txt')
    with open(filename,'r') as f:
        for (i, line) in enumerate(f):
            if phrase in line:
                return i
    return -1
  • Using with to open files is the pythonic idiom -- it ensures the file will be properly closed when the block using the file ends.
  • Iterating through a file using for line in f is much better than for line in f.readlines(). The former is pythonic (e.g., would work if f is any generic iterable; not necessarily a file object that implements readlines), and more efficient f.readlines() creates an list with the entire file in memory and then iterates through it. * if search_phrase in line is more pythonic than if line.find(search_phrase) >= 0, as it doesn't require line to implement find, reads more easily to see what's intended, and isn't easily screwed up (e.g., if line.find(search_phrase) and if line.find(search_phrase) > 0 both will not work for all cases as find returns the index of the first match or -1).
  • Its simpler/cleaner to wrap an iterated item in enumerate like for i, line in enumerate(f) than to initialize line_num = 0 before the loop and then manually increment in the loop. (Though arguably, this is more difficult to read for people unfamiliar with enumerate.)

See code like pythonista

Good examples of python-memcache (memcached) being used in Python?

I would advise you to use pylibmc instead.

It can act as a drop-in replacement of python-memcache, but a lot faster(as it's written in C). And you can find handy documentation for it here.

And to the question, as pylibmc just acts as a drop-in replacement, you can still refer to documentations of pylibmc for your python-memcache programming.

python convert list to dictionary

I'd go for recursions:

l = ['a', 'b', 'c', 'd', 'e', ' ']
d = dict([(k, v) for k,v in zip (l[::2], l[1::2])])

Iterate through DataSet

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (object item in row.ItemArray)
        {
            // read item
        }
    }
}

Or, if you need the column info:

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn column in table.Columns)
        {
            object item = row[column];
            // read column and item
        }
    }
}

Error - trustAnchors parameter must be non-empty

Some OpenJDK vendors releases caused this by having an empty cacerts file distributed with the binary. The bug is explained here: https://github.com/AdoptOpenJDK/openjdk-build/issues/555

You can copy to adoptOpenJdk8\jre\lib\security\cacerts the file from an old instalation like c:\Program Files\Java\jdk1.8.0_192\jre\lib\security\cacerts.

The AdoptOpenJDK buggy version is https://github.com/AdoptOpenJDK/openjdk8-releases/releases/download/jdk8u172-b11/OpenJDK8_x64_Win_jdk8u172-b11.zip

How can I use external JARs in an Android project?

Turns out I have not looked good enough at my stack trace, the problem is not that the external JAR is not included.

The problem is that Android platform is missing javax.naming.* and many other packages that the external JAR has dependencies too.

Adding external JAR files, and setting Order and Export in Eclipse works as expected with Android projects.

Nginx reverse proxy causing 504 Gateway Timeout

Increasing the timeout will not likely solve your issue since, as you say, the actual target web server is responding just fine.

I had this same issue and I found it had to do with not using a keep-alive on the connection. I can't actually answer why this is but, in clearing the connection header I solved this issue and the request was proxied just fine:

server {
    location / {
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   Host      $http_host;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_pass http://localhost:5000;
    }
}

Have a look at this posts which explains it in more detail: nginx close upstream connection after request Keep-alive header clarification http://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive

List all kafka topics

To read messages you should use:

kafka-console-consumer.sh --bootstrap-server kafka1:9092,kafka2:9092,kafka3:9092 --topic messages --from-beginning

--bootstrap-server is required attribute. You can use only single kafka1:9020 node.

How to change the color of an image on hover

Ideally you should use a transparent PNG with the circle in white and the background of the image transparent. Then you can set the background-color of the .fb-icon to blue on hover. So you're CSS would be:

fb-icon{
    background:none;
}

fb-icon:hover{
    background:#0000ff;
}

Additionally, if you don't want to use PNG's you can also use a sprite and alter the background position. A sprite is one large image with a collection of smaller images which can be used as a background image by changing the background position. So for eg, if your original circle image with the white background is 100px X 100px, you can increase the height of the image to 100px X 200px, so that the top half is the original image with the white background, while the lower half is the new image with the blue background. Then you set setup your CSS as:

fb-icon{
    background:url('path/to/image/image.png') no-repeat 0 0;
}

fb-icon:hover{
    background:url('path/to/image/image.png') no-repeat 0 -100px;
}

How can I start InternetExplorerDriver using Selenium WebDriver

In the same way for Chrome Browser below are the things to be considered.

Step 1-->Import files Required for Chrome :
import org.openqa.selenium.chrome.*;

Step 2--> Set the Path and initialize the Chrome Driver:

System.setProperty("webdriver.chrome.driver","S:\\chromedriver_win32\\chromedriver.exe");

Note: In Step 2 the location should point the chromedriver.exe file's storage location in your system drive

step 3--> Create an instance of Chrome browser

WebDriver driver = new ChromeDriver();

Rest will be the same as...

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

If you really don't have a choice for refactoring you can mock/stub everything in the super method call e.g.

    class BaseService {

        public void validate(){
            fail(" I must not be called");
        }

        public void save(){
            //Save method of super will still be called.
            validate();
        }
    }

    class ChildService extends BaseService{

        public void load(){}

        public void save(){
            super.save();
            load();
        }
    }

    @Test
    public void testSave() {
        ChildService classToTest = Mockito.spy(new ChildService());

        // Prevent/stub logic in super.save()
        Mockito.doNothing().when((BaseService)classToTest).validate();

        // When
        classToTest.save();

        // Then
        verify(classToTest).load();
    }

MySQL show status - active or total connections?

This is the total number of connections to the server till now. To find current conection status you can use

mysqladmin -u -p extended-status | grep -wi 'threads_connected\|threads_running' | awk '{ print $2,$4}'

This will show you:

Threads_connected 12

Threads_running 1  

Threads_connected: Number of connections

Threads_running: connections currently running some sql

AssertContains on strings in jUnit

You can use assertj-fluent assertions. It has lot of capabilities to write assertions in more human readable - user friendly manner.

In your case, it would be

 String x = "foo bar";
 assertThat(x).contains("foo");

It is not only for the strings, it can be used to assert lists, collections etc.. in a friendlier way

CodeIgniter - How to return Json response from controller

For CodeIgniter 4, you can use the built-in API Response Trait

Here's sample code for reference:

<?php namespace App\Controllers;

use CodeIgniter\API\ResponseTrait;

class Home extends BaseController
{
    use ResponseTrait;

    public function index()
    {
        $data = [
            'data' => 'value1',
            'data2' => 'value2',
        ];

        return $this->respond($data);
    }
}

Change values on matplotlib imshow() graph axis

I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.

Showing your image with matplotlib.pyplot.imshow is generally a fast way to display 2D data. However this by default labels the axes with the pixel count. If the 2D data you are plotting corresponds to some uniform grid defined by arrays x and y, then you can use matplotlib.pyplot.xticks and matplotlib.pyplot.yticks to label the x and y axes using the values in those arrays. These will associate some labels, corresponding to the actual grid data, to the pixel counts on the axes. And doing this is much faster than using something like pcolor for example.

Here is an attempt at this with your data:

import matplotlib.pyplot as plt

# ... define 2D array hist as you did

plt.imshow(hist, cmap='Reds')
x = np.arange(80,122,2) # the grid to which your data corresponds
nx = x.shape[0]
no_labels = 7 # how many labels to see on axis x
step_x = int(nx / (no_labels - 1)) # step between consecutive labels
x_positions = np.arange(0,nx,step_x) # pixel count at label position
x_labels = x[::step_x] # labels you want to see
plt.xticks(x_positions, x_labels)
# in principle you can do the same for y, but it is not necessary in your case

Get value from a string after a special character

_x000D_
_x000D_
//var val = $("#FieldId").val()_x000D_
//Get Value of hidden field by val() jquery function I'm using example string._x000D_
var val = "String to find after - DEMO"_x000D_
var foundString = val.substr(val.indexOf(' - ')+3,)_x000D_
console.log(foundString);
_x000D_
_x000D_
_x000D_ Assuming you need to find DEMO string after - by above code you can able to access DEMO string substr will return the string from whaterver the value indexOf return till the end of string it will return everything.

How to dynamically add a class to manual class names?

You can use this npm package. It handles everything and has options for static and dynamic classes based on a variable or a function.

// Support for string arguments
getClassNames('class1', 'class2');

// support for Object
getClassNames({class1: true, class2 : false});

// support for all type of data
getClassNames('class1', 'class2', ['class3', 'class4'], { 
    class5 : function() { return false; },
    class6 : function() { return true; }
});

<div className={getClassNames({class1: true, class2 : false})} />

Reading from file using read() function

fgets would work for you. here is very good documentation on this :-
http://www.cplusplus.com/reference/cstdio/fgets/

If you don't want to use fgets, following method will work for you :-

int readline(FILE *f, char *buffer, size_t len)
{
   char c; 
   int i;

   memset(buffer, 0, len);

   for (i = 0; i < len; i++)
   {   
      int c = fgetc(f); 

      if (!feof(f)) 
      {   
         if (c == '\r')
            buffer[i] = 0;
         else if (c == '\n')
         {   
            buffer[i] = 0;

            return i+1;
         }   
         else
            buffer[i] = c; 
      }   
      else
      {   
         //fprintf(stderr, "read_line(): recv returned %d\n", c);
         return -1; 
      }   
   }   

   return -1; 
}

PhoneGap Eclipse Issue - eglCodecCommon glUtilsParamSize: unknow param errors

This is an error that you see when your emulator has the "Use host GPU" setting checked. If you uncheck it then the error goes away. Of course, then your emulator is not as responsive anymore.

Button background as transparent

Code:

button.setVisibility(View.INVISIBLE);

Xml:

android:background="@android:color/transparent"

How to ignore certain files in Git

Add the following line to .gitignore:

/Hello.class

This will exclude Hello.class from git. If you have already committed it, run the following command:

git rm Hello.class

If you want to exclude all class files from git, add the following line to .gitignore:

*.class

How to run only one unit test class using Gradle

Below is the command to run a single test class using gradlew command line option:

gradlew.bat Connected**your bundleVariant**AndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.example.TestClass

Below example to run class com.example.TestClass with variant Variant_1:

gradlew.bat ConnectedVariant_1AndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.example.TestClass 

How to find available directory objects on Oracle 11g system?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

Pandas dataframe get first row of each group

This will give you the second row of each group (zero indexed, nth(0) is the same as first()):

df.groupby('id').nth(1) 

Documentation: http://pandas.pydata.org/pandas-docs/stable/groupby.html#taking-the-nth-row-of-each-group

Create excel ranges using column numbers in vba?

Below are two solutions to select the range A1.

Cells(1,1).Select '(row 1, column 1) 
Range("A1").Select

Also check out this link;

We strongly recommend that you use Range instead of Cells to work with cells and groups of cells. It makes your sentences much clearer and you are not forced to remember that column AE is column 31.

The only time that you will use Cells is when you want to select all the cells of a worksheet. For example: Cells.Select To select all cells and then empty all cells of values or formulas you will use: Cells.ClearContents

--

"Cells" is particularly useful when setting ranges dynamically and looping through ranges by using counters. Defining ranges using letters as column numbers may be more transparent on the short run, but it will also make your application more rigid since they are "hard coded" representations - not dynamic.

Thanks to Kim Gysen

How do I compare two hashes?

If you want a nicely formatted diff, you can do this:

# Gemfile
gem 'awesome_print' # or gem install awesome_print

And in your code:

require 'ap'

def my_diff(a, b)
  as = a.ai(plain: true).split("\n").map(&:strip)
  bs = b.ai(plain: true).split("\n").map(&:strip)
  ((as - bs) + (bs - as)).join("\n")
end

puts my_diff({foo: :bar, nested: {val1: 1, val2: 2}, end: :v},
             {foo: :bar, n2: {nested: {val1: 1, val2: 3}}, end: :v})

The idea is to use awesome print to format, and diff the output. The diff won't be exact, but it is useful for debugging purposes.

SQL: ... WHERE X IN (SELECT Y FROM ...)

One reason why you might prefer to use a JOIN rather than NOT IN is that if the Values in the NOT IN clause contain any NULLs you will always get back no results. If you do use NOT IN remember to always consider whether the sub query might bring back a NULL value!

RE: Question in Comments

'x' NOT IN (NULL,'a','b')

= 'x' <> NULL and 'x' <> 'a' and 'x' <> 'b'

= Unknown and True and True

= Unknown

Comparing two strings in C?

You need to use strcmp:

strcmp(namet2, nameIt2)

Data was not saved: object references an unsaved transient instance - save the transient instance before flushing

I had the same problem. In my case it arises, because the lookup-table "country" has an existing record with countryId==0 and a primitive primary key and I try to save a User with a countryID==0. Change the primary key of country to Integer. Now Hibernate can identify new records.

For the recommendation of using wrapper classes as primary key see this stackoverflow question

How can I delete all of my Git stashes at once?

I had another requirement like only few stash have to be removed, below code would be helpful in that case.

#!/bin/sh
for i in `seq 5 8`
do
   git stash drop stash@{$i}
done

/* will delete from 5 to 8 index*/

How can I check if a checkbox is checked?

Use this below simple code: https://jsfiddle.net/Divyesh_Patel/v7a4h3kr/7/

_x000D_
_x000D_
<input type="checkbox" id="check">_x000D_
<a href="#" onclick="check()">click</a>_x000D_
<button onclick="check()">_x000D_
button_x000D_
</button>_x000D_
<script>_x000D_
 function check() {_x000D_
      if (document.getElementById('check').checked) {_x000D_
            alert("checked");_x000D_
        } else {_x000D_
            alert("You didn't check it! Let me check it for you.");_x000D_
        }_x000D_
       _x000D_
    }_x000D_
_x000D_
</script>
_x000D_
_x000D_
_x000D_

PyTorch: How to get the shape of a Tensor as a list of int

For PyTorch v1.0 and possibly above:

>>> import torch
>>> var = torch.tensor([[1,0], [0,1]])

# Using .size function, returns a torch.Size object.
>>> var.size()
torch.Size([2, 2])
>>> type(var.size())
<class 'torch.Size'>

# Similarly, using .shape
>>> var.shape
torch.Size([2, 2])
>>> type(var.shape)
<class 'torch.Size'>

You can cast any torch.Size object to a native Python list:

>>> list(var.size())
[2, 2]
>>> type(list(var.size()))
<class 'list'>

In PyTorch v0.3 and 0.4:

Simply list(var.size()), e.g.:

>>> import torch
>>> from torch.autograd import Variable
>>> from torch import IntTensor
>>> var = Variable(IntTensor([[1,0],[0,1]]))

>>> var
Variable containing:
 1  0
 0  1
[torch.IntTensor of size 2x2]

>>> var.size()
torch.Size([2, 2])

>>> list(var.size())
[2, 2]

PostgreSQL: How to change PostgreSQL user password?

TLDR:

On many systems, a user's account often contains a period, or some sort of punction (user: john.smith, horise.johnson). IN these cases a modification will have to be made to the accepted answer above. The change requires the username to be double-quoted.

Example:

ALTER USER "username.lastname" WITH PASSWORD 'password'; 

Rational:

Postgres is quite picky on when to use a 'double quote' and when to use a 'single quote'. Typically when providing a string you would use a single quote.

How to add a response header on nginx when using proxy_pass?

There is a module called HttpHeadersMoreModule that gives you more control over headers. It does not come with Nginx and requires additional installation. With it, you can do something like this:

location ... {
  more_set_headers "Server: my_server";
}

That will "set the Server output header to the custom value for any status code and any content type". It will replace headers that are already set or add them if unset.

Notify ObservableCollection when Item changes

I know it's late, but maybe this helps others. I have created a class NotifyObservableCollection, that solves the problem of missing notification to item itself, when a property of the item changes. The usage is as simple as ObservableCollection.

public class NotifyObservableCollection<T> : ObservableCollection<T> where T : INotifyPropertyChanged
{
    private void Handle(object sender, PropertyChangedEventArgs args)
    {
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset, null));
    }

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems != null) {
            foreach (object t in e.NewItems) {
                ((T) t).PropertyChanged += Handle;
            }
        }
        if (e.OldItems != null) {
            foreach (object t in e.OldItems) {
                ((T) t).PropertyChanged -= Handle;
            }
        }
        base.OnCollectionChanged(e);
    }

While Items are added or removed the class forwards the items PropertyChanged event to the collections PropertyChanged event.

usage:

public abstract class ParameterBase : INotifyPropertyChanged
{
    protected readonly CultureInfo Ci = new CultureInfo("en-US");
    private string _value;

    public string Value {
        get { return _value; }
        set {
            if (value == _value) return;
            _value = value;
            OnPropertyChanged();
        }
    }
}

public class AItem {
    public NotifyObservableCollection<ParameterBase> Parameters {
        get { return _parameters; }
        set {
            NotifyCollectionChangedEventHandler cceh = (sender, args) => OnPropertyChanged();
            if (_parameters != null) _parameters.CollectionChanged -= cceh;
            _parameters = value;
            //needed for Binding to AItem at xaml directly
            _parameters.CollectionChanged += cceh; 
        }
    }

    public NotifyObservableCollection<ParameterBase> DefaultParameters {
        get { return _defaultParameters; }
        set {
            NotifyCollectionChangedEventHandler cceh = (sender, args) => OnPropertyChanged();
            if (_defaultParameters != null) _defaultParameters.CollectionChanged -= cceh;
            _defaultParameters = value;
            //needed for Binding to AItem at xaml directly
            _defaultParameters.CollectionChanged += cceh;
        }
    }


public class MyViewModel {
    public NotifyObservableCollection<AItem> DataItems { get; set; }
}

If now a property of an item in DataItems changes, the following xaml will get a notification, though it binds to Parameters[0] or to the item itself except to the changing property Value of the item (Converters at Triggers are called reliable on every change).

<DataGrid CanUserAddRows="False" AutoGenerateColumns="False" ItemsSource="{Binding DataItems}">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Parameters[0].Value}" Header="P1">
            <DataGridTextColumn.CellStyle>
                <Style TargetType="DataGridCell">
                    <Setter Property="Background" Value="Aqua" />
                    <Style.Triggers>
                        <DataTrigger Value="False">
                            <!-- Bind to Items with changing properties -->
                            <DataTrigger.Binding>
                                <MultiBinding Converter="{StaticResource ParameterCompareConverter}">
                                    <Binding Path="DefaultParameters[0]" />
                                    <Binding Path="Parameters[0]" />
                                </MultiBinding>
                            </DataTrigger.Binding>
                            <Setter Property="Background" Value="DeepPink" />
                        </DataTrigger>
                        <!-- Binds to AItem directly -->
                        <DataTrigger Value="True" Binding="{Binding Converter={StaticResource CheckParametersConverter}}">
                            <Setter Property="FontWeight" Value="ExtraBold" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </DataGridTextColumn.CellStyle>
        </DataGridTextColumn>

Typescript : Property does not exist on type 'object'

You probably have allProviders typed as object[] as well. And property country does not exist on object. If you don't care about typing, you can declare both allProviders and countryProviders as Array<any>:

let countryProviders: Array<any>;
let allProviders: Array<any>;

If you do want static type checking. You can create an interface for the structure and use it:

interface Provider {
    region: string,
    country: string,
    locale: string,
    company: string
}

let countryProviders: Array<Provider>;
let allProviders: Array<Provider>;

Numeric for loop in Django templates

I'm just taking the popular answer a bit further and making it more robust. This lets you specify any start point, so 0 or 1 for example. It also uses python's range feature where the end is one less so it can be used directly with list lengths for example.

@register.filter(name='range')
def filter_range(start, end):
  return range(start, end)

Then in your template just include the above template tag file and use the following:

{% for c in 1|range:6 %}
{{ c }}
{% endfor %}

Now you can do 1-6 instead of just 0-6 or hard coding it. Adding a step would require a template tag, this should cover more uses cases so it's a step forward.

Time comparison

Java doesn't (yet) have a good built-in Time class (it has one for JDBC queries, but that's not what you want).

One option would be use the JodaTime APIs and its LocalTime class.

Sticking with just the built-in Java APIs, you are stuck with java.util.Date. You can use a SimpleDateFormat to parse the time, then the Date comparison functions to see if it is before or after some other time:

SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date ten = parser.parse("10:00");
Date eighteen = parser.parse("18:00");

try {
    Date userDate = parser.parse(someOtherDate);
    if (userDate.after(ten) && userDate.before(eighteen)) {
        ...
    }
} catch (ParseException e) {
    // Invalid date was entered
}

Or you could just use some string manipulations, perhaps a regular expression to extract just the hour and the minute portions, convert them to numbers and do a numerical comparison:

Pattern p = Pattern.compile("(\d{2}):(\d{2})");
Matcher m = p.matcher(userString);
if (m.matches() ) {
    String hourString = m.group(1);
    String minuteString = m.group(2);
    int hour = Integer.parseInt(hourString);
    int minute = Integer.parseInt(minuteString);

    if (hour >= 10 && hour <= 18) {
        ...
    }
}

It really all depends on what you are trying to accomplish.

Simple example for Intent and Bundle

Basically this is what you need to do:
in the first activity:

Intent intent = new Intent();
intent.setAction(this, SecondActivity.class);
intent.putExtra(tag, value);
startActivity(intent);

and in the second activtiy:

Intent intent = getIntent();
intent.getBooleanExtra(tag, defaultValue);
intent.getStringExtra(tag, defaultValue);
intent.getIntegerExtra(tag, defaultValue);

one of the get-functions will give return you the value, depending on the datatype you are passing through.

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

It can be understood like this:

var a= []; //creates a new empty array
var a= {}; //creates a new empty object

You can also understand that

var a = {}; is equivalent to var a= new Object();

Note:

You can use Arrays when you are bothered about the order of elements(of same type) in your collection else you can use objects. In objects the order is not guaranteed.

How can a add a row to a data frame in R?

There is a simpler way to append a record from one dataframe to another IF you know that the two dataframes share the same columns and types. To append one row from xx to yy just do the following where i is the i'th row in xx.

yy[nrow(yy)+1,] <- xx[i,]

Simple as that. No messy binds. If you need to append all of xx to yy, then either call a loop or take advantage of R's sequence abilities and do this:

zz[(nrow(zz)+1):(nrow(zz)+nrow(yy)),] <- yy[1:nrow(yy),]

How to use a variable for the database name in T-SQL?

You can also use sqlcmd mode for this (enable this on the "Query" menu in Management Studio).

:setvar dbname "TEST" 

CREATE DATABASE $(dbname)
GO
ALTER DATABASE $(dbname) SET COMPATIBILITY_LEVEL = 90
GO
ALTER DATABASE $(dbname) SET RECOVERY SIMPLE 
GO

EDIT:

Check this MSDN article to set parameters via the SQLCMD tool.

SQL Server Group by Count of DateTime Per Hour?

You can also achieve this by using following SQL with date and hour in same columns and proper date time format and ordered by date time

SELECT  dateadd(hour, datediff(hour, 0, StartDate), 0) as 'ForDate', 
    COUNT(*) as 'Count' 
FROM #Events
GROUP BY dateadd(hour, datediff(hour, 0, LogTime), 0)
ORDER BY ForDate

How to find/identify large commits in git history?

I stumbled across this for the same reason as anyone else. But the quoted scripts didn't quite work for me. I've made one that is more a hybrid of those I've seen and it now lives here - https://gitlab.com/inorton/git-size-calc

Parsing JSON with Unix tools

There are a number of tools specifically designed for the purpose of manipulating JSON from the command line, and will be a lot easier and more reliable than doing it with Awk, such as jq:

curl -s 'https://api.github.com/users/lambda' | jq -r '.name'

You can also do this with tools that are likely already installed on your system, like Python using the json module, and so avoid any extra dependencies, while still having the benefit of a proper JSON parser. The following assume you want to use UTF-8, which the original JSON should be encoded in and is what most modern terminals use as well:

Python 3:

curl -s 'https://api.github.com/users/lambda' | \
    python3 -c "import sys, json; print(json.load(sys.stdin)['name'])"

Python 2:

export PYTHONIOENCODING=utf8
curl -s 'https://api.github.com/users/lambda' | \
    python2 -c "import sys, json; print json.load(sys.stdin)['name']"

Frequently Asked Questions

Why not a pure shell solution?

The standard POSIX/Single Unix Specification shell is a very limited language which doesn't contain facilities for representing sequences (list or arrays) or associative arrays (also known as hash tables, maps, dicts, or objects in some other languages). This makes representing the result of parsing JSON somewhat tricky in portable shell scripts. There are somewhat hacky ways to do it, but many of them can break if keys or values contain certain special characters.

Bash 4 and later, zsh, and ksh have support for arrays and associative arrays, but these shells are not universally available (macOS stopped updating Bash at Bash 3, due to a change from GPLv2 to GPLv3, while many Linux systems don't have zsh installed out of the box). It's possible that you could write a script that would work in either Bash 4 or zsh, one of which is available on most macOS, Linux, and BSD systems these days, but it would be tough to write a shebang line that worked for such a polyglot script.

Finally, writing a full fledged JSON parser in shell would be a significant enough enough dependency that you might as well just use an existing dependency like jq or Python instead. It's not going to be a one-liner, or even small five-line snippet, to do a good implementation.

Why not use awk, sed, or grep?

It is possible to use these tools to do some quick extraction from JSON with a known shape and formatted in a known way, such as one key per line. There are several examples of suggestions for this in other answers.

However, these tools are designed for line based or record based formats; they are not designed for recursive parsing of matched delimiters with possible escape characters.

So these quick and dirty solutions using awk/sed/grep are likely to be fragile, and break if some aspect of the input format changes, such as collapsing whitespace, or adding additional levels of nesting to the JSON objects, or an escaped quote within a string. A solution that is robust enough to handle all JSON input without breaking will also be fairly large and complex, and so not too much different than adding another dependency on jq or Python.

I have had to deal with large amounts of customer data being deleted due to poor input parsing in a shell script before, so I never recommend quick and dirty methods that may be fragile in this way. If you're doing some one-off processing, see the other answers for suggestions, but I still highly recommend just using an existing tested JSON parser.

Historical notes

This answer originally recommended jsawk, which should still work, but is a little more cumbersome to use than jq, and depends on a standalone JavaScript interpreter being installed which is less common than a Python interpreter, so the above answers are probably preferable:

curl -s 'https://api.github.com/users/lambda' | jsawk -a 'return this.name'

This answer also originally used the Twitter API from the question, but that API no longer works, making it hard to copy the examples to test out, and the new Twitter API requires API keys, so I've switched to using the GitHub API which can be used easily without API keys. The first answer for the original question would be:

curl 'http://twitter.com/users/username.json' | jq -r '.text'

How to capitalize the first letter in a String in Ruby

You can use mb_chars. This respects umlaute:

class String

  # Only capitalize first letter of a string
  def capitalize_first
    self[0] = self[0].mb_chars.upcase
    self
  end

end

Example:

"ümlaute".capitalize_first
#=> "Ümlaute"

Why does LayoutInflater ignore the layout_width and layout_height layout parameters I've specified?

wanna add to main answer above
I tried to follow it but my recyclerView began to stretch every item to a screen
I had to add next line after inflating for reach to goal

itemLayoutView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));

I already added these params by xml but it didnot work correctly
and with this line all is ok

How to place div side by side

There are many ways to do what you're asking for:

  1. Using CSS float property:

_x000D_
_x000D_
 <div style="width: 100%; overflow: hidden;">
     <div style="width: 600px; float: left;"> Left </div>
     <div style="margin-left: 620px;"> Right </div>
</div>
_x000D_
_x000D_
_x000D_

  1. Using CSS display property - which can be used to make divs act like a table:

_x000D_
_x000D_
<div style="width: 100%; display: table;">
    <div style="display: table-row">
        <div style="width: 600px; display: table-cell;"> Left </div>
        <div style="display: table-cell;"> Right </div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

There are more methods, but those two are the most popular.

What's an easy way to read random line from a file in Unix command line?

A solution that also works on MacOSX, and should also works on Linux(?):

N=5
awk 'NR==FNR {lineN[$1]; next}(FNR in lineN)' <(jot -r $N 1 $(wc -l < $file)) $file 

Where:

  • N is the number of random lines you want

  • NR==FNR {lineN[$1]; next}(FNR in lineN) file1 file2 --> save line numbers written in file1 and then print corresponding line in file2

  • jot -r $N 1 $(wc -l < $file) --> draw N numbers randomly (-r) in range (1, number_of_line_in_file) with jot. The process substitution <() will make it look like a file for the interpreter, so file1 in previous example.

First Heroku deploy failed `error code=H10`

Also check your database connection. I forgot to change my database connection from localhost and this crashed my app once it was pushed to heroku.

Python `if x is not None` or `if not x is None`?

There's no performance difference, as they compile to the same bytecode:

>>> import dis
>>> dis.dis("not x is None")
  1           0 LOAD_NAME                0 (x)
              2 LOAD_CONST               0 (None)
              4 COMPARE_OP               9 (is not)
              6 RETURN_VALUE
>>> dis.dis("x is not None")
  1           0 LOAD_NAME                0 (x)
              2 LOAD_CONST               0 (None)
              4 COMPARE_OP               9 (is not)
              6 RETURN_VALUE

Stylistically, I try to avoid not x is y, a human reader might misunderstand it as (not x) is y. If I write x is not y then there is no ambiguity.

How to get Enum Value from index in Java?

Here's three ways to do it.

public enum Months {
    JAN(1), FEB(2), MAR(3), APR(4), MAY(5), JUN(6), JUL(7), AUG(8), SEP(9), OCT(10), NOV(11), DEC(12);


    int monthOrdinal = 0;

    Months(int ord) {
        this.monthOrdinal = ord;
    }

    public static Months byOrdinal2ndWay(int ord) {
        return Months.values()[ord-1]; // less safe
    }

    public static Months byOrdinal(int ord) {
        for (Months m : Months.values()) {
            if (m.monthOrdinal == ord) {
                return m;
            }
        }
        return null;
    }
    public static Months[] MONTHS_INDEXED = new Months[] { null, JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };

}




import static junit.framework.Assert.assertEquals;

import org.junit.Test;

public class MonthsTest {

@Test
public void test_indexed_access() {
    assertEquals(Months.MONTHS_INDEXED[1], Months.JAN);
    assertEquals(Months.MONTHS_INDEXED[2], Months.FEB);

    assertEquals(Months.byOrdinal(1), Months.JAN);
    assertEquals(Months.byOrdinal(2), Months.FEB);


    assertEquals(Months.byOrdinal2ndWay(1), Months.JAN);
    assertEquals(Months.byOrdinal2ndWay(2), Months.FEB);
}

}

How to use SqlClient in ASP.NET Core?

Try this one Open your projectname.csproj file its work for me.

<PackageReference Include="System.Data.SqlClient" Version="4.6.0" />

You need to add this Reference "ItemGroup" tag inside.

C++ terminate called without an active exception

As long as your program die, then without detach or join of the thread, this error will occur. Without detaching and joining the thread, you should give endless loop after creating thread.

int main(){

std::thread t(thread,1);

while(1){}

//t.detach();
return 0;}

It is also interesting that, after sleeping or looping, thread can be detach or join. Also with this way you do not get this error.

Below example also shows that, third thread can not done his job before main die. But this error can not happen also, as long as you detach somewhere in the code. Third thread sleep for 8 seconds but main will die in 5 seconds.

void thread(int n) {std::this_thread::sleep_for (std::chrono::seconds(n));}

int main() {
std::cout << "Start main\n";
std::thread t(thread,1);
std::thread t2(thread,3);
std::thread t3(thread,8);
sleep(5);

t.detach();
t2.detach();
t3.detach();
return 0;}

Calling a Fragment method from a parent Activity

First you create method in your fragment like

public void name()
{


}

in your activity you add this

add onCreate() method

myfragment fragment=new myfragment()

finally call the method where you want to call add this

fragment.method_name();

try this code

What does '&' do in a C++ declaration?

#include<iostream>
using namespace std;
int add(int &number);

int main ()
{
            int number;
            int result;
            number=5;
            cout << "The value of the variable number before calling the function : " << number << endl;
            result=add(&number);
            cout << "The value of the variable number after the function is returned : " << number << endl;
            cout << "The value of result : " << result << endl;
            return(0);
}

int add(int &p)
{
            *p=*p+100;
            return(*p);
}

This is invalid code on several counts. Running it through g++ gives:

crap.cpp: In function ‘int main()’:
crap.cpp:11: error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int*’
crap.cpp:3: error: in passing argument 1 of ‘int add(int&)’
crap.cpp: In function ‘int add(int&)’:
crap.cpp:19: error: invalid type argument of ‘unary *’
crap.cpp:19: error: invalid type argument of ‘unary *’
crap.cpp:20: error: invalid type argument of ‘unary *’

A valid version of the code reads:

#include<iostream>
using namespace std;
int add(int &number);

int main ()
{
            int number;
            int result;
            number=5;
            cout << "The value of the variable number before calling the function : " << number << endl;
            result=add(number);
            cout << "The value of the variable number after the function is returned : " << number << endl;
            cout << "The value of result : " << result << endl;
            return(0);
}

int add(int &p)
{
            p=p+100;
            return p;
}

What is happening here is that you are passing a variable "as is" to your function. This is roughly equivalent to:

int add(int *p)
{
      *p=*p+100;
      return *p;
}

However, passing a reference to a function ensures that you cannot do things like pointer arithmetic with the reference. For example:

int add(int &p)
{
            *p=*p+100;
            return p;
}

is invalid.

If you must use a pointer to a reference, that has to be done explicitly:

int add(int &p)
{
                    int* i = &p;
            i=i+100L;
            return *i;
}

Which on a test run gives (as expected) junk output:

The value of the variable number before calling the function : 5
The value of the variable number after the function is returned : 5
The value of result : 1399090792

Best way to serialize/unserialize objects in JavaScript?

I tried to do this with Date with native JSON...

function stringify (obj: any) {
  return JSON.stringify(
    obj,
    function (k, v) {
      if (this[k] instanceof Date) {
        return ['$date', +this[k]]
      }
      return v
    }
  )
}

function clone<T> (obj: T): T {
  return JSON.parse(
    stringify(obj),
    (_, v) => (Array.isArray(v) && v[0] === '$date') ? new Date(v[1]) : v
  )
}

What does this say? It says

  • There needs to be a unique identifier, better than $date, if you want it more secure.
class Klass {
  static fromRepr (repr: string): Klass {
    return new Klass(...)
  }

  static guid = '__Klass__'

  __repr__ (): string {
    return '...'
  }
}

This is a serializable Klass, with

function serialize (obj: any) {
  return JSON.stringify(
    obj,
    function (k, v) { return this[k] instanceof Klass ? [Klass.guid, this[k].__repr__()] : v }
  )
}

function deserialize (repr: string) {
  return JSON.parse(
    repr,
    (_, v) => (Array.isArray(v) && v[0] === Klass.guid) ? Klass.fromRepr(v[1]) : v
  )
}

I tried to do it with Mongo-style Object ({ $date }) as well, but it failed in JSON.parse. Supplying k doesn't matter anymore...

BTW, if you don't care about libraries, you can use yaml.dump / yaml.load from js-yaml. Just make sure you do it the dangerous way.

How to parse a date?

The problem is that you have a date formatted like this:

Thu Jun 18 20:56:02 EDT 2009

But are using a SimpleDateFormat that is:

yyyy-MM-dd

The two formats don't agree. You need to construct a SimpleDateFormat that matches the layout of the string you're trying to parse into a Date. Lining things up to make it easy to see, you want a SimpleDateFormat like this:

EEE MMM dd HH:mm:ss zzz yyyy
Thu Jun 18 20:56:02 EDT 2009

Check the JavaDoc page I linked to and see how the characters are used.

How to generate a random integer number from within a range

Here is a slight simpler algorithm than Ryan Reich's solution:

/// Begin and end are *inclusive*; => [begin, end]
uint32_t getRandInterval(uint32_t begin, uint32_t end) {
    uint32_t range = (end - begin) + 1;
    uint32_t limit = ((uint64_t)RAND_MAX + 1) - (((uint64_t)RAND_MAX + 1) % range);

    /* Imagine range-sized buckets all in a row, then fire randomly towards
     * the buckets until you land in one of them. All buckets are equally
     * likely. If you land off the end of the line of buckets, try again. */
    uint32_t randVal = rand();
    while (randVal >= limit) randVal = rand();

    /// Return the position you hit in the bucket + begin as random number
    return (randVal % range) + begin;
}

Example (RAND_MAX := 16, begin := 2, end := 7)
    => range := 6  (1 + end - begin)
    => limit := 12 (RAND_MAX + 1) - ((RAND_MAX + 1) % range)

The limit is always a multiple of the range,
so we can split it into range-sized buckets:
    Possible-rand-output: 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16
    Buckets:             [0, 1, 2, 3, 4, 5][0, 1, 2, 3, 4, 5][X, X, X, X, X]
    Buckets + begin:     [2, 3, 4, 5, 6, 7][2, 3, 4, 5, 6, 7][X, X, X, X, X]

1st call to rand() => 13
    ? 13 is not in the bucket-range anymore (>= limit), while-condition is true
        ? retry...
2nd call to rand() => 7
    ? 7 is in the bucket-range (< limit), while-condition is false
        ? Get the corresponding bucket-value 1 (randVal % range) and add begin
    => 3

How to delete all files and folders in a directory?

 foreach (string file in System.IO.Directory.GetFiles(path))
 {
    System.IO.File.Delete(file);
 }

 foreach (string subDirectory in System.IO.Directory.GetDirectories(path))
 {
     System.IO.Directory.Delete(subDirectory,true); 
 } 

ASP.NET MVC 404 Error Handling

In IIS, you can specify a redirect to "certain" page based on error code. In you example, you can configure 404 - > Your customized 404 error page.

LogisticRegression: Unknown label type: 'continuous' using sklearn in python

I struggled with the same issue when trying to feed floats to the classifiers. I wanted to keep floats and not integers for accuracy. Try using regressor algorithms. For example:

import numpy as np
from sklearn import linear_model
from sklearn import svm

classifiers = [
    svm.SVR(),
    linear_model.SGDRegressor(),
    linear_model.BayesianRidge(),
    linear_model.LassoLars(),
    linear_model.ARDRegression(),
    linear_model.PassiveAggressiveRegressor(),
    linear_model.TheilSenRegressor(),
    linear_model.LinearRegression()]

trainingData    = np.array([ [2.3, 4.3, 2.5],  [1.3, 5.2, 5.2],  [3.3, 2.9, 0.8],  [3.1, 4.3, 4.0]  ])
trainingScores  = np.array( [3.4, 7.5, 4.5, 1.6] )
predictionData  = np.array([ [2.5, 2.4, 2.7],  [2.7, 3.2, 1.2] ])

for item in classifiers:
    print(item)
    clf = item
    clf.fit(trainingData, trainingScores)
    print(clf.predict(predictionData),'\n')

How to count the frequency of the elements in an unordered list?

def frequencyDistribution(data):
    return {i: data.count(i) for i in data}   

print frequencyDistribution([1,2,3,4])

...

 {1: 1, 2: 1, 3: 1, 4: 1}   # originalNumber: count

How to remove the Flutter debug banner?

The debug banner appears only while in development and is automatically removed in the release build.

To hide this there is a need to set debugShowCheckedModeBanner to false

MaterialApp(
  debugShowCheckedModeBanner: false,
)

enter image description here

Python argparse command line flags without arguments

Your script is right. But by default is of None type. So it considers true of any other value other than None is assigned to args.argument_name variable.

I would suggest you to add a action="store_true". This would make the True/False type of flag. If used its True else False.

import argparse
parser = argparse.ArgumentParser('parser-name')
parser.add_argument("-f","--flag",action="store_true",help="just a flag argument")

usage

$ python3 script.py -f

After parsing when checked with args.f it returns true,

args = parser.parse_args()
print(args.f)
>>>true

Process with an ID #### is not running in visual studio professional 2013 update 3

First Error

For the first error:

Process with an ID #### is not running.

The following steps worked for me:

  1. Close all instances of Visual Studio.
  2. Rename the IISExpress folder (in my PC is in C:\Users\jmelosegui\Documents).
  3. Add the _CSRUN_DISABLE_WORKAROUNDS Environment System variable with the value of 1. enter image description here
  4. Start Visual Studio in administrator mode. (In Windows, right click the executable file and select Run as administrator).

Second Error

The second error:

The webpage is not available

What caused this error:

I deleted IIS Express Development Certificate while playing with the SSL.

The following steps worked for me:

  1. Go to Control Panel.
  2. Select Add/Remove Programs.
  3. Locate IIS 8.0 Express.
  4. Right click on it then click Repair.
  5. Your certificate should be back!

Hope this helps!

How to find the logs on android studio?

For Android studio 3.4.2 go to View -> Tool Windows -> Logcat.

enter image description here

ASP.NET MVC 3 Razor - Adding class to EditorFor

You can create the same behavior creating a simple custom editor called DateTime.cshtml, saving it in Views/Shared/EditorTemplates

@model DateTime

@{
    var css = ViewData["class"] ?? "";
    @Html.TextBox("", (Model != DateTime.MinValue? Model.ToString("dd/MM/yyyy") : string.Empty), new { @class = "calendar medium " + css});
}

and in your views

@Html.EditorFor(model => model.StartDate, new { @class = "required" })

Note that in my example I'm hard-coding two css classes and the date format. You can, of course, change that. You also can do the same with others html attributes, like readonly, disabled, etc.

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

I found a possible solution here: http://www.made4dotnet.com/Default.aspx?tabid=141&aid=15

Edit:

If you automate Microsoft Excel with Microsoft Visual Basic .NET, Microsoft Visual C# .NET, or Microsoft Visual C++, you may receive the following errors when calling certain methods because the machine has the locale set to something other than US English (locale ID or LCID 1033):

Exception from HRESULT: 0x800A03EC

and/or

Old format or invalid type library

SOLUTION 1:


To get around this error you can set CurrentCulture to en-US when executing code related to Excel and reset back to your originale by using these 2 functions.

//declare a variable to hold the CurrentCulture
System.Globalization.CultureInfo oldCI;
//get the old CurrenCulture and set the new, en-US
void SetNewCurrentCulture()
{
  oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
  System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
}
//reset Current Culture back to the originale
void ResetCurrentCulture()
{
  System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
}

SOLUTION 2:


Another solution that could work, create a 1033 directory under Microsoft Office\Office11 (or your corresponding office-version), copy excel.exe to the 1033 directory, and rename it to xllex.dll.

Although you might solve the problem using one off these solutions, when you call the Excel object model in locales other than US English, the Excel object model can act differently and your code can fail in ways you may not have thought of. For example, you might have code that sets the value of a range to a date:

yourRange.Value2 = "10/10/09"

Depending on the locale this code can act differently resulting in Excel putting into the range any of the following values:

October 10, 2009 September 10, 2009 October 9, 2010

Calling Non-Static Method In Static Method In Java

There are two ways:

  1. Call the non-static method from an instance within the static method. See fabien's answer for an oneliner sample... although I would strongly recommend against it. With his example he creates an instance of the class and only uses it for one method, only to have it dispose of it later. I don't recommend it because it treats an instance like a static function.
  2. Change the static method to a non-static.

How to take keyboard input in JavaScript?

If you are doing this in a browser, you can capture keyboard events.

  • keydown
  • keypress
  • keyup

Can all be listened to on HTML nodes in most browsers.

Webkit also supports...

  • textInput

See for more details .. http://unixpapa.com/js/key.html

How to read the output from git diff?

Here's the simple example.

diff --git a/file b/file 
index 10ff2df..84d4fa2 100644
--- a/file
+++ b/file
@@ -1,5 +1,5 @@
 line1
 line2
-this line will be deleted
 line4
 line5
+this line is added

Here's an explanation (see details here).

  • --git is not a command, this means it's a git version of diff (not unix)
  • a/ b/ are directories, they are not real. it's just a convenience when we deal with the same file (in my case a/ is in index and b/ is in working directory)
  • 10ff2df..84d4fa2 are blob IDs of these 2 files
  • 100644 is the “mode bits,” indicating that this is a regular file (not executable and not a symbolic link)
  • --- a/file +++ b/file minus signs shows lines in the a/ version but missing from the b/ version; and plus signs shows lines missing in a/ but present in b/ (in my case --- means deleted lines and +++ means added lines in b/ and this the file in the working directory)
  • @@ -1,5 +1,5 @@ in order to understand this it's better to work with a big file; if you have two changes in different places you'll get two entries like @@ -1,5 +1,5 @@; suppose you have file line1 ... line100 and deleted line10 and add new line100 - you'll get:
@@ -7,7 +7,6 @@ line6
 line7
 line8
 line9
-this line10 to be deleted
 line11
 line12
 line13
@@ -98,3 +97,4 @@ line97
 line98
 line99
 line100
+this is new line100

Add attribute 'checked' on click jquery

A simple answer is to add checked attributes within a checkbox:

$('input[id='+$(this).attr("id")+']').attr("checked", "checked");

Change the color of a bullet in a html list?

It works as well if we set color for each elements for example: I added some Margin to left now.

<article class="event-item">
    <p>Black text here</p>
</article>

.event-item{
    list-style-type: disc;
    display: list-item;
    color: #ff6f9a;
     margin-left: 25px;
}
.event-item p {
    margin: 0;
    color: initial;
}

How can I find out which server hosts LDAP on my windows domain?

If you're using AD you can use serverless binding to locate a domain controller for the default domain, then use LDAP://rootDSE to get information about the directory server, as described in the linked article.

PostgreSQL: Modify OWNER on all tables simultaneously in PostgreSQL

Docker: Modify Owner of all Tables + Sequences

export user="your_new_owner"
export dbname="your_db_name"

cat <<EOF | docker run -i --rm --link postgres:postgres postgres sh -c "psql -h \$POSTGRES_PORT_5432_TCP_ADDR -p \$POSTGRES_PORT_5432_TCP_PORT -U postgres -d $dbname" | grep ALTER | docker run -i --rm --link postgres:postgres postgres sh -c "psql -h \$POSTGRES_PORT_5432_TCP_ADDR -p \$POSTGRES_PORT_5432_TCP_PORT -U postgres -d $dbname"
SELECT 'ALTER TABLE '||schemaname||'.'||tablename||' OWNER TO $user;' FROM pg_tables WHERE schemaname = 'public';
SELECT 'ALTER SEQUENCE '||relname||' OWNER TO $user;' FROM pg_class WHERE relkind = 'S';
EOF

How do I change the background color with JavaScript?

if you wish to use a button or some other event, just use this in JS:

document.querySelector("button").addEventListener("click", function() {
document.body.style.backgroundColor = "red";
});

JavaScript Chart Library

Check out ZingChart HTML5 Canvas, SVG, VML and Flash Charts. Very powerful and compatible library. I'm on the Zing team - mention us on twitter @zingchart or shoot any questions to [email protected].

Changing Jenkins build number

For multibranch pipeline projects, do this in the script console:

def project = Jenkins.instance.getItemByFullName("YourMultibranchPipelineProjectName")    
project.getAllJobs().each{ item ->   
    
    if(item.name == 'jobName'){ // master, develop, feature/......
      
      item.updateNextBuildNumber(#Number);
      item.saveNextBuildNumber();
      
      println('new build: ' + item.getNextBuildNumber())
    }
}

Remove all stylings (border, glow) from textarea

The glow effect is most-likely controlled by box-shadow. In addition to adding what Pavel said, you can add the box-shadow property for the different browser engines.

textarea {
    border: none;
    overflow: auto;
    outline: none;

    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;

    resize: none; /*remove the resize handle on the bottom right*/
}

You may also try adding !important to prioritize this CSS.

SCRIPT5: Access is denied in IE9 on xmlhttprequest

I think that the issue is that the file is on your local computer, and IE is denying access because if it let scripts have access to files on the comp that the browser is running on, that would be a HUGE security hole.
If you have access to a server or another comp that you could use as one, maybe you could try putting the files on the that, and then running the scripts as you would from a website.

How to sum columns in a dataTable?

There is also a way to do this without loops using the DataTable.Compute Method. The following example comes from that page. You can see that the code used is pretty simple.:

private void ComputeBySalesSalesID(DataSet dataSet)
{
    // Presumes a DataTable named "Orders" that has a column named "Total."
    DataTable table;
    table = dataSet.Tables["Orders"];

    // Declare an object variable. 
    object sumObject;
    sumObject = table.Compute("Sum(Total)", "EmpID = 5");
}

I must add that if you do not need to filter the results, you can always pass an empty string:

sumObject = table.Compute("Sum(Total)", "")

How to find the type of an object in Go?

I found 3 ways to return a variable's type at runtime:

Using string formatting

func typeof(v interface{}) string {
    return fmt.Sprintf("%T", v)
}

Using reflect package

func typeof(v interface{}) string {
    return reflect.TypeOf(v).String()
}

Using type assertions

func typeof(v interface{}) string {
    switch v.(type) {
    case int:
        return "int"
    case float64:
        return "float64"
    //... etc
    default:
        return "unknown"
    }
}

Every method has a different best use case:

  • string formatting - short and low footprint (not necessary to import reflect package)

  • reflect package - when need more details about the type we have access to the full reflection capabilities

  • type assertions - allows grouping types, for example recognize all int32, int64, uint32, uint64 types as "int"

plot legends without border and with white background

As documented in ?legend you do this like so:

plot(1:10,type = "n")
abline(v=seq(1,10,1), col='grey', lty='dotted')
legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white")
points(1:10,1:10)

enter image description here

Line breaks are achieved with the new line character \n. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.

Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).

Content-Disposition:What are the differences between "inline" and "attachment"?

It might also be worth mentioning that inline will try to open Office Documents (xls, doc etc) directly from the server, which might lead to a User Credentials Prompt.

see this link:

http://forums.asp.net/t/1885657.aspx/1?Access+the+SSRS+Report+in+excel+format+on+server

somebody tried to deliver an Excel Report from SSRS via ASP.Net -> the user always got prompted to enter the credentials. After clicking cancel on the prompt it would be opened anyway...

If the Content Disposition is marked as Attachment it will automatically be saved to the temp folder after clicking open and then opened in Excel from the local copy.

How to enable DataGridView sorting when user clicks on the column header?

You don't need to create a binding datasource. If you want to apply sorting for all of your columns, here is a more generic solution of mine;

private int _previousIndex;
private bool _sortDirection;

private void gridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.ColumnIndex == _previousIndex)
        _sortDirection ^= true; // toggle direction

    gridView.DataSource = SortData(
        (List<MainGridViewModel>)gridReview.DataSource, gridReview.Columns[e.ColumnIndex].Name, _sortDirection);

    _previousIndex = e.ColumnIndex;
}

public List<MainGridViewModel> SortData(List<MainGridViewModel> list, string column, bool ascending)
{
    return ascending ? 
        list.OrderBy(_ => _.GetType().GetProperty(column).GetValue(_)).ToList() :
        list.OrderByDescending(_ => _.GetType().GetProperty(column).GetValue(_)).ToList();
}

Make sure you subscribe your data grid to the event ColumnHeaderMouseClick. When the user clicks on the column it will sort by descending. If the same column header is clicked again, sorting will be applied by ascending.

Remove all subviews?

If you want to remove all the subviews on your UIView (here yourView), then write this code at your button click:

[[yourView subviews] makeObjectsPerformSelector: @selector(removeFromSuperview)];

node.js: read a text file into an array. (Each line an item in the array.)

I had the same problem, and I have solved it with the module line-by-line

https://www.npmjs.com/package/line-by-line

At least for me works like a charm, both in synchronous and asynchronous mode.

Also, the problem with lines terminating not terminating \n can be solved with the option:

{ encoding: 'utf8', skipEmptyLines: false }

Synchronous processing of lines:

var LineByLineReader = require('line-by-line'),
    lr = new LineByLineReader('big_file.txt');

lr.on('error', function (err) {
    // 'err' contains error object
});

lr.on('line', function (line) {
    // 'line' contains the current line without the trailing newline character.
});

lr.on('end', function () {
    // All lines are read, file is closed now.
}); 

How to use awk sort by column 3

Seeing as that the original question was on how to use awk and every single one of the first 7 answers use sort instead, and that this is the top hit on Google, here is how to use awk.

Sample net.csv file with headers:

ip,hostname,user,group,encryption,aduser,adattr
192.168.0.1,gw,router,router,-,-,-
192.168.0.2,server,admin,admin,-,-,-
192.168.0.3,ws-03,user,user,-,-,-
192.168.0.4,ws-04,user,user,-,-,-

And sort.awk:

#!/usr/bin/awk -f
# usage: ./sort.awk -v f=FIELD FILE

BEGIN { 
   FS="," 
}

# each line
{ 
   a[NR]=$0 ""
   s[NR]=$f ""  
}

END {
   isort(s,a,NR); 
   for(i=1; i<=NR; i++) print a[i]
}

#insertion sort of A[1..n]
function isort(S, A, n, i, j) {
   for( i=2; i<=n; i++) {
      hs = S[j=i]
      ha = A[j=i]
      while (S[j-1] > hs) { 
         j--; 
         S[j+1] = S[j]
         A[j+1] = A[j] 
      }
      S[j] = hs
      A[j] = ha
   }
}

To use it:

awk sort.awk f=3 < net.csv  # OR 

chmod +x sort.awk
./sort.awk f=3 net.csv

Creating a PHP header/footer

You can use this for header: Important: Put the following on your PHP pages that you want to include the content.

<?php
//at top:
require('header.php'); 
 ?>
 <?php
// at bottom:
require('footer.php');
?>

You can also include a navbar globaly just use this instead:

 <?php
 // At top:
require('header.php'); 
 ?>
  <?php
// At bottom:
require('footer.php');
 ?>
 <?php
 //Wherever navbar goes:
require('navbar.php'); 
?>

In header.php:

 <!DOCTYPE html>
 <html lang="en">
 <head>
    <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
 </head>
 <body> 

Do Not close Body or Html tags!
Include html here:

 <?php
 //Or more global php here:

 ?>

Footer.php:

Code here:

<?php
//code

?>

Navbar.php:

<p> Include html code here</p>
<?php
 //Include Navbar PHP code here
 
?>

Benifits:

  • Cleaner main php file (index.php) script.
  • Change the header or footer. etc to change it on all pages with the include— Good for alerts on all pages etc...
  • Time Saving!
  • Faster page loads!
  • you can have as many files to include as needed!
  • server sided!

ggplot legends - change labels, order and title

You need to do two things:

  1. Rename and re-order the factor levels before the plot
  2. Rename the title of each legend to the same title

The code:

dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))

library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha = 0.35, linetype=0)+ 
  geom_line(aes(linetype=model), size = 1) +       
  geom_point(aes(shape=model), size=4)  +      
  theme(legend.position=c(.6,0.8)) +
  theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
  scale_linetype_discrete("Model 1") +
  scale_shape_discrete("Model 1") +
  scale_colour_discrete("Model 1")

enter image description here

However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:

ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha=0.2, colour=NA)+ 
  geom_line() +       
  geom_point()  +      
  facet_wrap(~model)

enter image description here

Error Message: Type or namespace definition, or end-of-file expected

  1. Make sure you have System.Web referenced
  2. Get rid of the two } at the end.

How can I find last row that contains data in a specific column?

Public Function GetLastRow(ByVal SheetName As String) As Integer
    Dim sht As Worksheet
    Dim FirstUsedRow As Integer     'the first row of UsedRange
    Dim UsedRows As Integer         ' number of rows used

    Set sht = Sheets(SheetName)
    ''UsedRange.Rows.Count for the empty sheet is 1
    UsedRows = sht.UsedRange.Rows.Count
    FirstUsedRow = sht.UsedRange.Row
    GetLastRow = FirstUsedRow + UsedRows - 1

    Set sht = Nothing
End Function

sheet.UsedRange.Rows.Count: retrurn number of rows used, not include empty row above the first row used

if row 1 is empty, and the last used row is 10, UsedRange.Rows.Count will return 9, not 10.

This function calculate the first row number of UsedRange plus number of UsedRange rows.

The Definitive C Book Guide and List

Beginner

Introductory, no previous programming experience

  • C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]

    * Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.

  • Programming: Principles and Practice Using C++ (Bjarne Stroustrup, 2nd Edition - May 25, 2014) (updated for C++11/C++14) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners.

Introductory, with previous programming experience

  • A Tour of C++ (Bjarne Stroustrup) (2nd edition for C++17) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.

  • Accelerated C++ (Andrew Koenig and Barbara Moo, 1st Edition - August 24, 2000) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction to the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach to teaching the language.) Despite this, the C++ it teaches is purely C++98. [Review]

Best practices

  • Effective C++ (Scott Meyers, 3rd Edition - May 22, 2005) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]

  • Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.

  • Effective STL (Scott Meyers) This aims to do the same to the part of the standard library coming from the STL what Effective C++ did to the language as a whole: It presents rules of thumb along with their rationale. [Review]


Intermediate

  • More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.

  • Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]

  • More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object-oriented programming in C++ and correct use of the STL. [Review]

  • Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using non-member functions and the single responsibility principle. [Review]

  • C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]

  • C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition covering C++11, C++14 and C++17 has been already published. [Review]

  • C++ 17 - The Complete Guide (Nicolai M. Josuttis) This book describes all the new features introduced in the C++17 Standard covering everything from the simple ones like 'Inline Variables', 'constexpr if' all the way up to 'Polymorphic Memory Resources' and 'New and Delete with overaligned Data'. [Review]

  • C++ in Action (Bartosz Milewski). This book explains C++ and its features by building an application from ground up. [Review]

  • Functional Programming in C++ (Ivan Cukic). This book introduces functional programming techniques to modern C++ (C++11 and later). A very nice read for those who want to apply functional programming paradigms to C++.

  • Professional C++ (Marc Gregoire, 5th Edition - Feb 2021) Provides a comprehensive and detailed tour of the C++ language implementation replete with professional tips and concise but informative in-text examples, emphasizing C++20 features. Uses C++20 features, such as modules and std::format throughout all examples.


Advanced

  • Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multi-methods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]

  • C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)

  • C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications. A second edition covering C++14 and C++17 has been already published. [Review]

  • Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by type traits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.


Reference Style - All Levels

  • The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much like it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review] Note: All releases of the C++ standard are tracked in the question "Where do I find the current C or C++ standard documents?".

  • C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]

  • The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]

C++11/14/17/… References:

  • The C++11/14/17 Standard (INCITS/ISO/IEC 14882:2011/2014/2017) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. The C++17 standard is released in electronic form for 198 Swiss Francs.

  • The C++17 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++20.

  • Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.

  • The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.

  • The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.

  • cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.


Classics / Older

Note: Some information contained within these books may not be up-to-date or no longer considered best practice.

  • The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.

  • Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]

  • Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.

  • Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly, a good read, if it only was up to date. It was written long before C++ 98 and misses on many features (e.g. namespaces) important for large-scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is released in 2019.

  • Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.

  • The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however, this book goes through the entire C++ standard of the time explaining the rationale, the possible implementations, and features of the language. This is not a book to learn programming principles and patterns on C++, but to understand every aspect of the C++ language.

  • Thinking in C++ (Bruce Eckel, 2nd Edition, 2000). Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they're marred by a number of trivial errors (e.g. maintaining that temporaries are automatically const), with no official errata list. A partial 3rd party errata list is available at http://www.computersciencelab.com/Eckel.htm, but it is apparently not maintained.

  • Scientific and Engineering C++: An Introduction to Advanced Techniques and Examples (John Barton and Lee Nackman) It is a comprehensive and very detailed book that tried to explain and make use of all the features available in C++, in the context of numerical methods. It introduced at the time several new techniques, such as the Curiously Recurring Template Pattern (CRTP, also called Barton-Nackman trick). It pioneered several techniques such as dimensional analysis and automatic differentiation. It came with a lot of compilable and useful code, ranging from an expression parser to a Lapack wrapper. The code is still available online. Unfortunately, the books have become somewhat outdated in the style and C++ features, however, it was an incredible tour-de-force at the time (1994, pre-STL). The chapters on dynamics inheritance are a bit complicated to understand and not very useful. An updated version of this classic book that includes move semantics and the lessons learned from the STL would be very nice.

Today's Date in Perl in MM/DD/YYYY format

use Time::Piece;
...
my $t = localtime;
print $t->mdy("/");# 02/29/2000

WPF Binding to parent DataContext

Because of things like this, as a general rule of thumb, I try to avoid as much XAML "trickery" as possible and keep the XAML as dumb and simple as possible and do the rest in the ViewModel (or attached properties or IValueConverters etc. if really necessary).

If possible I would give the ViewModel of the current DataContext a reference (i.e. property) to the relevant parent ViewModel

public class ThisViewModel : ViewModelBase
{
    TypeOfAncestorViewModel Parent { get; set; }
}

and bind against that directly instead.

<TextBox Text="{Binding Parent}" />

Excel VBA select range at last row and column

Is this what you are trying? I have commented the code so that you will not have any problem understanding it.

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long, lCol As Long
    Dim rng As Range

    '~~> Set this to the relevant worksheet
    Set ws = [Sheet1]

    With ws
        '~~> Get the last row and last column
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
        lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column

        '~~> Set the range
        Set rng = .Range(.Cells(lRow, 1), .Cells(lRow, lCol))

        With rng
            Debug.Print .Address
            '
            '~~> What ever you want to do with the address
            '
        End With
    End With
End Sub

BTW I am assuming that LastRow is the same for all rows and same goes for the columns. If that is not the case then you will have use .Find to find the Last Row and the Last Column. You might want to see THIS

Opening Android Settings programmatically

To achieve this just use an Intent using the constant ACTION_SETTINGS, specifically defined to show the System Settings:

startActivity(new Intent(Settings.ACTION_SETTINGS));

startActivityForResult() is optional, only if you want to return some data when the settings activity is closed.

startActivityForResult(new Intent(Settings.ACTION_SETTINGS), 0);

here you can find a list of contants to show specific settings or details of an aplication.

configure: error: C compiler cannot create executables

I just had this issue building apache. The solution I used was the same as Mostafa, I had to export 2 variables:

export CC=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
CPP='/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -E'

This was one Mac OSX Mavericks

Node.js: How to read a stream into a buffer?

I suggest to have array of buffers and concat to resulting buffer only once at the end. Its easy to do manually, or one could use node-buffers

set serveroutput on in oracle procedure

Actually, you need to call SET SERVEROUTPUT ON; before the BEGIN call.

Everyone suggested this but offers no advice where to actually place the line:

SET SERVEROUTPUT ON;

BEGIN
    FOR rec in (SELECT * FROM EMPLOYEES) LOOP
        DBMS_OUTPUT.PUT_LINE(rec.EmployeeName);
    ENDLOOP;
END;

Otherwise, you won't see any output.

Use Font Awesome icon as CSS content

You should have font-weight set to 900 for Font Awesome 5 Free font-family to work.

This is the working one:

.css-selector::before {
   font-family: 'Font Awesome 5 Free';
   content: "\f101";
   font-weight: 900;
}

PHP decoding and encoding json with unicode characters

A hacky way of doing JSON_UNESCAPED_UNICODE in PHP 5.3. Really disappointed by PHP json support. Maybe this will help someone else.

$array = some_json();
// Encode all string children in the array to html entities.
array_walk_recursive($array, function(&$item, $key) {
    if(is_string($item)) {
        $item = htmlentities($item);
    }
});
$json = json_encode($array);

// Decode the html entities and end up with unicode again.
$json = html_entity_decode($rson);

Uninstall mongoDB from ubuntu

I suggest the following to make sure everything is uninstalled:

sudo apt-get purge mongodb mongodb-clients mongodb-server mongodb-dev

sudo apt-get purge mongodb-10gen

sudo apt-get autoremove

This should also remove your config from

 /etc/mongodb.conf.

If you want to clean up completely and you might also want to remove the data directory

/var/lib/mongodb

How do I force files to open in the browser instead of downloading (PDF)?

To indicate to the browser that the file should be viewed in the browser, the HTTP response should include these headers:

Content-Type: application/pdf
Content-Disposition: inline; filename="filename.pdf"

To have the file downloaded rather than viewed:

Content-Type: application/pdf
Content-Disposition: attachment; filename="filename.pdf"

The quotes around the filename are required if the filename contains special characters such as filename[1].pdf which may otherwise break the browser's ability to handle the response.

How you set the HTTP response headers will depend on your HTTP server (or, if you are generating the PDF response from server-side code: your server-side programming language).

How to use `replace` of directive definition?

Replace [True | False (default)]

Effect

1.  Replace the directive element. 

Dependency:

1. When replace: true, the template or templateUrl must be required. 

Hashcode and Equals for Hashset

  1. There's no need to call equals if hashCode differs.
  2. There's no need to call hashCode if (obj1 == obj2).
  3. There's no need for hashCode and/or equals just to iterate - you're not comparing objects
  4. When needed to distinguish in between objects.

Immediate exit of 'while' loop in C++

while(choice!=99)
{
  cin>>choice;
  if (choice==99)
    exit(0);
  cin>>gNum;
}

Trust me, that will exit the loop. If that doesn't work nothing will. Mind, this may not be what you want...

Can you change a path without reloading the controller in AngularJS?

I couldn't make any of the answers here to work. As a horrible hack, I store in local storage a timestamp when I change the route, and check at page initialization whether this timestamp is set and recent, in that case I don't trigger some initialization actions.

In controller:

window.localStorage['routeChangeWithoutReloadTimestamp'] = new Date().getTime();
$location.path(myURL);

In config:

.when(myURL, {
            templateUrl: 'main.html',
            controller:'MainCtrl',
            controllerAs: 'vm',
            reloadOnSearch: false,
            resolve:
            {
                var routeChangeWithoutReloadTimestamp =
                    window.localStorage['routeChangeWithoutReloadTimestamp'];
                var currentTimestamp = new Date().getTime();
                if (!routeChangeWithoutReloadTimestamp ||
                        currentTimestamp - routeChangeWithoutReloadTimestamp >= 5000) {
                    //initialization code here
                }
                //reset the timestamp to trigger initialization when needed
                window.localStorage['routeChangeWithoutReloadTimestamp'] = 0;
            }
});

I used a timestamp rather than a boolean, just in case the code is interrupted before having a chance to reinit the value stored before changing route. The risk of collision between tabs is very low.

Importing CSV File to Google Maps

none of that needed.... just go to:

http://www.gpsvisualizer.com/

now and load your csv file as-is. extra columns and all. it will slice and dice and use just the log & lat columns and plot it for you on google maps.

How to pass objects to functions in C++?

There are three methods of passing an object to a function as a parameter:

  1. Pass by reference
  2. pass by value
  3. adding constant in parameter

Go through the following example:

class Sample
{
public:
    int *ptr;
    int mVar;

    Sample(int i)
    {
        mVar = 4;
        ptr = new int(i);
    }

    ~Sample()
    {
        delete ptr;
    }

    void PrintVal()
    {
        cout << "The value of the pointer is " << *ptr << endl
             << "The value of the variable is " << mVar;
   }
};

void SomeFunc(Sample x)
{
cout << "Say i am in someFunc " << endl;
}


int main()
{

  Sample s1= 10;
  SomeFunc(s1);
  s1.PrintVal();
  char ch;
  cin >> ch;
}

Output:

Say i am in someFunc
The value of the pointer is -17891602
The value of the variable is 4

What's the algorithm to calculate aspect ratio?

This algorithm in Python gets you part of the way there.


Tell me what happens if the windows is a funny size.

Maybe what you should have is a list of all acceptable ratios (to the 3rd party component). Then, find the closest match to your window and return that ratio from the list.

Align button to the right

<div class="container-fluid">
  <div class="row">
    <h3 class="one">Text</h3>
    <button class="btn btn-secondary ml-auto">Button</button>
  </div>
</div>

.ml-auto is Bootstraph 4's non-flexbox way of aligning things.

What JSON library to use in Scala?

Play released its module for dealing with JSON independently from Play Framework, Play WS

Made a blog post about that, check it out at http://pedrorijo.com/blog/scala-json/

Using case classes, and Play WS (already included in Play Framework) you case convert between json and case classes with a simple one-liner implicit

case class User(username: String, friends: Int, enemies: Int, isAlive: Boolean)

object User {
  implicit val userJsonFormat = Json.format[User]
}

how to set ul/li bullet point color?

A couple ways this can be done:

This will make it a square

ul
{
  list-style-type: square;
}

This will make it green

li
{
  color: #0F0;
}

This will prevent the text from being green

li p
{
  color: #000;
}

However that will require that all text within lists be in paragraphs so that the color is not overridden.

A better way is to make an image of a green square and use:

ul
{
  list-style: url(green-square.png);
}

mvn clean install vs. deploy vs. release

The clean, install and deploy phases are valid lifecycle phases and invoking them will trigger all the phases preceding them, and the goals bound to these phases.

mvn clean install

This command invokes the clean phase and then the install phase sequentially:

  • clean: removes files generated at build-time in a project's directory (target by default)
  • install: installs the package into the local repository, for use as a dependency in other projects locally.

mvn deploy

This command invokes the deploy phase:

  • deploy: copies the final package to the remote repository for sharing with other developers and projects.

mvn release

This is not a valid phase nor a goal so this won't do anything. But if refers to the Maven Release Plugin that is used to automate release management. Releasing a project is done in two steps: prepare and perform. As documented:

Preparing a release goes through the following release phases:

  • Check that there are no uncommitted changes in the sources
  • Check that there are no SNAPSHOT dependencies
  • Change the version in the POMs from x-SNAPSHOT to a new version (you will be prompted for the versions to use)
  • Transform the SCM information in the POM to include the final destination of the tag
  • Run the project tests against the modified POMs to confirm everything is in working order
  • Commit the modified POMs
  • Tag the code in the SCM with a version name (this will be prompted for)
  • Bump the version in the POMs to a new value y-SNAPSHOT (these values will also be prompted for)
  • Commit the modified POMs

And then:

Performing a release runs the following release phases:

  • Checkout from an SCM URL with optional tag
  • Run the predefined Maven goals to release the project (by default, deploy site-deploy)

See also

Make a URL-encoded POST request using `http.NewRequest(...)`

URL-encoded payload must be provided on the body parameter of the http.NewRequest(method, urlStr string, body io.Reader) method, as a type that implements io.Reader interface.

Based on the sample code:

package main

import (
    "fmt"
    "net/http"
    "net/url"
    "strconv"
    "strings"
)

func main() {
    apiUrl := "https://api.com"
    resource := "/user/"
    data := url.Values{}
    data.Set("name", "foo")
    data.Set("surname", "bar")

    u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    urlStr := u.String() // "https://api.com/user/"

    client := &http.Client{}
    r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
    r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

    resp, _ := client.Do(r)
    fmt.Println(resp.Status)
}

resp.Status is 200 OK this way.

Saving a Numpy array as an image

With pygame

so this should work as I tested (you have to have pygame installed if you do not have pygame install it by using pip -> pip install pygame (that sometimes does not work so in that case you will have to download the wheel or sth but that you can look up on google)):

import pygame


pygame.init()
win = pygame.display.set_mode((128, 128))
pygame.surfarray.blit_array(win, yourarray)
pygame.display.update()
pygame.image.save(win, 'yourfilename.png')

just remember to change display width and height according to your array

here is an example, run this code:

import pygame
from numpy import zeros


pygame.init()
win = pygame.display.set_mode((128, 128))
striped = zeros((128, 128, 3))
striped[:] = (255, 0, 0)
striped[:, ::3] = (0, 255, 255)
pygame.surfarray.blit_array(win, striped)
pygame.display.update()
pygame.image.save(win, 'yourfilename.png')

Cannot instantiate the type List<Product>

Use a concrete list type, e.g. ArrayList instead of just List.

Valid values for android:fontFamily and what they map to?

As far as I'm aware, you can't declare custom fonts in xml or themes. I usually just make custom classes extending textview that set their own font on instantiation and use those in my layout xml files.

ie:

public class Museo500TextView extends TextView {
    public Museo500TextView(Context context, AttributeSet attrs) {
        super(context, attrs);      
        this.setTypeface(Typeface.createFromAsset(context.getAssets(), "path/to/font.ttf"));
    }
}

and

<my.package.views.Museo900TextView
        android:id="@+id/dialog_error_text_header"
        android:layout_width="190dp"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textSize="12sp" />

Why is a div with "display: table-cell;" not affected by margin?

If you have div next each other like this

<div id="1" style="float:left; margin-right:5px">

</div>
<div id="2" style="float:left">

</div>

This should work!

How to split the filename from a full path in batch?

@echo off
Set filename="C:\Documents and Settings\All Users\Desktop\Dostips.cmd"
call :expand %filename%
:expand
set filename=%~nx1
echo The name of the file is %filename%
set folder=%~dp1
echo It's path is %folder%

CSS - How to Style a Selected Radio Buttons Label?

You are using an adjacent sibling selector (+) when the elements are not siblings. The label is the parent of the input, not it's sibling.

CSS has no way to select an element based on it's descendents (nor anything that follows it).

You'll need to look to JavaScript to solve this.

Alternatively, rearrange your markup:

<input id="foo"><label for="foo">…</label>

Jquery Smooth Scroll To DIV - Using ID value from Link

You can do this:

$('.searchbychar').click(function () {
    var divID = '#' + this.id;
    $('html, body').animate({
        scrollTop: $(divID).offset().top
    }, 2000);
});

F.Y.I.

  • You need to prefix a class name with a . (dot) like in your first line of code.
  • $( 'searchbychar' ).click(function() {
  • Also, your code $('.searchbychar').attr('id') will return a string ID not a jQuery object. Hence, you can not apply .offset() method to it.

set column width of a gridview in asp.net

You need to convert the column into a 'TemplateField'.

In Designer View, click the smart tag of the GridView, select-> 'Edit columns'. Select your column you wish to modify and press the hyperlink converting it to a template. See screenshot: Converting column to template.

Note: Modifying your datasource might regenerate the columns again, so it might make changes to your template columns.

Ref: https://msdn.microsoft.com/en-us/library/bb288032.aspx

onclick="javascript:history.go(-1)" not working in Chrome

Try this:

<a href="www.mypage.com" onclick="history.go(-1); return false;"> Link </a>

What to do with "Unexpected indent" in python?

Run the following command to get it solved :

autopep8 -i <filename>.py

This will update your code and solve all indentation Errors :)

Hope this will solve

Internal and external fragmentation

External fragmentation
Total memory space is enough to satisfy a request or to reside a process in it, but it is not contiguous so it can not be used.

External fragmentation

Internal fragmentation
Memory block assigned to process is bigger. Some portion of memory is left unused as it can not be used by another process.

Internal fragmentation

Detect when a window is resized using JavaScript ?

Another way of doing this, using only JavaScript, would be this:

window.addEventListener('resize', functionName);

This fires every time the size changes, like the other answer.

functionName is the name of the function being executed when the window is resized (the brackets on the end aren't necessary).

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

Yes, this is possible and I would like to provide a slight alternative to Rajeev's answer that does not pass a php-generated datetime formatted string to the query.

The important distinction about how to declare the values to be SET in the UPDATE query is that they must not be quoted as literal strings.

To prevent CodeIgniter from doing this "favor" automatically, use the set() method with a third parameter of false.

$userId = 444;
$this->db->set('Last', 'Current', false);
$this->db->set('Current', 'NOW()', false);
$this->db->where('Id', $userId);
// return $this->db->get_compiled_update('Login');  // uncomment to see the rendered query
$this->db->update('Login');
return $this->db->affected_rows();  // this is expected to return the integer: 1

The generated query (depending on your database adapter) would be like this:

UPDATE `Login` SET Last = Current, Current = NOW() WHERE `Id` = 444

Demonstrated proof that the query works: https://www.db-fiddle.com/f/vcc6PfMcYhDD87wZE5gBtw/0

In this case, Last and Current ARE MySQL Keywords, but they are not Reserved Keywords, so they don't need to be backtick-wrapped.

If your precise query needs to have properly quoted identifiers (table/column names), then there is always protectIdentifiers().

Setting environment variable in react-native?

In my opinion the best option is to use react-native-config. It supports 12 factor.

I found this package extremely useful. You can set multiple environments, e.g. development, staging, production.

In case of Android, variables are available also in Java classes, gradle, AndroidManifest.xml etc. In case of iOS, variables are available also in Obj-C classes, Info.plist.

You just create files like

  • .env.development
  • .env.staging
  • .env.production

You fill these files with key, values like

API_URL=https://myapi.com
GOOGLE_MAPS_API_KEY=abcdefgh

and then just use it:

import Config from 'react-native-config'

Config.API_URL  // 'https://myapi.com'
Config.GOOGLE_MAPS_API_KEY  // 'abcdefgh'

If you want to use different environments, you basically set ENVFILE variable like this:

ENVFILE=.env.staging react-native run-android

or for assembling app for production (android in my case):

cd android && ENVFILE=.env.production ./gradlew assembleRelease

How to force a hover state with jQuery?

Also, you could try triggering a mouseover.

$("#btn").click(function() {
   $("#link").trigger("mouseover");
});

Not sure if this will work for your specific scenario, but I've had success triggering mouseover instead of hover for various cases.

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

If you're using node, why not generate them with node? This module seems to be pretty full featured:

Note that I wouldn't generate on the fly. Generate with some kind of build script so you have a consistent certificate and key. Otherwise you'll have to authorize the newly generated self-signed certificate every time.

Apply style to cells of first row

This should do the work:

.category_table tr:first-child td {
    vertical-align: top;
}

Windows 7: unable to register DLL - Error Code:0X80004005

Use following command should work on windows 7. don't forget to enclose the dll name with full path in double quotations.

C:\Windows\SysWOW64>regsvr32 "c:\dll.name" 

Formatting html email for Outlook

I used VML(Vector Markup Language) based formatting in my email template. In VML Based you have write your code within comment I took help from this site.

https://litmus.com/blog/a-guide-to-bulletproof-buttons-in-email-design#supporttable

How to rebase local branch onto remote master

1.Update Master first...

git checkout [master branch]
git pull [master branch]

2.Now rebase source-branch with master branch

git checkout [source branch]
git rebase [master branch]
git pull [source branch] (remote/source branch)
git push [source branch]

IF source branch does not yet exist on remote then do:

git push -u origin [source branch]

"et voila..."

ERROR 2013 (HY000): Lost connection to MySQL server at 'reading authorization packet', system error: 0

I've struggled a lot with this error. Tried every single answer I found on the internet.

In the end, I've connected my computer to my cell phone's hotspot and everything worked. I turned out that my company's internet was blocking the connection with MySQL.

This is not a complete solution, but maybe someone faces the same problem. It worths to check the connection.

Showing the stack trace from a running Python application

How to debug any function in console:

Create function where you use pdb.set_trace(), then function you want debug.

>>> import pdb
>>> import my_function

>>> def f():
...     pdb.set_trace()
...     my_function()
... 

Then call created function:

>>> f()
> <stdin>(3)f()
(Pdb) s
--Call--
> <stdin>(1)my_function()
(Pdb) 

Happy debugging :)

Connect to sqlplus in a shell script and run SQL scripts

Wouldn't something akin to this be better, security-wise?:

sqlplus -s /nolog << EOF
CONNECT admin/password;

whenever sqlerror exit sql.sqlcode;
set echo off 
set heading off

@pl_script_1.sql
@pl_script_2.sql

exit;
EOF 

How to solve "The directory is not empty" error when running rmdir command in a batch script?

As @gfullam stated in a comment to @BoffinbraiN's answer, the <dir> you are deleting itself might not be the one which contains files: there might be subdirectories in <dir> that get a "The directory is not empty" message and the only solution then would be to recursively iterate over the directories, manually deleting all their containing files... I ended up deciding to use a port of rm from UNIX. rm.exe comes with Git Bash, MinGW, Cygwin, GnuWin32 and others. You just need to have its parent directory in your PATH and then execute as you would in a UNIX system.

Batch script example:

set PATH=C:\cygwin64\bin;%PATH%
rm -rf "C:\<dir>"

How to change lowercase chars to uppercase using the 'keyup' event?

Let say your html code is :

<input type="text" id="txtMyText" />

then the jquery should be :

$('#txtMyText').keyup(function() {
  this.value = this.value.toUpperCase();
});

Date only from TextBoxFor()

I use Globalize so work with many date formats so use the following:

@Html.TextBoxFor(m => m.DateOfBirth, "{0:d}")

This will automatically adjust the date format to the browser's locale settings.

Amazon S3 boto - how to create a folder?

Use this:

import boto3
s3 = boto3.client('s3')
bucket_name = "YOUR-BUCKET-NAME"
directory_name = "DIRECTORY/THAT/YOU/WANT/TO/CREATE" #it's name of your folders
s3.put_object(Bucket=bucket_name, Key=(directory_name+'/'))

CKEditor, Image Upload (filebrowserUploadUrl)

If you don't want to have to buy CKFinder, like I didn't want to buy CKFinder, then I wrote a very reliable uploader for CKEditor 4. It consists of a second form, placed immediately above your textarea form, and utilizes the iframe hack, which, in spite of its name, is seamless and unobtrusive.

After the image is successfully uploaded, it will appear in your CKEditor window, along with whatever content is already there.

editor.php (the form page):

<?php
set_time_limit ( 3600 )
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Content Editor</title>
<link href="jquery-ui-1.10.2/themes/vader/ui.dialog.css" rel="stylesheet" media="screen" id="dialog_ui" />
<link href="jquery-ui-1.10.2/themes/vader/jquery-ui.css" rel="stylesheet" media="screen" id="dialog_ui" />
<script src="jquery-ui-1.10.2/jquery-1.9.1.js"></script>
<script src="jquery-ui-1.10.2/jquery.form.js"></script>
<script src="jquery-ui-1.10.2/ui/jquery-ui.js"></script>
<script src="ckeditor/ckeditor.js"></script>
<script src="ckeditor/config.js"></script>
<script src="ckeditor/adapters/jquery.js"></script>
<script src="ckeditor/plugin2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('#editor').ckeditor({ height: 400, width:600});
});

function placePic(){

    function ImageExist(url){
       var img = new Image();
       img.src = url;
       return img.height != 0;
    }

var filename = document.forms['uploader']['uploadedfile'].value;
document.forms['uploader']['filename'].value = filename;
var url = 'http://www.mydomain.com/external/images/cms/'+filename;
document.getElementById('uploader').submit();
var string = CKEDITOR.instances.editor.getData();
var t = setInterval(function(){

            var exists = ImageExist(url);
            if(exists === true){
                    if(document.getElementById('loader')){
                        document.getElementById('loader').parentNode.removeChild(document.getElementById('loader'));
                    }
                    CKEDITOR.instances.editor.setData(string + "<img src=\""+url+"\" />");
                    clearInterval(t);
            }
            else{
                if(! document.getElementById("loader")){
                    var loader = document.createElement("div");
                    loader.setAttribute("id","loader");
                    loader.setAttribute("style","position:absolute;margin:-300px auto 0px 240px;width:113px;height:63px;text-align:center;z-index:10;");
                    document.getElementById('formBox').appendChild(loader);

                    var loaderGif = document.createElement("img");
                    loaderGif.setAttribute("id","loaderGif");
                    loaderGif.setAttribute("style","width:113px;height:63px;text-align:center;");
                    loaderGif.src = "external/images/cms/2dumbfish.gif";
                    document.getElementById('loader').appendChild(loaderGif);
                }
            }

            },100);
}

function loadContent(){
if(document.forms['editorform']['site'].value !== "" && document.forms['editorform']['page'].value !== ""){
    var site = document.forms['editorform']['site'].value;
    var page = document.forms['editorform']['page'].value;
    var url = site+"/"+page+".html";
    $.ajax({
        type: "GET",
        url: url,
        dataType: 'html',
        success: function (html) {
            CKEDITOR.instances.editor.setData(html);
        }
    });
}
}
</script>
<style>
button{
  width: 93px;
  height: 28px;
  border:none;
  padding: 0 4px 8px 0;
  font-weight:bold
}
#formBox{
    width:50%;
margin:10px auto 0px auto;
font-family:Tahoma, Geneva, sans-serif;
font-size:12px;
}
#field{
position:absolute;
top:10px;
margin-left:300px;
margin-bottom:20px;
}
#target{
position:absolute;
top:100px;
left:100px;
width:400px;
height:100px;
display:none;
}
.textField{
    padding-left: 1px;
border-style: solid;
border-color: black;
border-width: 1px;
font-family: helvetica, arial, sans serif;
padding-left: 1px;
}
#report{
float:left;
margin-left:20px;
margin-top:10px;
font-family: helvetica, arial, sans serif;
font-size:12px;
color:#900;
}
</style>
</head>

<body>
<?php
if(isset($_GET['r'])){ ?><div id="report">
<?php echo $_GET['r']; ?> is changed.
</div><?php
}
?>
<div id="formBox">
<form id="uploader" name="uploader" action="editaction.php"  method="post" target="target" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="50000000" />
<input type="hidden" name="filename" value="" />
Insert image:&nbsp;<input name="uploadedfile" type="file" class="textField" onchange="placePic();return false;" />&nbsp;&nbsp;
</form>

<form name="editorform" id="editorform" method="post" action="editaction.php" >
<div id="field" >Site:&nbsp;<select name="site"  class="textField" onchange="loadContent();return false;">
    <option value=""></option>
    <option value="scubatortuga">scubatortuga</option>
    <option value="drytortugascharters">drytortugascharters</option>
    <option value="keyscombo">keyscombo</option>
    <option value="keywesttreasurehunters">keywesttreasurehunters</option>
    <option value="spearfishkeywest">spearfishkeywest</option>
</select>
Page:&nbsp;<select name="page" class="textField" onchange="loadContent();return false;">
    <option value=""></option>
    <option value="one">1</option>
    <option value="two">2</option>
    <option value="three">3</option>
    <option value="four">4</option>
</select>
</div><br />
<textarea name="editor" id="editor"></textarea><br />
<input type="submit" name="submit" value="Submit" />
</form>
</div>
<iframe name="target" id="target"></iframe>
</body>
</html>

And here is the action page, editaction.php, which does the actual file upload:

<?php
//editaction.php

foreach($_POST as $k => $v){
    ${"$k"} = $v;
}
//fileuploader.php
if($_FILES){
  $target_path = "external/images/cms/";
  $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 
  if(! file_exists("$target_path$filename")){
    move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path);
  }
}
else{
    $string = stripslashes($editor);
    $filename = "$site/$page.html";
    $handle = fopen($filename,"w");
    fwrite($handle,$string,strlen($string));
    fclose($handle);
    header("location: editor.php?r=$filename");
}
?>

How to deselect a selected UITableView cell?

use this code

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
 {
    //Change the selected background view of the cell.
     [tableView deselectRowAtIndexPath:indexPath animated:YES];
 }

Swift 3.0:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    //Change the selected background view of the cell.
    tableView.deselectRow(at: indexPath, animated: true)
}

Android BroadcastReceiver within Activity

Extends the ToastDisplay class with BroadcastReceiver and register the receiver in the manifest file,and dont register your broadcast receiver in onResume() .

<application
  ....
  <receiver android:name=".ToastDisplay">
    <intent-filter>
      <action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"/>
    </intent-filter>
  </receiver>
</application>

if you want to register in activity then register in the onCreate() method e.g:

onCreate(){

    sentSmsBroadcastCome = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "SMS SENT!!", Toast.LENGTH_SHORT).show();
        }
    };
    IntentFilter filterSend = new IntentFilter();
    filterSend.addAction("m.sent");
    registerReceiver(sentSmsBroadcastCome, filterSend);
}

Rock, Paper, Scissors Game Java

int w =0 , l =0, d=0, i=0;
    Scanner sc = new Scanner(System.in);

// try tentimes
    while (i<10) {


        System.out.println("scissor(1) ,Rock(2),Paper(3) ");
        int n = sc.nextInt();
        int m =(int)(Math.random()*3+1);


        if(n==m){

            System.out.println("Com:"+m +"so>>> " + "draw");
            d++;


        }else if ((n-1)%3==(m%3)){
            w++;
            System.out.println("Com:"+m +"so>>> " +"win");
        }
        else if(n >=4 )
        {
            System.out.println("pleas enter correct number)");


    }
        else {
            System.out.println("Com:"+m +"so>>> " +"lose");
            l++;

        }
        i++;

Difference between arguments and parameters in Java

There are different points of view. One is they are the same. But in practice, we need to differentiate formal parameters (declarations in the method's header) and actual parameters (values passed at the point of invocation). While phrases "formal parameter" and "actual parameter" are common, "formal argument" and "actual argument" are not used. This is because "argument" is used mainly to denote "actual parameter". As a result, some people insist that "parameter" can denote only "formal parameter".

How to clear text area with a button in html using javascript?

Your Html

<input type="button" value="Clear" onclick="clearContent()"> 
<textarea id='output' rows=20 cols=90></textarea>

Your Javascript

function clearContent()
{
    document.getElementById("output").value='';
}

Collision Detection between two images in Java

Here's a useful of an open source game that uses a lot of collisions: http://robocode.sourceforge.net/

You may take a look at the code and complement with the answers written here.

Is there an eval() function in Java?

The following resolved the issue:

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String str = "4*5";
System.out.println(engine.eval(str));

How to vertically align an image inside a div

The only (and the best cross-browser) way as I know is to use an inline-block helper with height: 100% and vertical-align: middle on both elements.

So there is a solution: http://jsfiddle.net/kizu/4RPFa/4570/

_x000D_
_x000D_
.frame {_x000D_
    height: 25px;      /* Equals maximum image height */_x000D_
    width: 160px;_x000D_
    border: 1px solid red;_x000D_
    white-space: nowrap; /* This is required unless you put the helper span closely near the img */_x000D_
_x000D_
    text-align: center;_x000D_
    margin: 1em 0;_x000D_
}_x000D_
_x000D_
.helper {_x000D_
    display: inline-block;_x000D_
    height: 100%;_x000D_
    vertical-align: middle;_x000D_
}_x000D_
_x000D_
img {_x000D_
    background: #3A6F9A;_x000D_
    vertical-align: middle;_x000D_
    max-height: 25px;_x000D_
    max-width: 160px;_x000D_
}
_x000D_
<div class="frame">_x000D_
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=250px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=25px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=23px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=21px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=19px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=17px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=15px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=13px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=11px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=9px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=7px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=5px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=3px />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Or, if you don't want to have an extra element in modern browsers and don't mind using Internet Explorer expressions, you can use a pseudo-element and add it to Internet Explorer using a convenient Expression, that runs only once per element, so there won't be any performance issues:

The solution with :before and expression() for Internet Explorer: http://jsfiddle.net/kizu/4RPFa/4571/

_x000D_
_x000D_
.frame {_x000D_
    height: 25px;      /* Equals maximum image height */_x000D_
    width: 160px;_x000D_
    border: 1px solid red;_x000D_
    white-space: nowrap;_x000D_
_x000D_
    text-align: center;_x000D_
    margin: 1em 0;_x000D_
}_x000D_
_x000D_
.frame:before,_x000D_
.frame_before {_x000D_
    content: "";_x000D_
    display: inline-block;_x000D_
    height: 100%;_x000D_
    vertical-align: middle;_x000D_
}_x000D_
_x000D_
img {_x000D_
    background: #3A6F9A;_x000D_
    vertical-align: middle;_x000D_
    max-height: 25px;_x000D_
    max-width: 160px;_x000D_
}_x000D_
_x000D_
/* Move this to conditional comments */_x000D_
.frame {_x000D_
    list-style:none;_x000D_
    behavior: expression(_x000D_
        function(t){_x000D_
            t.insertAdjacentHTML('afterBegin','<span class="frame_before"></span>');_x000D_
            t.runtimeStyle.behavior = 'none';_x000D_
        }(this)_x000D_
    );_x000D_
}
_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=250px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=25px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=23px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=21px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=19px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=17px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=15px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=13px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=11px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=9px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=7px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=5px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=3px /></div>
_x000D_
_x000D_
_x000D_


How it works:

  1. When you have two inline-block elements near each other, you can align each to other's side, so with vertical-align: middle you'll get something like this:

    Two aligned blocks

  2. When you have a block with fixed height (in px, em or another absolute unit), you can set the height of inner blocks in %.

  3. So, adding one inline-block with height: 100% in a block with fixed height would align another inline-block element in it (<img/> in your case) vertically near it.

Uninstalling an MSI file from the command line without using msiexec

I would try the following syntax - it works for me.

msiexec /x filename.msi /q 

Sorting a set of values

From a comment:

I want to sort each set.

That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.


You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.

Oracle SQL: Use sequence in insert with Select Statement

Assuming that you want to group the data before you generate the key with the sequence, it sounds like you want something like

INSERT INTO HISTORICAL_CAR_STATS (
    HISTORICAL_CAR_STATS_ID, 
    YEAR,
    MONTH, 
    MAKE,
    MODEL,
    REGION,
    AVG_MSRP,
    CNT) 
SELECT MY_SEQ.nextval,
       year,
       month,
       make,
       model,
       region,
       avg_msrp,
       cnt
  FROM (SELECT '2010' year,
               '12' month,
               'ALL' make,
               'ALL' model,
               REGION,
               sum(AVG_MSRP*COUNT)/sum(COUNT) avg_msrp,
               sum(cnt) cnt
          FROM HISTORICAL_CAR_STATS
         WHERE YEAR = '2010' 
           AND MONTH = '12'
           AND MAKE != 'ALL' 
         GROUP BY REGION)

Right click to select a row in a Datagridview and show a menu to delete it

private void dataGridView1_CellContextMenuStripNeeded(object sender, 
DataGridViewCellContextMenuStripNeededEventArgs e)
{            
    if (e.RowIndex != -1)
    {
        dataGridView1.ClearSelection();
        this.dataGridView1.Rows[e.RowIndex].Selected = true;
        e.ContextMenuStrip = contextMenuStrip1;
    }
}

convert ArrayList<MyCustomClass> to JSONArray

Add to your gradle:

implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

Convert ArrayList to JsonArray

JsonArray jsonElements = (JsonArray) new Gson().toJsonTree(itemsArrayList);

How to modify a text file?

Rewriting a file in place is often done by saving the old copy with a modified name. Unix folks add a ~ to mark the old one. Windows folks do all kinds of things -- add .bak or .old -- or rename the file entirely or put the ~ on the front of the name.

import shutil
shutil.move( afile, afile+"~" )

destination= open( aFile, "w" )
source= open( aFile+"~", "r" )
for line in source:
    destination.write( line )
    if <some condition>:
        destination.write( >some additional line> + "\n" )
source.close()
destination.close()

Instead of shutil, you can use the following.

import os
os.rename( aFile, aFile+"~" )

How to lookup JNDI resources on WebLogic?

You should be able to simply do this:

Context context = new InitialContext();
dataSource = (javax.sql.DataSource) context.lookup("jdbc/myDataSource");

If you are looking it up from a remote destination you need to use the WL initial context factory like this:

Hashtable<String, String> h = new Hashtable<String, String>(7);
h.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
h.put(Context.PROVIDER_URL, pURL); //For example "t3://127.0.0.1:7001"
h.put(Context.SECURITY_PRINCIPAL, pUsername);
h.put(Context.SECURITY_CREDENTIALS, pPassword);

InitialContext context = new InitialContext(h);
dataSource = (javax.sql.DataSource) context.lookup("jdbc/myDataSource");

weblogic.jndi.WLInitialContextFactory

form confirm before submit

sample fiddle: http://jsfiddle.net/z68VD/

html:

<form id="uguu" action="http://google.ca">
    <input type="submit" value="text 1" />
</form>

jquery:

$("#uguu").submit(function() {
    if ($("input[type='submit']").val() == "text 1") {
        alert("Please confirm if everything is correct");
        $("input[type='submit']").val("text 2");
        return false;
    }
});

How to set Java SDK path in AndroidStudio?

Click "use embedded JDK" on version Android Studio 3.2.1

click this box

Oracle SQL Where clause to find date records older than 30 days

Use:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= TRUNC(SYSDATE) - 30

SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date that is 30 days previous including the current time.

Depending on your needs, you could also look at using ADD_MONTHS:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)

Chrome:The website uses HSTS. Network errors...this page will probably work later

One very quick way around this is, when you're viewing the "Your connection is not private" screen:

type badidea

type thisisunsafe (credit to The Java Guy for finding the new passphrase)

That will allow the security exception when Chrome is otherwise not allowing the exception to be set via clickthrough, e.g. for this HSTS case.

This is only recommended for local connections and local-network virtual machines, obviously, but it has the advantage of working for VMs being used for development (e.g. on port-forwarded local connections) and not just direct localhost connections.

Note: the Chrome developers have changed this passphrase in the past, and may do so again. If badidea ceases to work, please leave a note here if you learn the new passphrase. I'll try to do the same.

Edit: as of 30 Jan 2018 this passphrase appears to no longer work.

If I can hunt down a new one I'll post it here. In the meantime I'm going to take the time to set up a self-signed certificate using the method outlined in this stackoverflow post:

How to create a self-signed certificate with openssl?

Edit: as of 1 Mar 2018 and Chrome Version 64.0.3282.186 this passphrase works again for HSTS-related blocks on .dev sites.

Edit: as of 9 Mar 2018 and Chrome Version 65.0.3325.146 the badidea passphrase no longer works.

Edit 2: the trouble with self-signed certificates seems to be that, with security standards tightening across the board these days, they cause their own errors to be thrown (nginx, for example, refuses to load an SSL/TLS cert that includes a self-signed cert in the chain of authority, by default).

The solution I'm going with now is to swap out the top-level domain on all my .app and .dev development sites with .test or .localhost. Chrome and Safari will no longer accept insecure connections to standard top-level domains (including .app).

The current list of standard top-level domains can be found in this Wikipedia article, including special-use domains:

Wikipedia: List of Internet Top Level Domains: Special Use Domains

These top-level domains seem to be exempt from the new https-only restrictions:

  • .local
  • .localhost
  • .test
  • (any custom/non-standard top-level domain)

See the answer and link from codinghands to the original question for more information:

answer from codinghands

How do I get the full path of the current file's directory?

Let's assume you have the following directory structure: -

main/ fold1 fold2 fold3...

folders = glob.glob("main/fold*")

for fold in folders:
    abspath = os.path.dirname(os.path.abspath(fold))
    fullpath = os.path.join(abspath, sch)
    print(fullpath)

What does -z mean in Bash?

The expression -z string is true if the length of string is zero.

Run bash script as daemon

To run it as a full daemon from a shell, you'll need to use setsid and redirect its output. You can redirect the output to a logfile, or to /dev/null to discard it. Assuming your script is called myscript.sh, use the following command:

setsid myscript.sh >/dev/null 2>&1 < /dev/null &

This will completely detach the process from your current shell (stdin, stdout and stderr). If you want to keep the output in a logfile, replace the first /dev/null with your /path/to/logfile.

You have to redirect the output, otherwise it will not run as a true daemon (it will depend on your shell to read and write output).

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

For creating real UML class diagrams:

In Visual Studio 2013 Ultimate you can do this without any external tools.

  • In the menu, click on Architecture, New Diagram Select UML Class Diagram
  • This will ask you to create a new Modeling Project if you don't have one already.

You will have a empty UMLClassDiagram.classdiagram.

  • Again, go to Architecture, Windows, Architecture Explorer.
  • A window will pop up with your namespaces, Choose Class View.
  • Then a list of sub-namespaces will appear, if any. Choose one, select the classes and drag them to the empty UMLClassDiagram1.classdiagram window.

Reference: Create UML Class Diagrams from Code

How to use ConcurrentLinkedQueue?

This is probably what you're looking for in terms of thread safety & "prettyness" when trying to consume everything in the queue:

for (YourObject obj = queue.poll(); obj != null; obj = queue.poll()) {
}

This will guarantee that you quit when the queue is empty, and that you continue to pop objects off of it as long as it's not empty.

Get top n records for each group of grouped results

Try this:

SELECT a.person, a.group, a.age FROM person AS a WHERE 
(SELECT COUNT(*) FROM person AS b 
WHERE b.group = a.group AND b.age >= a.age) <= 2 
ORDER BY a.group ASC, a.age DESC

DEMO

Launch Image does not show up in my iOS App

There is a bug where Xcode 6 launch images stored in asset files cause iphone landscape only apps on iOS7/iOS8 to display a black launch image. iPad works fine.

http://www.raywenderlich.com/forums/viewtopic.php?f=2&t=10868

Solution: Use the new Launchscreen.xib for ios8+ onwards. (it is far better)

For ios7 devices to work you simply turn off launch images source and use the old school launch images file names in the plist

iphone5 - [email protected] 
iphone4s - [email protected]
ipad2 - Default-Landscape~ipad.png
ipad retina - Default-Landscape@2x~ipad.png

Painful but works. B
enter image description here

Error inflating class android.support.design.widget.NavigationView

For me, I encountered this error many times,

Error inflating class android.support.design.widget.NavigationView #28 and #29

The solution that works for me is that you must match your support design library and your support appcompat library.

compile 'com.android.support:appcompat-v7:23.1.1'

compile 'com.android.support:design:23.1.1'

For me they must match. :) It works for me!

How do I convert a number to a numeric, comma-separated formatted string?

remove the commas with a replace and convert:

CONVERT(INT,REPLACE([varName],',',''))

where varName is the name of the variable that has numeric values in it with commas

Difference between scaling horizontally and vertically for databases

The accepted answer is spot on the basic definition of horizontal vs vertical scaling. But unlike the common belief that horizontal scaling of databases is only possible with Cassandra, MongoDB, etc I would like to add that horizontal scaling is also very much possible with any traditional RDMS; that too without using any third party solutions.

I know of many companies, specially SaaS based companies that do this. This is done using simple application logic. You basically take a set of users and divide them over multiple DB servers. So for example, you would typically have a "meta" database/table that would store clients, DB server/connection strings, etc and a table that stores client/server mapping.

Then simply direct requests from each client to the DB server they are mapped to.

Now some may say this is akin to horizontal partitioning and not "true" horizontal scaling and they will be right in some ways. But the end result is that you have scaled your DB over multiple Db servers.

The only difference between the two approaches to horizontal scaling is that one approach (MongoDB, etc) the scaling is done by the DB software itself. In that sense you are "buying" the scaling. In the other approach (for RDBMS horizontal scaling), the scaling is built by application code/logic.

Buy vs Build

Delete all the queues from RabbitMQ?

To list queues,

./rabbitmqadmin -f tsv -q list queues

To delete a queue,

./rabbitmqadmin delete queue name=name_of_queue

How can I get terminal output in python?

You can use Popen in subprocess as they suggest.

with os, which is not recomment, it's like below:

import os
a  = os.popen('pwd').readlines()

CSS for the "down arrow" on a <select> element?

No, the down arrow is a browser element. It's built in [and different] in every browser. You can, however, replace the select box with a custom drop down box using javascript.

Jan Hancic mentioned a jQuery plugin to do just that.

How to build a query string for a URL in C#?

Here is an implementation which uses very basic language features. It's part of a class which we have to port and maintain in Objective C so we choose to have more lines of code but easier to port and understand by a programmer that isn't very familiar with C#.

        /// <summary>
        /// Builds a complete http url with query strings.
        /// </summary>
        /// <param name="pHostname"></param>
        /// <param name="pPort"></param>
        /// <param name="pPage">ex "/index.html" or index.html</param>
        /// <param name="pGetParams">a Dictionary<string,string> collection containing the key value pairs.  Pass null if there are none.</param>
        /// <returns>a string of the form: http://[pHostname]:[pPort/[pPage]?key1=val1&key2=val2...</returns>

  static public string buildURL(string pHostname, int pPort, string pPage, Dictionary<string,string> pGetParams)
        {
            StringBuilder sb = new StringBuilder(200);
            sb.Append("http://");
            sb.Append(pHostname);
            if( pPort != 80 ) {
                sb.Append(pPort);
            }
            // Allows page param to be passed in with or without leading slash.
            if( !pPage.StartsWith("/") ) {
                sb.Append("/");
            }
            sb.Append(pPage);

            if (pGetParams != null && pGetParams.Count > 0)
            {
                sb.Append("?");
                foreach (KeyValuePair<string, string> kvp in pGetParams)
                {
                    sb.Append(kvp.Key);
                    sb.Append("=");
                    sb.Append( System.Web.HttpUtility.UrlEncode(kvp.Value) );
                    sb.Append("&");
                }
                sb.Remove(sb.Length - 1, 1); // Remove the final '&'
            }
            return sb.ToString();
        }

Change auto increment starting number?

How to auto increment by one, starting at 10 in MySQL:

create table foobar(
  id             INT PRIMARY KEY AUTO_INCREMENT,
  moobar         VARCHAR(500)
); 
ALTER TABLE foobar AUTO_INCREMENT=10;

INSERT INTO foobar(moobar) values ("abc");
INSERT INTO foobar(moobar) values ("def");
INSERT INTO foobar(moobar) values ("xyz");

select * from foobar;

'10', 'abc'
'11', 'def'
'12', 'xyz'

This auto increments the id column by one starting at 10.

Auto increment in MySQL by 5, starting at 10:

drop table foobar
create table foobar(
  id             INT PRIMARY KEY AUTO_INCREMENT,
  moobar         VARCHAR(500)
); 
SET @@auto_increment_increment=5;
ALTER TABLE foobar AUTO_INCREMENT=10;

INSERT INTO foobar(moobar) values ("abc");
INSERT INTO foobar(moobar) values ("def");
INSERT INTO foobar(moobar) values ("xyz");

select * from foobar;
'11', 'abc'
'16', 'def'
'21', 'xyz'

This auto increments the id column by 5 each time, starting at 10.

Getting the 'external' IP address in Java

If you are using JAVA based webapp and if you want to grab the client's (One who makes the request via a browser) external ip try deploying the app in a public domain and use request.getRemoteAddr() to read the external IP address.

Bad Request, Your browser sent a request that this server could not understand

I was testing my application with special characters & was observing the same error. After some research, turns out the % symbol was the cause. I had to modify it to the encoded representation %25. Its all fine now, thanks to the below post

https://superuser.com/questions/759959/why-does-the-percent-sign-in-a-url-cause-an-http-400-bad-request-error

How to Apply Mask to Image in OpenCV?

Here is some code to apply binary mask on a video frame sequence acquired from a webcam. comment and uncomment the "bitwise_not(Mon_mask,Mon_mask);"line and see the effect.

bests, Ahmed.

#include "cv.h"      // include it to used Main OpenCV functions.
#include "highgui.h" //include it to use GUI functions.

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    int c;

int radius=100;
      CvPoint2D32f center;
    //IplImage* color_img;
      Mat image, image0,image1; 
        IplImage *tmp;
    CvCapture* cv_cap = cvCaptureFromCAM(0);

    while(1)  {
        tmp = cvQueryFrame(cv_cap); // get frame
          // IplImage to Mat
            Mat imgMat(tmp);
            image =tmp; 



    center.x = tmp->width/2;
    center.y = tmp->height/2;

         Mat Mon_mask(image.size(), CV_8UC1, Scalar(0,0,0));


        circle(Mon_mask, center, radius, Scalar(255,255,255), -1, 8, 0 ); //-1 means filled

        bitwise_not(Mon_mask,Mon_mask);// commenté ou pas = RP ou DMLA 





        if(tmp != 0)

           imshow("Glaucom", image); // show frame

     c = cvWaitKey(10); // wait 10 ms or for key stroke
    if(c == 27)
        break; // if ESC, break and quit
    }
    /* clean up */
    cvReleaseCapture( &cv_cap );
    cvDestroyWindow("Glaucom");

}

Email validation using jQuery

<!-- Dont forget to include the jQuery library here -->
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">

$(document).ready(function() {

    $("#validate").keyup(function(){

        var email = $("#validate").val();

        if(email != 0)
        {
            if(isValidEmailAddress(email))
            {
                $("#validEmail").css({
                    "background-image": "url('validYes.png')"
                });
            } else {
                $("#validEmail").css({
                    "background-image": "url('validNo.png')"
                });
            }
        } else {
            $("#validEmail").css({
                "background-image": "none"
            });         
        }

    });

});

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

</script>

<style>
    #validEmail
    {
        margin-top: 4px;
        margin-left: 9px;
        position: absolute;
        width: 16px;
        height: 16px;
    }

    .text
    {
        font-family: Arial, Tahoma, Helvetica;
    }
</style>

    <title>Live Email Validation with jQuery Demo</title>
</head>
<body>
    <div class="text"><h1>Reynoldsftw.com - Live Email Validation</h1><h2>Type in an email address in the box below:</h2></div>
    <div><input type="text" id="validate" width="30"><span id="validEmail"></span></div>
    <div class="text"><P>More script and css style

: www.htmldrive.net


Source:htmldrive.com

How to move a file?

  import os,shutil

  current_path = "" ## source path

  new_path = "" ## destination path

  os.chdir(current_path)

  for files in os.listdir():

        os.rename(files, new_path+'{}'.format(f))
        shutil.move(files, new_path+'{}'.format(f)) ## to move files from 

different disk ex. C: --> D:

How to upload file to server with HTTP POST multipart/form-data?

The below code reads a file, converts it to a byte array and then makes a request to the server.

    public void PostImage()
    {
        HttpClient httpClient = new HttpClient();
        MultipartFormDataContent form = new MultipartFormDataContent();

        byte[] imagebytearraystring = ImageFileToByteArray(@"C:\Users\Downloads\icon.png");
        form.Add(new ByteArrayContent(imagebytearraystring, 0, imagebytearraystring.Count()), "profile_pic", "hello1.jpg");
        HttpResponseMessage response = httpClient.PostAsync("your url", form).Result;

        httpClient.Dispose();
        string sd = response.Content.ReadAsStringAsync().Result;
    }

    private byte[] ImageFileToByteArray(string fullFilePath)
    {
        FileStream fs = File.OpenRead(fullFilePath);
        byte[] bytes = new byte[fs.Length];
        fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
        fs.Close();
        return bytes;
    }

PHP upload image

  <?php 
 $target_dir = "images/";
    echo $target_file = $target_dir . basename($_FILES["image"]["name"]);
    $post_tmp_img = $_FILES["image"]["tmp_name"];
    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
    $post_imag = $_FILES["image"]["name"];
        move_uploaded_file($post_tmp_img,"../images/$post_imag");
 ?>

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment