Programs & Examples On #Spectrum

The frequency domain of a wave-like function.

How do I connect to my existing Git repository using Visual Studio Code?

  1. Open Visual Studio Code terminal (Ctrl + `)
  2. Write the Git clone command. For example,

    git clone https://github.com/angular/angular-phonecat.git
    
  3. Open the folder you have just cloned (menu FileOpen Folder)

    Enter image description here

Generate random colors (RGB)

Output in the form of (r,b,g) its look like (255,155,100)

from numpy import random
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

Plotting power spectrum in python

if rate is the sampling rate(Hz), then np.linspace(0, rate/2, n) is the frequency array of every point in fft. You can use rfft to calculate the fft in your data is real values:

import numpy as np
import pylab as pl
rate = 30.0
t = np.arange(0, 10, 1/rate)
x = np.sin(2*np.pi*4*t) + np.sin(2*np.pi*7*t) + np.random.randn(len(t))*0.2
p = 20*np.log10(np.abs(np.fft.rfft(x)))
f = np.linspace(0, rate/2, len(p))
plot(f, p)

enter image description here

signal x contains 4Hz & 7Hz sin wave, so there are two peaks at 4Hz & 7Hz.

Understanding Matlab FFT example

It sounds like you need to some background reading on what an FFT is (e.g. http://en.wikipedia.org/wiki/FFT). But to answer your questions:

Why does the x-axis (frequency) end at 500?

Because the input vector is length 1000. In general, the FFT of a length-N input waveform will result in a length-N output vector. If the input waveform is real, then the output will be symmetrical, so the first 501 points are sufficient.

Edit: (I didn't notice that the example padded the time-domain vector.)

The frequency goes to 500 Hz because the time-domain waveform is declared to have a sample-rate of 1 kHz. The Nyquist sampling theorem dictates that a signal with sample-rate fs can support a (real) signal with a maximum bandwidth of fs/2.

How do I know the frequencies are between 0 and 500?

See above.

Shouldn't the FFT tell me, in which limits the frequencies are?

No.

Does the FFT only return the amplitude value without the frequency?

The FFT simply assigns an amplitude (and phase) to every frequency bin.

How to remove carriage returns and new lines in Postgresql?

select regexp_replace(field, E'[\\n\\r\\u2028]+', ' ', 'g' )

I had the same problem in my postgres d/b, but the newline in question wasn't the traditional ascii CRLF, it was a unicode line separator, character U2028. The above code snippet will capture that unicode variation as well.

Update... although I've only ever encountered the aforementioned characters "in the wild", to follow lmichelbacher's advice to translate even more unicode newline-like characters, use this:

select regexp_replace(field, E'[\\n\\r\\f\\u000B\\u0085\\u2028\\u2029]+', ' ', 'g' )

Visual Studio 2010 shortcut to find classes and methods?

Use the "Go To Find Combo Box" with the ">of" command. CTRL+/ or CTRL+D are the standard hotkeys.

For example, go to the combo box (CTRL+/) and type: >of MyClassName. As you type, intellisense will refine the options in the dropdown.

In my experience, this is faster than Navigate To and doesn't bring up another dialog to deal with. Also, this combo box has a lot of other nifty little shortcut commands:

Using the Go To Find Combo Box

This textbox used to be the default on the Standard toolbar in Visual Studio. It was removed in Visual Studio 2012, so you have to add it back using menu Tools ? Customize. The hotkeys may have changed too: I'm not sure since mine are all customized.

Get text of label with jquery

No solution here worked for me. Instead I added a class to the label and was able to select it that way.

<asp:Label ID="Label1" CssClass="myLabel1Class" runat="server" Text="Label"></asp:Label>

$(".myLabel1Class").val()

And, as mentioned by others, make sure you have your jquery loaded.

How to apply bold text style for an entire row using Apache POI?

This should work fine.

    Workbook wb = new XSSFWorkbook("myWorkbook.xlsx");
    Row row=sheet.getRow(0);
    CellStyle style=null;

    XSSFFont defaultFont= wb.createFont();
    defaultFont.setFontHeightInPoints((short)10);
    defaultFont.setFontName("Arial");
    defaultFont.setColor(IndexedColors.BLACK.getIndex());
    defaultFont.setBold(false);
    defaultFont.setItalic(false);

    XSSFFont font= wb.createFont();
    font.setFontHeightInPoints((short)10);
    font.setFontName("Arial");
    font.setColor(IndexedColors.WHITE.getIndex());
    font.setBold(true);
    font.setItalic(false);

    style=row.getRowStyle();
    style.setFillBackgroundColor(IndexedColors.DARK_BLUE.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setFont(font);

If you do not create defaultFont all your workbook will be using the other one as default.

Use success() or complete() in AJAX call

"complete" executes when the ajax call is finished. "success" executes when the ajax call finishes with a successful response code.

Android Service needs to run always (Never pause or stop)

I found a simple and clear way of keeping the Service running always.

This guy has explained it so clearly and have used a good algorithm. His approach is to send a Broadcast when the service is about to get killed and then use it to restart the service.

You should check it out: http://fabcirablog.weebly.com/blog/creating-a-never-ending-background-service-in-android

ReferenceError: fetch is not defined

Best one is Axios library for fetching. use npm i --save axios for installng and use it like fetch, just write axios instead of fetch and then get response in then().

Creating an empty bitmap and drawing though canvas in Android

This is probably simpler than you're thinking:

int w = WIDTH_PX, h = HEIGHT_PX;

Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);

// ready to draw on that bitmap through that canvas

Here's a series of tutorials I've found on the topic: Drawing with Canvas Series

How do I execute multiple SQL Statements in Access' Query Editor?

You might find it better to use a 3rd party program to enter the queries into Access such as WinSQL I think from memory WinSQL supports multiple queries via it's batch feature.

I ultimately found it easier to just write a program in perl to do bulk INSERTS into an Access via ODBC. You could use vbscript or any language that supports ODBC though.

You can then do anything you like and have your own complicated logic to handle the importing.

How to convert a std::string to const char* or char*?

If you just want to pass a std::string to a function that needs const char* you can use

std::string str;
const char * c = str.c_str();

If you want to get a writable copy, like char *, you can do that with this:

std::string str;
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = '\0'; // don't forget the terminating 0

// don't forget to free the string after finished using it
delete[] writable;

Edit: Notice that the above is not exception safe. If anything between the new call and the delete call throws, you will leak memory, as nothing will call delete for you automatically. There are two immediate ways to solve this.

boost::scoped_array

boost::scoped_array will delete the memory for you upon going out of scope:

std::string str;
boost::scoped_array<char> writable(new char[str.size() + 1]);
std::copy(str.begin(), str.end(), writable.get());
writable[str.size()] = '\0'; // don't forget the terminating 0

// get the char* using writable.get()

// memory is automatically freed if the smart pointer goes 
// out of scope

std::vector

This is the standard way (does not require any external library). You use std::vector, which completely manages the memory for you.

std::string str;
std::vector<char> writable(str.begin(), str.end());
writable.push_back('\0');

// get the char* using &writable[0] or &*writable.begin()

php exec command (or similar) to not wait for result

This uses wget to notify a URL of something without waiting.

$command = 'wget -qO- http://test.com/data=data';
exec('nohup ' . $command . ' >> /dev/null 2>&1 & echo $!', $pid);

This uses ls to update a log without waiting.

$command = 'ls -la > content.log';
exec('nohup ' . $command . ' >> /dev/null 2>&1 & echo $!', $pid);

Create SQLite Database and table

The next link will bring you to a great tutorial, that helped me a lot!

How to SQLITE in C#

I nearly used everything in that article to create the SQLite database for my own C# Application.

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

After you added the reference, refer to the dll from your code using the following line on top of your class:

using System.Data.SQLite;

You can find the dll's here:

SQLite DLL's

You can find the NuGet way here:

NuGet

Up next is the create script. Creating a database file:

SQLiteConnection.CreateFile("MyDatabase.sqlite");

SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

m_dbConnection.Close();

After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

Example on how to use transactions:

 using (TransactionScope tran = new TransactionScope())
 {
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
     tran.Complete();
 }

What does 'const static' mean in C and C++?

It's a small space optimization.

When you say

const int foo = 42;

You're not defining a constant, but creating a read-only variable. The compiler is smart enough to use 42 whenever it sees foo, but it will also allocate space in the initialized data area for it. This is done because, as defined, foo has external linkage. Another compilation unit can say:

extern const int foo;

To get access to its value. That's not a good practice since that compilation unit has no idea what the value of foo is. It just knows it's a const int and has to reload the value from memory whenever it is used.

Now, by declaring that it is static:

static const int foo = 42;

The compiler can do its usual optimization, but it can also say "hey, nobody outside this compilation unit can see foo and I know it's always 42 so there is no need to allocate any space for it."

I should also note that in C++, the preferred way to prevent names from escaping the current compilation unit is to use an anonymous namespace:

namespace {
    const int foo = 42; // same as static definition above
}

Algorithm to randomly generate an aesthetically-pleasing color palette

you could have them be within a certain brightness. that would control the ammount of "neon" colors a bit. for instance, if the "brightness"

brightness = sqrt(R^2+G^2+B^2)

was within a certain high bound, it would have a washed out, light color to it. Conversely, if it was within a certain low bound, it would be darker. This would eliminate any crazy, standout colors and if you chose a bound really high or really low, they would all be fairly close to either white or black.

Reading/Writing a MS Word file in PHP

Office 2007 .docx should be possible since it's an XML standard. Word 2003 most likely requires COM to read, even with the standards now published by MS, since those standards are huge. I haven't seen many libraries written to match them yet.

SQL query return data from multiple tables

Part 2 - Subqueries

Okay, now the boss has burst in again - I want a list of all of our cars with the brand and a total of how many of that brand we have!

This is a great opportunity to use the next trick in our bag of SQL goodies - the subquery. If you are unfamiliar with the term, a subquery is a query that runs inside another query. There are many different ways to use them.

For our request, lets first put a simple query together that will list each car and the brand:

select
    a.ID,
    b.brand
from
    cars a
        join brands b
            on a.brand=b.ID

Now, if we wanted to simply get a count of cars sorted by brand, we could of course write this:

select
    b.brand,
    count(a.ID) as countCars
from
    cars a
        join brands b
            on a.brand=b.ID
group by
    b.brand

+--------+-----------+
| brand  | countCars |
+--------+-----------+
| BMW    |         2 |
| Ford   |         2 |
| Nissan |         1 |
| Smart  |         1 |
| Toyota |         5 |
+--------+-----------+

So, we should be able to simply add in the count function to our original query right?

select
    a.ID,
    b.brand,
    count(a.ID) as countCars
from
    cars a
        join brands b
            on a.brand=b.ID
group by
    a.ID,
    b.brand

+----+--------+-----------+
| ID | brand  | countCars |
+----+--------+-----------+
|  1 | Toyota |         1 |
|  2 | Ford   |         1 |
|  3 | Nissan |         1 |
|  4 | Smart  |         1 |
|  5 | Toyota |         1 |
|  6 | BMW    |         1 |
|  7 | Ford   |         1 |
|  8 | Toyota |         1 |
|  9 | Toyota |         1 |
| 10 | BMW    |         1 |
| 11 | Toyota |         1 |
+----+--------+-----------+
11 rows in set (0.00 sec)

Sadly, no, we can't do that. The reason is that when we add in the car ID (column a.ID) we have to add it into the group by - so now, when the count function works, there is only one ID matched per ID.

This is where we can however use a subquery - in fact we can do two completely different types of subquery that will return the same results that we need for this. The first is to simply put the subquery in the select clause. This means each time we get a row of data, the subquery will run off, get a column of data and then pop it into our row of data.

select
    a.ID,
    b.brand,
    (
    select
        count(c.ID)
    from
        cars c
    where
        a.brand=c.brand
    ) as countCars
from
    cars a
        join brands b
            on a.brand=b.ID

+----+--------+-----------+
| ID | brand  | countCars |
+----+--------+-----------+
|  2 | Ford   |         2 |
|  7 | Ford   |         2 |
|  1 | Toyota |         5 |
|  5 | Toyota |         5 |
|  8 | Toyota |         5 |
|  9 | Toyota |         5 |
| 11 | Toyota |         5 |
|  3 | Nissan |         1 |
|  4 | Smart  |         1 |
|  6 | BMW    |         2 |
| 10 | BMW    |         2 |
+----+--------+-----------+
11 rows in set (0.00 sec)

And Bam!, this would do us. If you noticed though, this sub query will have to run for each and every single row of data we return. Even in this little example, we only have five different Brands of car, but the subquery ran eleven times as we have eleven rows of data that we are returning. So, in this case, it doesn't seem like the most efficient way to write code.

For a different approach, lets run a subquery and pretend it is a table:

select
    a.ID,
    b.brand,
    d.countCars
from
    cars a
        join brands b
            on a.brand=b.ID
        join
            (
            select
                c.brand,
                count(c.ID) as countCars
            from
                cars c
            group by
                c.brand
            ) d
            on a.brand=d.brand

+----+--------+-----------+
| ID | brand  | countCars |
+----+--------+-----------+
|  1 | Toyota |         5 |
|  2 | Ford   |         2 |
|  3 | Nissan |         1 |
|  4 | Smart  |         1 |
|  5 | Toyota |         5 |
|  6 | BMW    |         2 |
|  7 | Ford   |         2 |
|  8 | Toyota |         5 |
|  9 | Toyota |         5 |
| 10 | BMW    |         2 |
| 11 | Toyota |         5 |
+----+--------+-----------+
11 rows in set (0.00 sec)

Okay, so we have the same results (ordered slightly different - it seems the database wanted to return results ordered by the first column we picked this time) - but the same right numbers.

So, what's the difference between the two - and when should we use each type of subquery? First, lets make sure we understand how that second query works. We selected two tables in the from clause of our query, and then wrote a query and told the database that it was in fact a table instead - which the database is perfectly happy with. There can be some benefits to using this method (as well as some limitations). Foremost is that this subquery ran once. If our database contained a large volume of data, there could well be a massive improvement over the first method. However, as we are using this as a table, we have to bring in extra rows of data - so that they can actually be joined back to our rows of data. We also have to be sure that there are enough rows of data if we are going to use a simple join like in the query above. If you recall, the join will only pull back rows that have matching data on both sides of the join. If we aren't careful, this could result in valid data not being returned from our cars table if there wasn't a matching row in this subquery.

Now, looking back at the first subquery, there are some limitations as well. because we are pulling data back into a single row, we can ONLY pull back one row of data. Subqueries used in the select clause of a query very often use only an aggregate function such as sum, count, max or another similar aggregate function. They don't have to, but that is often how they are written.

So, before we move on, lets have a quick look at where else we can use a subquery. We can use it in the where clause - now, this example is a little contrived as in our database, there are better ways of getting the following data, but seeing as it is only for an example, lets have a look:

select
    ID,
    brand
from
    brands
where
    brand like '%o%'

+----+--------+
| ID | brand  |
+----+--------+
|  1 | Ford   |
|  2 | Toyota |
|  6 | Holden |
+----+--------+
3 rows in set (0.00 sec)

This returns us a list of brand IDs and Brand names (the second column is only added to show us the brands) that contain the letter o in the name.

Now, we could use the results of this query in a where clause this:

select
    a.ID,
    b.brand
from
    cars a
        join brands b
            on a.brand=b.ID
where
    a.brand in
        (
        select
            ID
        from
            brands
        where
            brand like '%o%'
        )

+----+--------+
| ID | brand  |
+----+--------+
|  2 | Ford   |
|  7 | Ford   |
|  1 | Toyota |
|  5 | Toyota |
|  8 | Toyota |
|  9 | Toyota |
| 11 | Toyota |
+----+--------+
7 rows in set (0.00 sec)

As you can see, even though the subquery was returning the three brand IDs, our cars table only had entries for two of them.

In this case, for further detail, the subquery is working as if we wrote the following code:

select
    a.ID,
    b.brand
from
    cars a
        join brands b
            on a.brand=b.ID
where
    a.brand in (1,2,6)

+----+--------+
| ID | brand  |
+----+--------+
|  1 | Toyota |
|  2 | Ford   |
|  5 | Toyota |
|  7 | Ford   |
|  8 | Toyota |
|  9 | Toyota |
| 11 | Toyota |
+----+--------+
7 rows in set (0.00 sec)

Again, you can see how a subquery vs manual inputs has changed the order of the rows when returning from the database.

While we are discussing subqueries, lets see what else we can do with a subquery:

  • You can place a subquery within another subquery, and so on and so on. There is a limit which depends on your database, but short of recursive functions of some insane and maniacal programmer, most folks will never hit that limit.
  • You can place a number of subqueries into a single query, a few in the select clause, some in the from clause and a couple more in the where clause - just remember that each one you put in is making your query more complex and likely to take longer to execute.

If you need to write some efficient code, it can be beneficial to write the query a number of ways and see (either by timing it or by using an explain plan) which is the optimal query to get your results. The first way that works may not always be the best way of doing it.

How to find the width of a div using vanilla JavaScript?

Actually, you don't have to use document.getElementById("mydiv") .
You can simply use the id of the div, like:

var w = mydiv.clientWidth;
or
var w = mydiv.offsetWidth;
etc.

Replacement for "rename" in dplyr

I tried to use dplyr::rename and I get an error:

occ_5d <- dplyr::rename(occ_5d, rowname='code_5d')
Error: Unknown column `code_5d` 
Call `rlang::last_error()` to see a backtrace

I instead used the base R function which turns out to be quite simple and effective:

names(occ_5d)[1] = "code_5d"

SQL Server after update trigger

CREATE TRIGGER [dbo].[after_update] ON [dbo].[MYTABLE]
AFTER UPDATE
AS
BEGIN
    DECLARE @ID INT

    SELECT @ID = D.ID
    FROM inserted D

    UPDATE MYTABLE
    SET mytable.CHANGED_ON = GETDATE()
        ,CHANGED_BY = USER_NAME(USER_ID())
    WHERE ID = @ID
END

Anaconda Installed but Cannot Launch Navigator

For people from Brazil

There is a security software called Warsaw (used for home banking) that must be uninstalled! After you can install it back again.

After thousand times trying, installing, uninstalling, cleanning-up the regedit that finally solved the problem.

Can an angular directive pass arguments to functions in expressions specified in the directive's attributes?

If you declare your callback as mentioned by @lex82 like

callback = "callback(item.id, arg2)"

You can call the callback method in the directive scope with object map and it would do the binding correctly. Like

scope.callback({arg2:"some value"});

without requiring for $parse. See my fiddle(console log) http://jsfiddle.net/k7czc/2/

Update: There is a small example of this in the documentation:

& or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given and widget definition of scope: { localFn:'&myAttr' }, then isolate scope property localFn will point to a function wrapper for the count = count + value expression. Often it's desirable to pass data from the isolated scope via an expression and to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22}).

PhpMyAdmin "Wrong permissions on configuration file, should not be world writable!"

You should not be making them 777 (which is writeable by everyone). Try 644 instead, which means user has read and write and group and others can only read.

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) Symfony2

Ok, so this might not fix your issue but it definitely worked for me.

So you've created your Mysql user I take it? Go to user privileges on PhpMyAdmin and click edit next to the user your using for Symfony. Scroll down to near the bottom and where it says which host you want to use make sure you've selected LocalHost not % Any.

Then in your config file swap 127.0.0.1 for localhost. Hopefully that will work for you. Just worked for me as I was having the same issue.

How to download a file with Node.js (without using third-party libraries)?

Without library it could be buggy just to point out. Here are a few:

Here my suggestion:

  • Call system tool like wget or curl
  • use some tool like node-wget-promise which also very simple to use. var wget = require('node-wget-promise'); wget('http://nodejs.org/images/logo.svg');

Is a Python list guaranteed to have its elements stay in the order they are inserted in?

Yes lists and tuples are always ordered while dictionaries are not

How can I list the contents of a directory in Python?

Below code will list directories and the files within the dir. The other one is os.walk

def print_directory_contents(sPath):
        import os                                       
        for sChild in os.listdir(sPath):                
            sChildPath = os.path.join(sPath,sChild)
            if os.path.isdir(sChildPath):
                print_directory_contents(sChildPath)
            else:
                print(sChildPath)

What is The Rule of Three?

Introduction

C++ treats variables of user-defined types with value semantics. This means that objects are implicitly copied in various contexts, and we should understand what "copying an object" actually means.

Let us consider a simple example:

class person
{
    std::string name;
    int age;

public:

    person(const std::string& name, int age) : name(name), age(age)
    {
    }
};

int main()
{
    person a("Bjarne Stroustrup", 60);
    person b(a);   // What happens here?
    b = a;         // And here?
}

(If you are puzzled by the name(name), age(age) part, this is called a member initializer list.)

Special member functions

What does it mean to copy a person object? The main function shows two distinct copying scenarios. The initialization person b(a); is performed by the copy constructor. Its job is to construct a fresh object based on the state of an existing object. The assignment b = a is performed by the copy assignment operator. Its job is generally a little more complicated, because the target object is already in some valid state that needs to be dealt with.

Since we declared neither the copy constructor nor the assignment operator (nor the destructor) ourselves, these are implicitly defined for us. Quote from the standard:

The [...] copy constructor and copy assignment operator, [...] and destructor are special member functions. [ Note: The implementation will implicitly declare these member functions for some class types when the program does not explicitly declare them. The implementation will implicitly define them if they are used. [...] end note ] [n3126.pdf section 12 §1]

By default, copying an object means copying its members:

The implicitly-defined copy constructor for a non-union class X performs a memberwise copy of its subobjects. [n3126.pdf section 12.8 §16]

The implicitly-defined copy assignment operator for a non-union class X performs memberwise copy assignment of its subobjects. [n3126.pdf section 12.8 §30]

Implicit definitions

The implicitly-defined special member functions for person look like this:

// 1. copy constructor
person(const person& that) : name(that.name), age(that.age)
{
}

// 2. copy assignment operator
person& operator=(const person& that)
{
    name = that.name;
    age = that.age;
    return *this;
}

// 3. destructor
~person()
{
}

Memberwise copying is exactly what we want in this case: name and age are copied, so we get a self-contained, independent person object. The implicitly-defined destructor is always empty. This is also fine in this case since we did not acquire any resources in the constructor. The members' destructors are implicitly called after the person destructor is finished:

After executing the body of the destructor and destroying any automatic objects allocated within the body, a destructor for class X calls the destructors for X's direct [...] members [n3126.pdf 12.4 §6]

Managing resources

So when should we declare those special member functions explicitly? When our class manages a resource, that is, when an object of the class is responsible for that resource. That usually means the resource is acquired in the constructor (or passed into the constructor) and released in the destructor.

Let us go back in time to pre-standard C++. There was no such thing as std::string, and programmers were in love with pointers. The person class might have looked like this:

class person
{
    char* name;
    int age;

public:

    // the constructor acquires a resource:
    // in this case, dynamic memory obtained via new[]
    person(const char* the_name, int the_age)
    {
        name = new char[strlen(the_name) + 1];
        strcpy(name, the_name);
        age = the_age;
    }

    // the destructor must release this resource via delete[]
    ~person()
    {
        delete[] name;
    }
};

Even today, people still write classes in this style and get into trouble: "I pushed a person into a vector and now I get crazy memory errors!" Remember that by default, copying an object means copying its members, but copying the name member merely copies a pointer, not the character array it points to! This has several unpleasant effects:

  1. Changes via a can be observed via b.
  2. Once b is destroyed, a.name is a dangling pointer.
  3. If a is destroyed, deleting the dangling pointer yields undefined behavior.
  4. Since the assignment does not take into account what name pointed to before the assignment, sooner or later you will get memory leaks all over the place.

Explicit definitions

Since memberwise copying does not have the desired effect, we must define the copy constructor and the copy assignment operator explicitly to make deep copies of the character array:

// 1. copy constructor
person(const person& that)
{
    name = new char[strlen(that.name) + 1];
    strcpy(name, that.name);
    age = that.age;
}

// 2. copy assignment operator
person& operator=(const person& that)
{
    if (this != &that)
    {
        delete[] name;
        // This is a dangerous point in the flow of execution!
        // We have temporarily invalidated the class invariants,
        // and the next statement might throw an exception,
        // leaving the object in an invalid state :(
        name = new char[strlen(that.name) + 1];
        strcpy(name, that.name);
        age = that.age;
    }
    return *this;
}

Note the difference between initialization and assignment: we must tear down the old state before assigning to name to prevent memory leaks. Also, we have to protect against self-assignment of the form x = x. Without that check, delete[] name would delete the array containing the source string, because when you write x = x, both this->name and that.name contain the same pointer.

Exception safety

Unfortunately, this solution will fail if new char[...] throws an exception due to memory exhaustion. One possible solution is to introduce a local variable and reorder the statements:

// 2. copy assignment operator
person& operator=(const person& that)
{
    char* local_name = new char[strlen(that.name) + 1];
    // If the above statement throws,
    // the object is still in the same state as before.
    // None of the following statements will throw an exception :)
    strcpy(local_name, that.name);
    delete[] name;
    name = local_name;
    age = that.age;
    return *this;
}

This also takes care of self-assignment without an explicit check. An even more robust solution to this problem is the copy-and-swap idiom, but I will not go into the details of exception safety here. I only mentioned exceptions to make the following point: Writing classes that manage resources is hard.

Noncopyable resources

Some resources cannot or should not be copied, such as file handles or mutexes. In that case, simply declare the copy constructor and copy assignment operator as private without giving a definition:

private:

    person(const person& that);
    person& operator=(const person& that);

Alternatively, you can inherit from boost::noncopyable or declare them as deleted (in C++11 and above):

person(const person& that) = delete;
person& operator=(const person& that) = delete;

The rule of three

Sometimes you need to implement a class that manages a resource. (Never manage multiple resources in a single class, this will only lead to pain.) In that case, remember the rule of three:

If you need to explicitly declare either the destructor, copy constructor or copy assignment operator yourself, you probably need to explicitly declare all three of them.

(Unfortunately, this "rule" is not enforced by the C++ standard or any compiler I am aware of.)

The rule of five

From C++11 on, an object has 2 extra special member functions: the move constructor and move assignment. The rule of five states to implement these functions as well.

An example with the signatures:

class person
{
    std::string name;
    int age;

public:
    person(const std::string& name, int age);        // Ctor
    person(const person &) = default;                // 1/5: Copy Ctor
    person(person &&) noexcept = default;            // 4/5: Move Ctor
    person& operator=(const person &) = default;     // 2/5: Copy Assignment
    person& operator=(person &&) noexcept = default; // 5/5: Move Assignment
    ~person() noexcept = default;                    // 3/5: Dtor
};

The rule of zero

The rule of 3/5 is also referred to as the rule of 0/3/5. The zero part of the rule states that you are allowed to not write any of the special member functions when creating your class.

Advice

Most of the time, you do not need to manage a resource yourself, because an existing class such as std::string already does it for you. Just compare the simple code using a std::string member to the convoluted and error-prone alternative using a char* and you should be convinced. As long as you stay away from raw pointer members, the rule of three is unlikely to concern your own code.

How to do constructor chaining in C#

I have a diary class and so i am not writing setting the values again and again

public Diary() {
    this.Like = defaultLike;
    this.Dislike = defaultDislike;
}

public Diary(string title, string diary): this()
{
    this.Title = title;
    this.DiaryText = diary;
}

public Diary(string title, string diary, string category): this(title, diary) {
    this.Category = category;
}

public Diary(int id, string title, string diary, string category)
    : this(title, diary, category)
{
    this.DiaryID = id;
}

Avoid browser popup blockers

The easiest way to get rid of this is to:

  1. Dont use document.open().
  2. Instead use this.document.location.href = location; where location is the url to be loaded

Ex :

<script>
function loadUrl(location)
{
this.document.location.href = location;
}</script>

<div onclick="loadUrl('company_page.jsp')">Abc</div>

This worked very well for me. Cheers

What is the equivalent to getch() & getche() in Linux?

There is a getch() function in the ncurses library. You can get it by installing the ncurses-dev package.

See last changes in svn

If you have not yet commit you last changes before vacation. - Command line to the project folder. - Type 'svn diff'

If you already commit you last changes before vacation.

  • Browse to your project.
  • Find a link "View log". Click it.
  • Select top two revision and Click "Compare Revisions" button in the bottom. This will show you the different between the latest and the previous revision.

Convert RGB values to Integer

int rgb = new Color(r, g, b).getRGB();

find if an integer exists in a list of integers

bool vExist = false;
int vSelectValue = 1;

List<int> vList = new List<int>();
vList.Add(1);
vList.Add(2);

IEnumerable vRes = (from n in vListwhere n == vSelectValue);
if (vRes.Count > 0) {
    vExist = true;
}

center image in div with overflow hidden

I have been trying to implement Jaap's answer inside this page of my recent site, with one difference : the .main {height:} was set to auto instead of a fixed px value. As responsive developer i am looking for a solution to synchronize the image height with the left floating text element, yet only in case my text height becomes greater then my actual image height. In that case the image should not be rescaled, but cropped and centered as decribed in the original question here above. Can this be done ? You can simulate the behaviour by slowly downsizing the browser's width.

Correlation heatmap

  1. Use the 'jet' colormap for a transition between blue and red.
  2. Use pcolor() with the vmin, vmax parameters.

It is detailed in this answer: https://stackoverflow.com/a/3376734/21974

How to ignore a property in class if null, using json.net

To expound slightly on GlennG's very helpful answer (translating the syntax from C# to VB.Net is not always "obvious") you can also decorate individual class properties to manage how null values are handled. If you do this don't use the global JsonSerializerSettings from GlennG's suggestion, otherwise it will override the individual decorations. This comes in handy if you want a null item to appear in the JSON so the consumer doesn't have to do any special handling. If, for example, the consumer needs to know an array of optional items is normally available, but is currently empty... The decoration in the property declaration looks like this:

<JsonPropertyAttribute("MyProperty", DefaultValueHandling:=NullValueHandling.Include)> Public Property MyProperty As New List(of String)

For those properties you don't want to have appear at all in the JSON change :=NullValueHandling.Include to :=NullValueHandling.Ignore. By the way - I've found that you can decorate a property for both XML and JSON serialization just fine (just put them right next to each other). This gives me the option to call the XML serializer in dotnet or the NewtonSoft serializer at will - both work side-by-side and my customers have the option to work with XML or JSON. This is slick as snot on a doorknob since I have customers that require both!

No signing certificate "iOS Distribution" found

Tried the above solutions with no luck ... restarted my mac solved the issue...

How to Correctly Use Lists in R?

Although this is a pretty old question I must say it is touching exactly the knowledge I was missing during my first steps in R - i.e. how to express data in my hand as an object in R or how to select from existing objects. It is not easy for an R novice to think "in an R box" from the very beginning.

So I myself started to use crutches below which helped me a lot to find out what object to use for what data, and basically to imagine real-world usage.

Though I not giving exact answers to the question the short text below might help the reader who just started with R and is asking similar questions.

  • Atomic vector ... I called that "sequence" for myself, no direction, just sequence of same types. [ subsets.
  • Vector ... the sequence with one direction from 2D, [ subsets.
  • Matrix ... bunch of vectors with the same length forming rows or columns, [ subsets by rows and columns, or by sequence.
  • Arrays ... layered matrices forming 3D
  • Dataframe ... a 2D table like in excel, where I can sort, add or remove rows or columns or make arit. operations with them, only after some time I truly recognized that data frame is a clever implementation of list where I can subset using [ by rows and columns, but even using [[.
  • List ... to help myself I thought about the list as of tree structure where [i] selects and returns whole branches and [[i]] returns item from the branch. And because it is tree like structure, you can even use an index sequence to address every single leaf on a very complex list using its [[index_vector]]. Lists can be simple or very complex and can mix together various types of objects into one.

So for lists you can end up with more ways how to select a leaf depending on situation like in the following example.

l <- list("aaa",5,list(1:3),LETTERS[1:4],matrix(1:9,3,3))
l[[c(5,4)]] # selects 4 from matrix using [[index_vector]] in list
l[[5]][4] # selects 4 from matrix using sequential index in matrix
l[[5]][1,2] # selects 4 from matrix using row and column in matrix

This way of thinking helped me a lot.

How to export settings?

I'm preferred my own way to synchronize all Visual Studio Code extensions between laptops, using .dotfiles and small script to perform updates automatically. This way helps me every time when I want to install all extensions I have without any single mouse activity in Visual Studio Code after installing (via Homebrew).

So I just write each new added extension to .txt file stored at my .dotfiles folder. After that I pull master branch on another laptop to get up-to-date file with all extensions.

Using the script, which Big Rich had written before, with one more change, I can totally synchronise all extensions almost automatically.

Script

cat dart-extensions.txt | xargs -L 1 code --install-extension

And also there is one more way to automate that process. Here you can add a script which looks up a Visual Studio Code extension in realtime and each time when you take a diff between the code --list-extensions command and your .txt file in .dotfiles, you can easily update your file and push it to your remote repository.

How do I convert a calendar week into a date in Excel?

For ISO week numbers you can use this formula to get the Monday

=DATE(A2,1,-2)-WEEKDAY(DATE(A2,1,3))+B2*7

assuming year in A2 and week number in B2

it's the same as my answer here https://stackoverflow.com/a/10855872/1124287

Simple way to unzip a .zip file using zlib

Minizip does have an example programs to demonstrate its usage - the files are called minizip.c and miniunz.c.

Update: I had a few minutes so I whipped up this quick, bare bones example for you. It's very smelly C, and I wouldn't use it without major improvements. Hopefully it's enough to get you going for now.

// uzip.c - Simple example of using the minizip API.
// Do not use this code as is! It is educational only, and probably
// riddled with errors and leaks!
#include <stdio.h>
#include <string.h>

#include "unzip.h"

#define dir_delimter '/'
#define MAX_FILENAME 512
#define READ_SIZE 8192

int main( int argc, char **argv )
{
    if ( argc < 2 )
    {
        printf( "usage:\n%s {file to unzip}\n", argv[ 0 ] );
        return -1;
    }

    // Open the zip file
    unzFile *zipfile = unzOpen( argv[ 1 ] );
    if ( zipfile == NULL )
    {
        printf( "%s: not found\n" );
        return -1;
    }

    // Get info about the zip file
    unz_global_info global_info;
    if ( unzGetGlobalInfo( zipfile, &global_info ) != UNZ_OK )
    {
        printf( "could not read file global info\n" );
        unzClose( zipfile );
        return -1;
    }

    // Buffer to hold data read from the zip file.
    char read_buffer[ READ_SIZE ];

    // Loop to extract all files
    uLong i;
    for ( i = 0; i < global_info.number_entry; ++i )
    {
        // Get info about current file.
        unz_file_info file_info;
        char filename[ MAX_FILENAME ];
        if ( unzGetCurrentFileInfo(
            zipfile,
            &file_info,
            filename,
            MAX_FILENAME,
            NULL, 0, NULL, 0 ) != UNZ_OK )
        {
            printf( "could not read file info\n" );
            unzClose( zipfile );
            return -1;
        }

        // Check if this entry is a directory or file.
        const size_t filename_length = strlen( filename );
        if ( filename[ filename_length-1 ] == dir_delimter )
        {
            // Entry is a directory, so create it.
            printf( "dir:%s\n", filename );
            mkdir( filename );
        }
        else
        {
            // Entry is a file, so extract it.
            printf( "file:%s\n", filename );
            if ( unzOpenCurrentFile( zipfile ) != UNZ_OK )
            {
                printf( "could not open file\n" );
                unzClose( zipfile );
                return -1;
            }

            // Open a file to write out the data.
            FILE *out = fopen( filename, "wb" );
            if ( out == NULL )
            {
                printf( "could not open destination file\n" );
                unzCloseCurrentFile( zipfile );
                unzClose( zipfile );
                return -1;
            }

            int error = UNZ_OK;
            do    
            {
                error = unzReadCurrentFile( zipfile, read_buffer, READ_SIZE );
                if ( error < 0 )
                {
                    printf( "error %d\n", error );
                    unzCloseCurrentFile( zipfile );
                    unzClose( zipfile );
                    return -1;
                }

                // Write data to file.
                if ( error > 0 )
                {
                    fwrite( read_buffer, error, 1, out ); // You should check return of fwrite...
                }
            } while ( error > 0 );

            fclose( out );
        }

        unzCloseCurrentFile( zipfile );

        // Go the the next entry listed in the zip file.
        if ( ( i+1 ) < global_info.number_entry )
        {
            if ( unzGoToNextFile( zipfile ) != UNZ_OK )
            {
                printf( "cound not read next file\n" );
                unzClose( zipfile );
                return -1;
            }
        }
    }

    unzClose( zipfile );

    return 0;
}

I built and tested it with MinGW/MSYS on Windows like this:

contrib/minizip/$ gcc -I../.. -o unzip uzip.c unzip.c ioapi.c ../../libz.a
contrib/minizip/$ ./unzip.exe /j/zlib-125.zip

How to decode HTML entities using jQuery?

Use

myString = myString.replace( /\&amp;/g, '&' );

It is easiest to do it on the server side because apparently JavaScript has no native library for handling entities, nor did I find any near the top of search results for the various frameworks that extend JavaScript.

Search for "JavaScript HTML entities", and you might find a few libraries for just that purpose, but they'll probably all be built around the above logic - replace, entity by entity.

Redis: Show database size/size for keys

Perhaps you can do some introspection on the db file. The protocol is relatively simple (yet not well documented), so you could write a parser for it to determine which individual keys are taking up a lot of space.


New suggestions:

Have you tried using MONITOR to see what is being written, live? Perhaps you can find the issue with the data in motion.

Excel VBA Automation Error: The object invoked has disconnected from its clients

You must have used the object, released it ("disconnect"), and used it again. Release object only after you're finished with it, or when calling Form_Closing.

Can one class extend two classes?

In Groovy, you can use trait instead of class. As they act similar to abstract classes (in the way that you can specify abstract methods, but you can still implement others), you can do something like:

trait EmployeeTrait {
    int getId() {
         return 1000 //Default value
    }
    abstract String getName() //Required
}

trait CustomerTrait {
    String getCompany() {
        return "Internal" // Default value
    }
    abstract String getAddress()
}

class InternalCustomer implements EmployeeTrait, CustomerTrait {
    String getName() { ... }
    String getAddress() { ... }
}

def internalCustomer = new InternalCustomer()
println internalCustomer.id // 1000
println internalCustomer.company //Internal

Just to point out, its not exactly the same as extending two classes, but in some cases (like the above example), it can solve the situation. I strongly suggest to analyze your design before jumping into using traits, usually they are not required and you won't be able to nicely implement inheritance (for example, you can't use protected methods in traits). Follow the accepted answer's recommendation if possible.

PowerShell: Run command from script's directory

I often used the following code to import a module which sit under the same directory as the running script. It will first get the directory from which powershell is running

$currentPath=Split-Path ((Get-Variable MyInvocation -Scope 0).Value).MyCommand.Path

import-module "$currentPath\sqlps.ps1"

Difference between DataFrame, Dataset, and RDD in Spark

Few insights from usage perspective, RDD vs DataFrame:

  1. RDDs are amazing! as they give us all the flexibility to deal with almost any kind of data; unstructured, semi structured and structured data. As, lot of times data is not ready to be fit into a DataFrame, (even JSON), RDDs can be used to do preprocessing on the data so that it can fit in a dataframe. RDDs are core data abstraction in Spark.
  2. Not all transformations that are possible on RDD are possible on DataFrames, example subtract() is for RDD vs except() is for DataFrame.
  3. Since DataFrames are like a relational table, they follow strict rules when using set/relational theory transformations, for example if you wanted to union two dataframes the requirement is that both dfs have same number of columns and associated column datatypes. Column names can be different. These rules don't apply to RDDs. Here is a good tutorial explaining these facts.
  4. There are performance gains when using DataFrames as others have already explained in depth.
  5. Using DataFrames you don't need to pass the arbitrary function as you do when programming with RDDs.
  6. You need the SQLContext/HiveContext to program dataframes as they lie in SparkSQL area of spark eco-system, but for RDD you only need SparkContext/JavaSparkContext which lie in Spark Core libraries.
  7. You can create a df from a RDD if you can define a schema for it.
  8. You can also convert a df to rdd and rdd to df.

I hope it helps!

Mongoose's find method with $or condition does not work properly

I implore everyone to use Mongoose's query builder language and promises instead of callbacks:

User.find().or([{ name: param }, { nickname: param }])
    .then(users => { /*logic here*/ })
    .catch(error => { /*error logic here*/ })

Read more about Mongoose Queries.

Loop through files in a directory using PowerShell

Other answers are great, I just want to add... a different approach usable in PowerShell: Install GNUWin32 utils and use grep to view the lines / redirect the output to file http://gnuwin32.sourceforge.net/

This overwrites the new file every time:

grep "step[49]" logIn.log > logOut.log 

This appends the log output, in case you overwrite the logIn file and want to keep the data:

grep "step[49]" logIn.log >> logOut.log 

Note: to be able to use GNUWin32 utils globally you have to add the bin folder to your system path.

Return char[]/string from a function

you can use a static array in your method, to avoid lose of your array when your function ends :

char * createStr() 
{
    char char1= 'm';
    char char2= 'y';

    static char str[3];  
    str[0] = char1;
    str[1] = char2;
    str[2] = '\0';

    return str;
}

Edit : As Toby Speight mentioned this approach is not thread safe, and also recalling the function leads to data overwrite that is unwanted in some applications. So you have to save the data in a buffer as soon as you return back from the function. (However because it is not thread safe method, concurrent calls could still make problem in some cases, and to prevent this you have to use lock. capture it when entering the function and release it after copy is done, i prefer not to use this approach because its messy and error prone.)

html5 - canvas element - Multiple layers

You can create multiple canvas elements without appending them into document. These will be your layers:

Then do whatever you want with them and at the end just render their content in proper order at destination canvas using drawImage on context.

Example:

/* using canvas from DOM */
var domCanvas = document.getElementById('some-canvas');
var domContext = domCanvas.getContext('2d');
domContext.fillRect(50,50,150,50);

/* virtual canvase 1 - not appended to the DOM */
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'blue';
ctx.fillRect(50,50,150,150);

/* virtual canvase 2 - not appended to the DOM */    
var canvas2 = document.createElement('canvas')
var ctx2 = canvas2.getContext('2d');
ctx2.fillStyle = 'yellow';
ctx2.fillRect(50,50,100,50)

/* render virtual canvases on DOM canvas */
domContext.drawImage(canvas, 0, 0, 200, 200);
domContext.drawImage(canvas2, 0, 0, 200, 200);

And here is some codepen: https://codepen.io/anon/pen/mQWMMW

Setting Column width in Apache POI

You can use also util methods mentioned in this blog: Getting cell witdth and height from excel with Apache POI. It can solve your problem.

Copy & paste from that blog:

static public class PixelUtil {

    public static final short EXCEL_COLUMN_WIDTH_FACTOR = 256;
    public static final short EXCEL_ROW_HEIGHT_FACTOR = 20;
    public static final int UNIT_OFFSET_LENGTH = 7;
    public static final int[] UNIT_OFFSET_MAP = new int[] { 0, 36, 73, 109, 146, 182, 219 };

    public static short pixel2WidthUnits(int pxs) {
        short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR * (pxs / UNIT_OFFSET_LENGTH));
        widthUnits += UNIT_OFFSET_MAP[(pxs % UNIT_OFFSET_LENGTH)];
        return widthUnits;
    }

    public static int widthUnits2Pixel(short widthUnits) {
        int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR) * UNIT_OFFSET_LENGTH;
        int offsetWidthUnits = widthUnits % EXCEL_COLUMN_WIDTH_FACTOR;
        pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH));
        return pixels;
    }

    public static int heightUnits2Pixel(short heightUnits) {
        int pixels = (heightUnits / EXCEL_ROW_HEIGHT_FACTOR);
        int offsetWidthUnits = heightUnits % EXCEL_ROW_HEIGHT_FACTOR;
        pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_ROW_HEIGHT_FACTOR / UNIT_OFFSET_LENGTH));
        return pixels;
    }
}

So when you want to get cell width and height you can use this to get value in pixel, values are approximately.

PixelUtil.heightUnits2Pixel((short) row.getHeight())
PixelUtil.widthUnits2Pixel((short) sh.getColumnWidth(columnIndex));

How to communicate between Docker containers via "hostname"

That should be what --link is for, at least for the hostname part.
With docker 1.10, and PR 19242, that would be:

docker network create --net-alias=[]: Add network-scoped alias for the container

(see last section below)

That is what Updating the /etc/hosts file details

In addition to the environment variables, Docker adds a host entry for the source container to the /etc/hosts file.

For instance, launch an LDAP server:

docker run -t  --name openldap -d -p 389:389 larrycai/openldap

And define an image to test that LDAP server:

FROM ubuntu
RUN apt-get -y install ldap-utils
RUN touch /root/.bash_aliases
RUN echo "alias lds='ldapsearch -H ldap://internalopenldap -LL -b
ou=Users,dc=openstack,dc=org -D cn=admin,dc=openstack,dc=org -w
password'" > /root/.bash_aliases
ENTRYPOINT bash

You can expose the 'openldap' container as 'internalopenldap' within the test image with --link:

 docker run -it --rm --name ldp --link openldap:internalopenldap ldaptest

Then, if you type 'lds', that alias will work:

ldapsearch -H ldap://internalopenldap ...

That would return people. Meaning internalopenldap is correctly reached from the ldaptest image.


Of course, docker 1.7 will add libnetwork, which provides a native Go implementation for connecting containers. See the blog post.
It introduced a more complete architecture, with the Container Network Model (CNM)

https://blog.docker.com/media/2015/04/cnm-model.jpg

That will Update the Docker CLI with new “network” commands, and document how the “-net” flag is used to assign containers to networks.


docker 1.10 has a new section Network-scoped alias, now officially documented in network connect:

While links provide private name resolution that is localized within a container, the network-scoped alias provides a way for a container to be discovered by an alternate name by any other container within the scope of a particular network.
Unlike the link alias, which is defined by the consumer of a service, the network-scoped alias is defined by the container that is offering the service to the network.

Continuing with the above example, create another container in isolated_nw with a network alias.

$ docker run --net=isolated_nw -itd --name=container6 -alias app busybox
8ebe6767c1e0361f27433090060b33200aac054a68476c3be87ef4005eb1df17

--alias=[]         

Add network-scoped alias for the container

You can use --link option to link another container with a preferred alias

You can pause, restart, and stop containers that are connected to a network. Paused containers remain connected and can be revealed by a network inspect. When the container is stopped, it does not appear on the network until you restart it.

If specified, the container's IP address(es) is reapplied when a stopped container is restarted. If the IP address is no longer available, the container fails to start.

One way to guarantee that the IP address is available is to specify an --ip-range when creating the network, and choose the static IP address(es) from outside that range. This ensures that the IP address is not given to another container while this container is not on the network.

$ docker network create --subnet 172.20.0.0/16 --ip-range 172.20.240.0/20 multi-host-network

$ docker network connect --ip 172.20.128.2 multi-host-network container2
$ docker network connect --link container1:c1 multi-host-network container2

Map to String in Java

Use Object#toString().

String string = map.toString();

That's after all also what System.out.println(object) does under the hoods. The format for maps is described in AbstractMap#toString().

Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).

Auto margins don't center image in page

there is a alternative to margin-left:auto; margin-right: auto; or margin:0 auto; for the ones that use position:absolute; this is how:
you set the left position of the element to 50% (left:50%;) but that will not center it correctly in order for the element to be centered correctly you need to give it a margin of minus half of it`s width, that will center your element perfectly

here is an example: http://jsfiddle.net/35ERq/3/

Angular : Manual redirect to route

Redirect to another page using function on component.ts file

componene.ts:

import {Router} from '@angular/router';
constructor(private router: Router) {}

OnClickFunction()
  {
    this.router.navigate(['/home']);
  }

component.html:

<div class="col-3">                  
<button (click)="OnClickFunction()" class="btn btn-secondary btn-custom mr-3">Button Name</button>
</div>

Read only file system on Android

Try the following on the command prompt:

>adb remount
>adb push framework-res_old.apk /system/framework-res.apk

How to enter special characters like "&" in oracle database?

Also you can use concat like this :D

Insert into Table Value(CONCAT('JAVA ',CONCAT('& ', 'Oracle'));

Setting up enviromental variables in Windows 10 to use java and javac

Its still the same concept, you'll need to setup path variable so that windows is aware of the java executable and u can run it from command prompt conveniently

Details from the java's own page: https://java.com/en/download/help/path.xml That article applies to: •Platform(s): Solaris SPARC, Solaris x86, Red Hat Linux, SUSE Linux, Windows 8, Windows 7, Vista, Windows XP, Windows 10

how to write value into cell with vba code without auto type conversion?

This is probably too late, but I had a similar problem with dates that I wanted entered into cells from a text variable. Inevitably, it converted my variable text value to a date. What I finally had to do was concatentate a ' to the string variable and then put it in the cell like this:

prvt_rng_WrkSht.Cells(prvt_rng_WrkSht.Rows.Count, cnst_int_Col_Start_Date).Formula = "'" & _ 
    param_cls_shift.Start_Date (string property of my class) 

CMake: How to build external projects and include their targets

cmake's ExternalProject_Add indeed can used, but what I did not like about it - is that it performs something during build, continuous poll, etc... I would prefer to build project during build phase, nothing else. I have tried to override ExternalProject_Add in several attempts, unfortunately without success.

Then I have tried also to add git submodule, but that drags whole git repository, while in certain cases I need only subset of whole git repository. What I have checked - it's indeed possible to perform sparse git checkout, but that require separate function, which I wrote below.

#-----------------------------------------------------------------------------
#
# Performs sparse (partial) git checkout
#
#   into ${checkoutDir} from ${url} of ${branch}
#
# List of folders and files to pull can be specified after that.
#-----------------------------------------------------------------------------
function (SparseGitCheckout checkoutDir url branch)
    if(EXISTS ${checkoutDir})
        return()
    endif()

    message("-------------------------------------------------------------------")
    message("sparse git checkout to ${checkoutDir}...")
    message("-------------------------------------------------------------------")

    file(MAKE_DIRECTORY ${checkoutDir})

    set(cmds "git init")
    set(cmds ${cmds} "git remote add -f origin --no-tags -t master ${url}")
    set(cmds ${cmds} "git config core.sparseCheckout true")

    # This command is executed via file WRITE
    # echo <file or folder> >> .git/info/sparse-checkout")

    set(cmds ${cmds} "git pull --depth=1 origin ${branch}")

    # message("In directory: ${checkoutDir}")

    foreach( cmd ${cmds})
        message("- ${cmd}")
        string(REPLACE " " ";" cmdList ${cmd})

        #message("Outfile: ${outFile}")
        #message("Final command: ${cmdList}")

        if(pull IN_LIST cmdList)
            string (REPLACE ";" "\n" FILES "${ARGN}")
            file(WRITE ${checkoutDir}/.git/info/sparse-checkout ${FILES} )
        endif()

        execute_process(
            COMMAND ${cmdList}
            WORKING_DIRECTORY ${checkoutDir}
            RESULT_VARIABLE ret
        )

        if(NOT ret EQUAL "0")
            message("error: previous command failed, see explanation above")
            file(REMOVE_RECURSE ${checkoutDir})
            break()
        endif()
    endforeach()

endfunction()


SparseGitCheckout(${CMAKE_BINARY_DIR}/catch_197 https://github.com/catchorg/Catch2.git v1.9.7 single_include)
SparseGitCheckout(${CMAKE_BINARY_DIR}/catch_master https://github.com/catchorg/Catch2.git master single_include)

I have added two function calls below just to illustrate how to use the function.

Someone might not like to checkout master / trunk, as that one might be broken - then it's always possible to specify specific tag.

Checkout will be performed only once, until you clear the cache folder.

Getting Java version at runtime

Just a note that in Java 9 and above, the naming convention is different. System.getProperty("java.version") returns "9" rather than "1.9".

Mongoose delete array element in document and save

The checked answer does work but officially in MongooseJS latest, you should use pull.

doc.subdocs.push({ _id: 4815162342 }) // added
doc.subdocs.pull({ _id: 4815162342 }) // removed

https://mongoosejs.com/docs/api.html#mongoosearray_MongooseArray-pull

I was just looking that up too.

See Daniel's answer for the correct answer. Much better.

How to disable anchor "jump" when loading a page?

Another approach

Try checking if the page has been scrolled and only then reset position:

var scrolled = false;

$(window).scroll(function(){
  scrolled = true;
});

if ( window.location.hash && scrolled ) {
  $(window).scrollTop( 0 );
}

Heres a demo

How to save data file into .RData?

Alternatively, when you want to save individual R objects, I recommend using saveRDS.

You can save R objects using saveRDS, then load them into R with a new variable name using readRDS.

Example:

# Save the city object
saveRDS(city, "city.rds")

# ...

# Load the city object as city
city <- readRDS("city.rds")

# Or with a different name
city2 <- readRDS("city.rds")

But when you want to save many/all your objects in your workspace, use Manetheran's answer.

Get the height and width of the browser viewport without scrollbars using jquery?

$(document).ready(function() {

  //calculate the window height & add css properties for height 100%

  wh = $( window ).height();

  ww = $( window ).width();

  $(".targeted-div").css({"height": wh, "width": ww});

});

How to change users in TortoiseSVN

Replace the line in htpasswd file:

Go to: http://www.htaccesstools.com/htpasswd-generator-windows/

(If the link is expired, search another generator from google.com.)

Enter your username and password. The site will generate an encrypted line. Copy that line and replace it with the previous line in the file "repo/htpasswd".

You might also need to Clear the 'Authentication data' from TortoiseSVN ? Settings ? Saved Data.

How do you properly return multiple values from a Promise?

Here is how I reckon you should be doing.

splitting the chain

Because both functions will be using amazingData, it makes sense to have them in a dedicated function. I usually do that everytime I want to reuse some data, so it is always present as a function arg.

As your example is running some code, I will suppose it is all declared inside a function. I will call it toto(). Then we will have another function which will run both afterSomething() and afterSomethingElse().

function toto() {
    return somethingAsync()
        .then( tata );
}

You will also notice I added a return statement as it is usually the way to go with Promises - you always return a promise so we can keep chaining if required. Here, somethingAsync() will produce amazingData and it will be available everywhere inside the new function.

Now what this new function will look like typically depends on is processAsync() also asynchronous?

processAsync not asynchronous

No reason to overcomplicate things if processAsync() is not asynchronous. Some old good sequential code would make it.

function tata( amazingData ) {
    var processed = afterSomething( amazingData );
    return afterSomethingElse( amazingData, processed );
}

function afterSomething( amazingData ) {
    return processAsync( amazingData );
}
function afterSomethingElse( amazingData, processedData ) {
}

Note that it does not matter if afterSomethingElse() is doing something async or not. If it does, a promise will be returned and the chain can continue. If it is not, then the result value will be returned. But because the function is called from a then(), the value will be wrapped into a promise anyway (at least in raw Javascript).

processAsync asynchronous

If processAsync() is asynchronous, the code will look slightly different. Here we consider afterSomething() and afterSomethingElse() are not going to be reused anywhere else.

function tata( amazingData ) {
    return afterSomething()
        .then( afterSomethingElse );

    function afterSomething( /* no args */ ) {
        return processAsync( amazingData );
    }
    function afterSomethingElse( processedData ) {
        /* amazingData can be accessed here */
    }
}

Same as before for afterSomethingElse(). It can be asynchronous or not. A promise will be returned, or a value wrapped into a resolved promise.


Your coding style is quite close to what I use to do, that is why I answered even after 2 years. I am not a big fan of having anonymous functions everywhere. I find it hard to read. Even if it is quite common in the community. It is as we replaced the callback-hell by a promise-purgatory.

I also like to keep the name of the functions in the then short. They will only be defined locally anyway. And most of the time they will call another function defined elsewhere - so reusable - to do the job. I even do that for functions with only 1 parameter, so I do not need to get the function in and out when I add/remove a parameter to the function signature.

Eating example

Here is an example:

function goingThroughTheEatingProcess(plenty, of, args, to, match, real, life) {
    return iAmAsync()
        .then(chew)
        .then(swallow);

        function chew(result) {
            return carefullyChewThis(plenty, of, args, "water", "piece of tooth", result);
        }

        function swallow(wine) {
            return nowIsTimeToSwallow(match, real, life, wine);
        }
}

function iAmAsync() {
    return Promise.resolve("mooooore");
}

function carefullyChewThis(plenty, of, args, and, some, more) {
    return true;
}

function nowIsTimeToSwallow(match, real, life, bobool) {
}

Do not focus too much on the Promise.resolve(). It is just a quick way to create a resolved promise. What I try to achieve by this is to have all the code I am running in a single location - just underneath the thens. All the others functions with a more descriptive name are reusable.

The drawback with this technique is that it is defining a lot of functions. But it is a necessary pain I am afraid in order to avoid having anonymous functions all over the place. And what is the risk anyway: a stack overflow? (joke!)


Using arrays or objects as defined in other answers would work too. This one in a way is the answer proposed by Kevin Reid.

You can also use bind() or Promise.all(). Note that they will still require you to split your code.

using bind

If you want to keep your functions reusable but do not really need to keep what is inside the then very short, you can use bind().

function tata( amazingData ) {
    return afterSomething( amazingData )
        .then( afterSomethingElse.bind(null, amazingData) );
}

function afterSomething( amazingData ) {
    return processAsync( amazingData );
}
function afterSomethingElse( amazingData, processedData ) {
}

To keep it simple, bind() will prepend the list of args (except the first one) to the function when it is called.

using Promise.all

In your post you mentionned the use of spread(). I never used the framework you are using, but here is how you should be able to use it.

Some believe Promise.all() is the solution to all problems, so it deserves to be mentioned I guess.

function tata( amazingData ) {
    return Promise.all( [ amazingData, afterSomething( amazingData ) ] )
        .then( afterSomethingElse );
}

function afterSomething( amazingData ) {
    return processAsync( amazingData );
}
function afterSomethingElse( args ) {
    var amazingData = args[0];
    var processedData = args[1];
}

You can pass data to Promise.all() - note the presence of the array - as long as promises, but make sure none of the promises fail otherwise it will stop processing.

And instead of defining new variables from the args argument, you should be able to use spread() instead of then() for all sort of awesome work.

Adding horizontal spacing between divs in Bootstrap 3

From what I understand you want to make a navigation bar or something similar to it. What I recommend doing is making a list and editing the items from there. Just try this;

<ul>
    <li class='item col-md-12 panel' id='gameplay-title'>Title</li>
    <li class='item col-md-6 col-md-offset-3 panel' id='gameplay-scoreboard'>Scoreboard</li>
</ul>

And so on... To add more categories add another ul in there. Now, for the CSS you just need this;

ul {
    list-style: none;
}
.item {
    display: inline;
    padding-right: 20px;
}

How to disable javax.swing.JButton in java?

For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button

You need that code to be in the actionPerformed(...) of the ActionListener registered with the Start button, not for the Start button itself.

You can add a simple ActionListener like this:

JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent ae) {
        startButton.setEnabled(false);
        stopButton.setEnabled(true);
     }
   }
 );

note that your startButton above will need to be final in the above example if you want to create the anonymous listener in local scope.

Difference between numpy dot() and Python 3.5+ matrix multiplication @

The @ operator calls the array's __matmul__ method, not dot. This method is also present in the API as the function np.matmul.

>>> a = np.random.rand(8,13,13)
>>> b = np.random.rand(8,13,13)
>>> np.matmul(a, b).shape
(8, 13, 13)

From the documentation:

matmul differs from dot in two important ways.

  • Multiplication by scalars is not allowed.
  • Stacks of matrices are broadcast together as if the matrices were elements.

The last point makes it clear that dot and matmul methods behave differently when passed 3D (or higher dimensional) arrays. Quoting from the documentation some more:

For matmul:

If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly.

For np.dot:

For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors (without complex conjugation). For N dimensions it is a sum product over the last axis of a and the second-to-last of b

HTTP POST Returns Error: 417 "Expectation Failed."

Another way -

Add these lines to your application config file configuration section:

<system.net>
    <settings>
        <servicePointManager expect100Continue="false" />
    </settings>
</system.net>

AngularJS - Access to child scope

While jm-'s answer is the best way to handle this case, for future reference it is possible to access child scopes using a scope's $$childHead, $$childTail, $$nextSibling and $$prevSibling members. These aren't documented so they might change without notice, but they're there if you really need to traverse scopes.

// get $$childHead first and then iterate that scope's $$nextSiblings
for(var cs = scope.$$childHead; cs; cs = cs.$$nextSibling) {
    // cs is child scope
}

Fiddle

How to access elements of a JArray (or iterate over them)

Once you have a JArray you can treat it just like any other Enumerable object, and using linq you can access them, check them, verify them, and select them.

var str = @"[1, 2, 3]";
var jArray = JArray.Parse(str);
Console.WriteLine(String.Join("-", jArray.Where(i => (int)i > 1).Select(i => i.ToString())));

Select first empty cell in column F starting from row 1. (without using offset )

I just wrote this one-liner to select the first empty cell found in a column based on a selected cell. Only works on first column of selected cells. Modify as necessary

Selection.End(xlDown).Range("A2").Select

Shell script to delete directories older than n days

OR

rm -rf `find /path/to/base/dir/* -type d -mtime +10`

Updated, faster version of it:

find /path/to/base/dir/* -mtime +10 -print0 | xargs -0 rm -f

How to disable right-click context-menu in JavaScript

You can't rely on context menus because the user can deactivate it. Most websites want to use the feature to annoy the visitor.

Module not found: Error: Can't resolve 'core-js/es6'

Sure, I had a similar issue and a simple

npm uninstall @babel/polyfill --save &&
npm install @babel/polyfill --save

did the trick for me.

However, usage of @babel/polyfill is deprecated (according to this comment) so only try this if you think you have older packages installed or if all else fails.

How do I delete from multiple tables using INNER JOIN in SQL server

Just wondering.. is that really possible in MySQL? it will delete t1 and t2? or I just misunderstood the question.

But if you just want to delete table1 with multiple join conditions, just don't alias the table you want to delete

this:

DELETE t1,t2 
FROM table1 AS t1 
INNER JOIN table2 t2 ...
INNER JOIN table3 t3 ...

should be written like this to work in MSSQL:

DELETE table1
FROM table1 
INNER JOIN table2 t2 ...
INNER JOIN table3 t3 ...

to contrast how the other two common RDBMS do a delete operation:

http://mssql-to-postgresql.blogspot.com/2007/12/deleting-duplicates-in-postgresql-ms.html

What's the difference setting Embed Interop Types true and false in Visual Studio?

This option was introduced in order to remove the need to deploy very large PIAs (Primary Interop Assemblies) for interop.

It simply embeds the managed bridging code used that allows you to talk to unmanaged assemblies, but instead of embedding it all it only creates the stuff you actually use in code.

Read more in Scott Hanselman's blog post about it and other VS improvements here.

As for whether it is advised or not, I'm not sure as I don't need to use this feature. A quick web search yields a few leads:

The only risk of turning them all to false is more deployment concerns with PIA files and a larger deployment if some of those files are large.

How do I check if file exists in Makefile so I can delete it?

The second top answer mentions ifeq, however, it fails to mention that these must be on the same level as the name of the target, e.g., to download a file only if it doesn't currently exist, the following code could be used:

download:
ifeq (,$(wildcard ./glob.c))
    curl … -o glob.c
endif

# THIS DOES NOT WORK!
download:
    ifeq (,$(wildcard ./glob.c))
        curl … -o glob.c
    endif

How can I detect when the mouse leaves the window?

None of these answers worked for me. I'm now using:

document.addEventListener('dragleave', function(e){

    var top = e.pageY;
    var right = document.body.clientWidth - e.pageX;
    var bottom = document.body.clientHeight - e.pageY;
    var left = e.pageX;

    if(top < 10 || right < 20 || bottom < 10 || left < 10){
        console.log('Mouse has moved out of window');
    }

});

I'm using this for a drag and drop file uploading widget. It's not absolutely accurate, being triggered when the mouse gets to a certain distance from the edge of the window.

Java - Using Accessor and Mutator methods

Let's go over the basics: "Accessor" and "Mutator" are just fancy names fot a getter and a setter. A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.

So first you need to set up a class with some variables to get/set:

public class IDCard
{
    private String mName;
    private String mFileName;
    private int mID;

}

But oh no! If you instantiate this class the default values for these variables will be meaningless. B.T.W. "instantiate" is a fancy word for doing:

IDCard test = new IDCard();

So - let's set up a default constructor, this is the method being called when you "instantiate" a class.

public IDCard()
{
    mName = "";
    mFileName = "";
    mID = -1;
}

But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:

public IDCard(String name, int ID, String filename)
{
    mName = name;
    mID = ID;
    mFileName = filename;
}

Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:

public String getName()
{
    return mName;
}

public void setName( String name )
{
    mName = name;
}

Nice. Now we can access mName. Add the rest of the accessors and mutators and you're now a certified Java newbie. Good luck.

using "if" and "else" Stored Procedures MySQL

you can use CASE WHEN as follow as achieve the as IF ELSE.

SELECT FROM A a 
LEFT JOIN B b 
ON a.col1 = b.col1 
AND (CASE 
        WHEN a.col2 like '0%' then TRIM(LEADING '0' FROM a.col2)
        ELSE substring(a.col2,1,2)
    END
)=b.col2; 

p.s:just in case somebody needs this way.

Add image to layout in ruby on rails

When using the new ruby, the image folder will go to asset folder on folder app

after placing your images in image folder, use

<%=image_tag("example_image.png", alt: "Example Image")%>

How to convert the background to transparent?

If you want a command-line solution, you can use the ImageMagick convert utility:

convert input.png -transparent red output.png

Whitespaces in java

From sun docs:

\s A whitespace character: [ \t\n\x0B\f\r]

The simplest way is to use it with regex.

What are the uses of the exec command in shell scripts?

The exec built-in command mirrors functions in the kernel, there are a family of them based on execve, which is usually called from C.

exec replaces the current program in the current process, without forking a new process. It is not something you would use in every script you write, but it comes in handy on occasion. Here are some scenarios I have used it;

  1. We want the user to run a specific application program without access to the shell. We could change the sign-in program in /etc/passwd, but maybe we want environment setting to be used from start-up files. So, in (say) .profile, the last statement says something like:

     exec appln-program
    

    so now there is no shell to go back to. Even if appln-program crashes, the end-user cannot get to a shell, because it is not there - the exec replaced it.

  2. We want to use a different shell to the one in /etc/passwd. Stupid as it may seem, some sites do not allow users to alter their sign-in shell. One site I know had everyone start with csh, and everyone just put into their .login (csh start-up file) a call to ksh. While that worked, it left a stray csh process running, and the logout was two stage which could get confusing. So we changed it to exec ksh which just replaced the c-shell program with the korn shell, and made everything simpler (there are other issues with this, such as the fact that the ksh is not a login-shell).

  3. Just to save processes. If we call prog1 -> prog2 -> prog3 -> prog4 etc. and never go back, then make each call an exec. It saves resources (not much, admittedly, unless repeated) and makes shutdown simplier.

You have obviously seen exec used somewhere, perhaps if you showed the code that's bugging you we could justify its use.

Edit: I realised that my answer above is incomplete. There are two uses of exec in shells like ksh and bash - used for opening file descriptors. Here are some examples:

exec 3< thisfile          # open "thisfile" for reading on file descriptor 3
exec 4> thatfile          # open "thatfile" for writing on file descriptor 4
exec 8<> tother           # open "tother" for reading and writing on fd 8
exec 6>> other            # open "other" for appending on file descriptor 6
exec 5<&0                 # copy read file descriptor 0 onto file descriptor 5
exec 7>&4                 # copy write file descriptor 4 onto 7
exec 3<&-                 # close the read file descriptor 3
exec 6>&-                 # close the write file descriptor 6

Note that spacing is very important here. If you place a space between the fd number and the redirection symbol then exec reverts to the original meaning:

  exec 3 < thisfile       # oops, overwrite the current program with command "3"

There are several ways you can use these, on ksh use read -u or print -u, on bash, for example:

read <&3
echo stuff >&4

How do I setup the dotenv file in Node.js?

If you are facing this problem it could be that the environment variable(s) is added/loaded after the file that requires the specific variable

const express = require('express');

const app = express();
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const morgan = require('morgan');

const passport = require('passport'); //you want to use process.env.JWT_SECRET (you will get undefined)

dotenv.config();

in the above case, you will get undefined for the process.env.JWT_SECRET

So the solution is that you put dotenv.config() before const passport = require('passport');

const express = require('express');

const app = express();
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const morgan = require('morgan');
dotenv.config();   
const passport = require('passport'); //you want to use process.env.JWT_SECRET (you will get the value for the enviroment variable)

Javascript use variable as object name

If you already know the list of the possible varible names then try creating a new Object(iconObj) whose properties name are same as object names, Here in below example, iconLib variable will hold two string values , either 'ZondIcons' or 'MaterialIcons'. propertyName is the property of ZondIcons or MaterialsIcon object.

   const iconObj = {
    ZondIcons,
    MaterialIcons,
  }
  const objValue = iconObj[iconLib][propertyName]

Error: EACCES: permission denied, access '/usr/local/lib/node_modules'

Below command worked for me:

sudo npm install -g appium --unsafe-perm=true --allow-root

Configure DataSource programmatically in Spring Boot

If you want more datesource configs e.g.

spring.datasource.test-while-idle=true 
spring.datasource.time-between-eviction-runs-millis=30000
spring.datasource.validation-query=select 1

you could use below code

@Bean
public DataSource dataSource() {
    DataSource dataSource = new DataSource(); // org.apache.tomcat.jdbc.pool.DataSource;
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setTestWhileIdle(testWhileIdle);     
    dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMills);
    dataSource.setValidationQuery(validationQuery);
    return dataSource;
}

refer: Spring boot jdbc Connection

Left align and right align within div in Bootstrap

2021 Update...

Bootstrap 5 (beta)

For aligning within a flexbox div or row...

  • ml-auto is now ms-auto
  • mr-auto is now me-auto

Bootstrap 4+

  • pull-right is now float-right
  • text-right is the same as 3.x, and works for inline elements
  • both float-* and text-* are responsive for different alignment at different widths (ie: float-sm-right)

The flexbox utils (eg:justify-content-between) can also be used for alignment:

<div class="d-flex justify-content-between">
      <div>
         left
      </div>
      <div>
         right
      </div>
 </div>

or, auto-margins (eg:ml-auto) in any flexbox container (row,navbar,card,d-flex,etc...)

<div class="d-flex">
      <div>
         left
      </div>
      <div class="ml-auto">
         right
      </div>
 </div>

Bootstrap 4 Align Demo
Bootstrap 4 Right Align Examples(float, flexbox, text-right, etc...)


Bootstrap 3

Use the pull-right class..

<div class="container">
  <div class="row">
    <div class="col-md-6">Total cost</div>
    <div class="col-md-6"><span class="pull-right">$42</span></div>
  </div>
</div>

Bootstrap 3 Demo

You can also use the text-right class like this:

  <div class="row">
    <div class="col-md-6">Total cost</div>
    <div class="col-md-6 text-right">$42</div>
  </div>

Bootstrap 3 Demo 2

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

This should solve your problem. session_start() should be called before any character is sent back to the browser. In your case, HTML and blank lines were sent before you called session_start(). Documentation here.

To further explain your question of why it works when you submit to a different page, that page either do not use session_start() or calls session_start() before sending any character back to the client! This page on the other hand was calling session_start() much later when a lot of HTML has been sent back to the client (browser).

The better way to code is to have a common header file that calls connects to MySQL database, calls session_start() and does other common things for all pages and include that file on top of each page like below:

include "header.php";

This will stop issues like you are having as also allow you to have a common set of code to manage across a project. Something definitely for you to think about I would suggest after looking at your code.

<?php
session_start();

                if (isset($_SESSION['error']))

                {

                    echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";

                    unset($_SESSION['error']);

                }

                ?>

                <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">

                <p>
                 <label class="style4">Category Name</label>

                   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="categoryname" /><br /><br />

                    <label class="style4">Category Image</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

                    <input type="file" name="image" /><br />

                    <input type="hidden" name="MAX_FILE_SIZE" value="100000" />

                   <br />
<br />
 <input type="submit" id="submit" value="UPLOAD" />

                </p>

                </form>




                             <?php



require("includes/conn.php");


function is_valid_type($file)

{

    $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");



    if (in_array($file['type'], $valid_types))

        return 1;

    return 0;
}

function showContents($array)

{

    echo "<pre>";

    print_r($array);

    echo "</pre>";
}


$TARGET_PATH = "images/category";

$cname = $_POST['categoryname'];

$image = $_FILES['image'];

$cname = mysql_real_escape_string($cname);

$image['name'] = mysql_real_escape_string($image['name']);

$TARGET_PATH .= $image['name'];

if ( $cname == "" || $image['name'] == "" )

{

    $_SESSION['error'] = "All fields are required";

    header("Location: managecategories.php");

    exit;

}

if (!is_valid_type($image))

{

    $_SESSION['error'] = "You must upload a jpeg, gif, or bmp";

    header("Location: managecategories.php");

    exit;

}




if (file_exists($TARGET_PATH))

{

    $_SESSION['error'] = "A file with that name already exists";

    header("Location: managecategories.php");

    exit;

}


if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))

{



    $sql = "insert into Categories (CategoryName, FileName) values ('$cname', '" . $image['name'] . "')";

    $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());

  header("Location: mangaecategories.php");

    exit;

}

else

{





    $_SESSION['error'] = "Could not upload file.  Check read/write persmissions on the directory";

    header("Location: mangagecategories.php");

    exit;

}

?> 

Visual Studio Code pylint: Unable to import 'protorpc'

First I will check the python3 path where it lives

enter image description here

And then in the VS Code settings just add that path, for example:

"python.pythonPath": "/usr/local/bin/python3"

How do I get a list of folders and sub folders without the files?

dir /ad /b /s will give the required answer.

How to show progress bar while loading, using ajax

<script>
$(function() {
    $("#client").on("change", function() {
      var clientid=$("#client").val();
     //show the loading div here
    $.ajax({
            type:"post",
            url:"clientnetworkpricelist/yourfile.php",
        data:"title="+clientid,
        success:function(data){
             $("#result").html(data);
          //hide the loading div here
        }
    }); 
    });
});
</script>

Or you can also do this:

$(document).ajaxStart(function() {
        // show loader on start
        $("#loader").css("display","block");
    }).ajaxSuccess(function() {
        // hide loader on success
        $("#loader").css("display","none");
    });

Android XXHDPI resources

As per this PPI calculation tool, Google Nexus 10 has a display density of about 300 DPI...

However, Android documentation states that:

ldpi : ~120dpi mdpi : ~160dpi hdpi : ~240dpi xhdpi : ~320dpi xxhdpi is not specified.

I think we just let Android OS scale up xhdpi resources...

Android runOnUiThread explanation

This should work for you

 public class MyActivity extends Activity {

    protected ProgressDialog mProgressDialog;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        populateTable();
    }

    private void populateTable() {
        mProgressDialog = ProgressDialog.show(this, "Please wait","Long operation starts...", true);
        new Thread() {
            @Override
            public void run() {

                doLongOperation();
                try {

                    // code runs in a thread
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mProgressDialog.dismiss();
                        }
                    });
                } catch (final Exception ex) {
                    Log.i("---","Exception in thread");
                }
            }
        }.start();

    }

    /** fake operation for testing purpose */
    protected void doLongOperation() {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
        }

    }
}

How can I find the number of elements in an array?

void numel(int array1[100][100])
{
    int count=0;
    for(int i=0;i<100;i++)
    {
        for(int j=0;j<100;j++)
        {
            if(array1[i][j]!='\0') 
            {
                count++;
                //printf("\n%d-%d",array1[i][j],count);
            }
            else 
                break;
        }
    }
    printf("Number of elements=%d",count);
}
int main()
{   
    int r,arr[100][100]={0},c;
    printf("Enter the no. of rows: ");
    scanf("%d",&r);
    printf("\nEnter the no. of columns: ");
    scanf("%d",&c);
    printf("\nEnter the elements: ");
    for(int i=0;i<r;i++)
    {
        for(int j=0;j<c;j++)
        {
            scanf("%d",&arr[i][j]);
        }
    }
    numel(arr);
}

This shows the exact number of elements in matrix irrespective of the array size you mentioned while initilasing(IF that's what you meant)

Delete dynamically-generated table row using jQuery

You should use Event Delegation, because of the fact that you are creating dynamic rows.

$(document).on('click','button.removebutton', function() {
    alert("aa");
  $(this).closest('tr').remove();
  return false;
});

Live Demo

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:

--yesterday
SELECT NOW() - INTERVAL '1 DAY';

--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

SELECT 
    org_id,
    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
FROM 
    sourcetable
WHERE 
    date_at <= now() - INTERVAL '130 DAYS'
GROUP BY 
    org_id,
    dateat;


TIPS

Tip 1

You can append multiple operands. E.g.: how to get last day of current month?

SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';

Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);


More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

Angularjs - display current date

Another way of doing is: In Controller, create a variable to hold the current date as shown below:

var eventsApp = angular.module("eventsApp", []);
eventsApp.controller("EventController", function EventController($scope) 
{

 $scope.myDate = Date.now();

});

In HTML view,

<!DOCTYPE html>
<html ng-app="eventsApp">
<head>
    <meta charset="utf-8" />
   <title></title>
   <script src="lib/angular/angular.js"></script>
</head>
<body>
<div ng-controller="EventController">
<span>{{myDate | date : 'yyyy-MM-dd'}}</span>
</div>
</body>
</html>

Remove duplicates from a list of objects based on property in Java 8

The easiest way to do it directly in the list is

HashSet<Object> seen=new HashSet<>();
employee.removeIf(e->!seen.add(e.getID()));
  • removeIf will remove an element if it meets the specified criteria
  • Set.add will return false if it did not modify the Set, i.e. already contains the value
  • combining these two, it will remove all elements (employees) whose id has been encountered before

Of course, it only works if the list supports removal of elements.

How to convert <font size="10"> to px?

Using the data points from the accepted answer you can use polynomial interpolation to obtain a formula.

WolframAlpha Input: interpolating polynomial {{1,.63},{2,.82}, {3,1}, {4,1.13}, {5,1.5}, {6, 2}, {7,3}}

Formula: 0.00223611x^6 - 0.0530417x^5 + 0.496319x^4 - 2.30479x^3 + 5.51644x^2 - 6.16717x + 3.14

And use in Groovy code:

import java.math.*
def convert = {x -> (0.00223611*x**6 - 0.053042*x**5 + 0.49632*x**4 - 2.30479*x**3 + 5.5164*x**2 - 6.167*x + 3.14).setScale(2, RoundingMode.HALF_UP) }
(1..7).each { i -> println(convert(i)) }

Is a URL allowed to contain a space?

URL can have an Space Character in them and they will be displayed as %20 in most of the browsers, but browser encoding rules change quite often and we cannot depend on how a browser will display the URL.

So Instead you can replace the Space Character in the URL with any character that you think shall make the URL More readable and ' Pretty ' ;) ..... O so general characters that are preferred are "-","_","+" .... but these aren't the compulsions so u can use any of the character that is not supposed to be in the URL Already.

Please avoid the %,&,},{,],[,/,>,< as the URL Space Character Replacement as they can pull up an error on certain browsers and Platforms.

As you can see the Stak overflow itself uses the '-' character as Space(%20) replacement.

Have an Happy questioning.

AngularJS - Building a dynamic table based on a json

Just want to share with what I used so far to save your time.

Here are examples of hard-coded headers and dynamic headers (in case if don't care about data structure). In both cases I wrote some simple directive: customSort

customSort

.directive("customSort", function() {
    return {
        restrict: 'A',
        transclude: true,    
        scope: {
          order: '=',
          sort: '='
        },
        template : 
          ' <a ng-click="sort_by(order)" style="color: #555555;">'+
          '    <span ng-transclude></span>'+
          '    <i ng-class="selectedCls(order)"></i>'+
          '</a>',
        link: function(scope) {

        // change sorting order
        scope.sort_by = function(newSortingOrder) {       
            var sort = scope.sort;

            if (sort.sortingOrder == newSortingOrder){
                sort.reverse = !sort.reverse;
            }                    

            sort.sortingOrder = newSortingOrder;        
        };


        scope.selectedCls = function(column) {
            if(column == scope.sort.sortingOrder){
                return ('icon-chevron-' + ((scope.sort.reverse) ? 'down' : 'up'));
            }
            else{            
                return'icon-sort' 
            } 
        };      
      }// end link
    }
    });

[1st option with static headers]

I used single ng-repeat

This is a good example in Fiddle (Notice, there is no jQuery library!)

enter image description here

           <tbody>
                <tr ng-repeat="item in pagedItems[currentPage] | orderBy:sortingOrder:reverse">
                    <td>{{item.id}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.description}}</td>
                    <td>{{item.field3}}</td>
                    <td>{{item.field4}}</td>
                    <td>{{item.field5}}</td>
                </tr>
            </tbody>

[2nd option with dynamic headers]

Demo 2: Fiddle


HTML

<table class="table table-striped table-condensed table-hover">
            <thead>
                <tr>
                   <th ng-repeat="header in table_headers"  
                     class="{{header.name}}" custom-sort order="header.name" sort="sort"
                    >{{ header.name }}

                        </th> 
                  </tr>
            </thead>
            <tfoot>
                <td colspan="6">
                    <div class="pagination pull-right">
                        <ul>
                            <li ng-class="{disabled: currentPage == 0}">
                                <a href ng-click="prevPage()">« Prev</a>
                            </li>

                            <li ng-repeat="n in range(pagedItems.length, currentPage, currentPage + gap) "
                                ng-class="{active: n == currentPage}"
                            ng-click="setPage()">
                                <a href ng-bind="n + 1">1</a>
                            </li>

                            <li ng-class="{disabled: (currentPage) == pagedItems.length - 1}">
                                <a href ng-click="nextPage()">Next »</a>
                            </li>
                        </ul>
                    </div>
                </td>
            </tfoot>
            <pre>pagedItems.length: {{pagedItems.length|json}}</pre>
            <pre>currentPage: {{currentPage|json}}</pre>
            <pre>currentPage: {{sort|json}}</pre>
            <tbody>

                <tr ng-repeat="item in pagedItems[currentPage] | orderBy:sort.sortingOrder:sort.reverse">
                     <td ng-repeat="val in item" ng-bind-html-unsafe="item[table_headers[$index].name]"></td>
                </tr>
            </tbody>
        </table>

As a side note:

The ng-bind-html-unsafe is deprecated, so I used it only for Demo (2nd example). You welcome to edit.

Showing all session data at once?

print_r($this->session->userdata); 

or

print_r($this->session->all_userdata());

Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up?

Why would a “java.net.ConnectException: Connection timed out” exception occur when URL is up?

Because the URLConnection (HttpURLConnection/HttpsURLConnection) is erratic. You can read about this here and here. Our solution were two things:

a) set the ContentLength via setFixedLengthStreamingMode

b) catch any TimeoutException and retry if it failed.

How to receive POST data in django

You should have access to the POST dictionary on the request object.

Reading content from URL with Node.js

the data object is a buffer of bytes. Simply call .toString() to get human-readable code:

console.log( data.toString() );

reference: Node.js buffers

boto3 client NoRegionError: You must specify a region error only sometimes

I believe, by default, boto picks the region which is set in aws cli. You can run command #aws configure and press enter (it shows what creds you have set in aws cli with region)twice to confirm your region.

Implement an input with a mask

I taken from this thread decision Implement an input with a mask and adapted it for IE10, and added setter- and getter- functions.

BUT I TESTED FOR PHONE-mask ONLY

$(document).ready(function(){
    var el_arr = document.querySelectorAll("[placeholder][data-slots]");
    for (var el_ind=0; el_ind < el_arr.length; el_ind++ ){
        var el = el_arr[el_ind];
        var pattern = el.getAttribute("placeholder"),
            slots = new Set(el.getAttribute("data-slots") || "_"),
            prev = function(j){return Array.from(pattern, function(c,i){ return slots.has(c)? j=i+1: j;});}(0),
            first = pattern.split('').findIndex(function(c){return slots.has(c);} ),
            accept = new RegExp(el.getAttribute("data-accept") || "\\d", "g"),
            clean = function(input){input = input.match(accept) || [];return Array.from(pattern, function(c){return input[0] === c || slots.has(c) ? input.shift() || c : c;});},
            format = function(){
                var elem = this;
                var i_j_arr = [el.selectionStart, el.selectionEnd].map(function(i){
                    i = clean(el.value.slice(0, i)).findIndex(function(c){ return slots.has(c);});
                    return i<0? prev[prev.length-1]: elem.back? prev[i-1] || first: i;
                });
                el.value = clean(el.value).join('');
                el.setSelectionRange(i_j_arr[0], i_j_arr[1]);
                this.back = false;
            },
            // sdo added
            get_masked_value = function(){
                var input = this.value;
                var ret=[];
                for(var k in pattern){
                    if ( !input[k] )break;
                    if( slots.has(pattern[k]) && input[k]!=pattern[k]){
                        ret.push(input[k]);
                    } 
                } 
                return ret.join('');
            },
            set_masked_value = function(input){
                var ret=[];
                var index_in_value = 0;
                for(var k in pattern){
                    if( slots.has(pattern[k]) && input[index_in_value]){
                        ret.push(input[index_in_value]);
                        index_in_value++;
                    }
                    else{
                        ret.push(pattern[k]);
                    }
                } 
                this.value = ret.join('');
            }                    
        ;
        el.get_masked_value = get_masked_value;
        el.set_masked_value = set_masked_value;
        el.back = false;
        el.addEventListener("keydown", function(event){ this.back = event.key === "Backspace";});
        el.addEventListener("input", format);
        el.addEventListener("focus", format);
        el.addEventListener("blur", function() { return el.value === pattern && (el.value=""); });
    }

});   

Is there a good Valgrind substitute for Windows?

Check out this question: Is there a good Valgrind substitute for Windows? . Though general substitute for valgrind is asked, it mainly discusses memory leak detectors and not race conditions detections.

What does "&" at the end of a linux command mean?

The & makes the command run in the background.

From man bash:

If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0.

estimating of testing effort as a percentage of development time

From my experience, 25% effort is spent on Analysis; 50% for Design, Development and Unit Test; remaining 25% for testing. Most projects will fit within a +/-10% variance of this rule of thumb depending on the nature of the project, knowledge of resources, quality of inputs & outputs, etc. One can add a project management overhead within these percentages or as an overhead on top within a 10-15% range.

How do I convert a string to a number in PHP?

In PHP you can use intval(string) or floatval(string) functions to convert strings to numbers.

AngularJS toggle class using ng-class

<div data-ng-init="featureClass=false" 
     data-ng-click="featureClass=!featureClass" 
     data-ng-class="{'active': featureClass}">
    Click me to toggle my class!
</div>

Analogous to jQuery's toggleClass method, this is a way to toggle the active class on/off when the element is clicked.

Check if a temporary table exists and delete if it exists before creating a temporary table

I cannot reproduce the error.

Perhaps I'm not understanding the problem.

The following works fine for me in SQL Server 2005, with the extra "foo" column appearing in the second select result:

IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
GO
CREATE TABLE #Results ( Company CHAR(3), StepId TINYINT, FieldId TINYINT )
GO
select company, stepid, fieldid from #Results
GO
ALTER TABLE #Results ADD foo VARCHAR(50) NULL
GO
select company, stepid, fieldid, foo from #Results
GO
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
GO

How to convert a String into an ArrayList?

Try something like

List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));

Demo:

String s = "lorem,ipsum,dolor,sit,amet";

List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));

System.out.println(myList);  // prints [lorem, ipsum, dolor, sit, amet]

This post has been rewritten as an article here.

How to refresh or show immediately in datagridview after inserting?

Try below piece of code.

this.dataGridView1.RefreshEdit();

Open File in Another Directory (Python)

If you know the full path to the file you can just do something similar to this. However if you question directly relates to relative paths, that I am unfamiliar with and would have to research and test.

path = 'C:\\Users\\Username\\Path\\To\\File'

with open(path, 'w') as f:
    f.write(data)

Edit:

Here is a way to do it relatively instead of absolute. Not sure if this works on windows, you will have to test it.

import os

cur_path = os.path.dirname(__file__)

new_path = os.path.relpath('..\\subfldr1\\testfile.txt', cur_path)
with open(new_path, 'w') as f:
    f.write(data)

Edit 2: One quick note about __file__, this will not work in the interactive interpreter due it being ran interactively and not from an actual file.

How to retrieve the dimensions of a view?

You are trying to get width and height of an elements, that weren't drawn yet.

If you use debug and stop at some point, you'll see, that your device screen is still empty, that's because your elements weren't drawn yet, so you can't get width and height of something, that doesn't yet exist.

And, I might be wrong, but setWidth() is not always respected, Layout lays out it's children and decides how to measure them (calling child.measure()), so If you set setWidth(), you are not guaranteed to get this width after element will be drawn.

What you need, is to use getMeasuredWidth() (the most recent measure of your View) somewhere after the view was actually drawn.

Look into Activity lifecycle for finding the best moment.

http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

I believe a good practice is to use OnGlobalLayoutListener like this:

yourView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (!mMeasured) {
                // Here your view is already layed out and measured for the first time
                mMeasured = true; // Some optional flag to mark, that we already got the sizes
            }
        }
    });

You can place this code directly in onCreate(), and it will be invoked when views will be laid out.

Practical uses for the "internal" keyword in C#

Being driven by "use as strict modifier as you can" rule I use internal everywhere I need to access, say, method from another class until I explicitly need to access it from another assembly.

As assembly interface is usually more narrow than sum of its classes interfaces, there are quite many places I use it.

Select current element in jQuery

When the jQuery click event calls your event handler, it sets "this" to the object that was clicked on. To turn it into a jQuery object, just pass it to the "$" function: $(this). So, to get, for example, the next sibling element, you would do this inside the click handler:

var nextSibling = $(this).next();

Edit: After reading Kevin's comment, I realized I might be mistaken about what you want. If you want to do what he asked, i.e. select the corresponding link in the other div, you could use $(this).index() to get the clicked link's position. Then you would select the link in the other div by its position, for example with the "eq" method.

var $clicked = $(this);
var linkIndex = $clicked.index();
$clicked.parent().next().children().eq(linkIndex);

If you want to be able to go both ways, you will need some way of determining which div you are in so you know if you need "next()" or "prev()" after "parent()"

creating an array of structs in c++

It works perfectly. I have gcc compiler C++11 ready. Try this and you'll see:

#include <iostream>

using namespace std;

int main()
{
    int pause;

    struct Customer
    {
           int uid;
           string name;
    };

    Customer customerRecords[2];
    customerRecords[0] = {25, "Bob Jones"};
    customerRecords[1] = {26, "Jim Smith"};
    cout << customerRecords[0].uid << " " << customerRecords[0].name << endl;
    cout << customerRecords[1].uid << " " << customerRecords[1].name << endl;
    cin >> pause;
return 0;
}

Typescript sleep

If you are using angular5 and above, please include the below method in your ts file.

async delay(ms: number) {
    await new Promise(resolve => setTimeout(()=>resolve(), ms)).then(()=>console.log("fired"));
}

then call this delay() method wherever you want.

e.g:

validateInputValues() {
    if (null == this.id|| this.id== "") {
        this.messageService.add(
            {severity: 'error', summary: 'ID is Required.'});
        this.delay(3000).then(any => {
            this.messageService.clear();
        });
    }
}

This will disappear message growl after 3 seconds.

Freemarker iterating over hashmap keys

For completeness, it's worth mentioning there's a decent handling of empty collections in Freemarker since recently.

So the most convenient way to iterate a map is:

<#list tags>
<ul class="posts">
    <#items as tagName, tagCount>
        <li>{$tagName} (${tagCount})</li>
    </#items>
</ul>
<#else>
    <p>No tags found.</p>
</#list>

No more <#if ...> wrappers.

Permission denied for relation

Posting Ron E answer for grant privileges on all tables as it might be useful to others.

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO jerry;

Is there a way to make a DIV unselectable?

Use

onselectstart="return false"

it prevents copying your content.

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

Even though utf8_decode is a useful solution, I prefer to correct the encoding errors on the table itself. In my opinion it is better to correct the bad characters themselves than making "hacks" in the code. Simply do a replace on the field on the table. To correct the bad encoded characters from OP :

update <table> set <field> = replace(<field>, "ë", "ë")
update <table> set <field> = replace(<field>, "Ã", "à")
update <table> set <field> = replace(<field>, "ì", "ì")
update <table> set <field> = replace(<field>, "ù", "ù")

Where <table> is the name of the mysql table and <field> is the name of the column in the table. Here is a very good check-list for those typically bad encoded windows-1252 to utf-8 characters -> Debugging Chart Mapping Windows-1252 Characters to UTF-8 Bytes to Latin-1 Characters.

Remember to backup your table before trying to replace any characters with SQL!

[I know this is an answer to a very old question, but was facing the issue once again. Some old windows machine didnt encoded the text correct before inserting it to the utf8_general_ci collated table.]

Your configuration specifies to merge with the <branch name> from the remote, but no such ref was fetched.?

For me it was a case sensitivity issue. My local branch was Version_feature2 instead of Version_Feature2. I re-checked out my branch using the correct casing and then git pull worked.

Does a `+` in a URL scheme/host/path represent a space?

Thou shalt always encode URLs.

Here is how Ruby encodes your URL:

irb(main):008:0> CGI.escape "a.com/a+b"
=> "a.com%2Fa%2Bb"

How to catch exception output from Python subprocess.check_output()?

I don't think the accepted solution handles the case where the error text is reported on stderr. From my testing the exception's output attribute did not contain the results from stderr and the docs warn against using stderr=PIPE in check_output(). Instead, I would suggest one small improvement to J.F Sebastian's solution by adding stderr support. We are, after all, trying to handle errors and stderr is where they are often reported.

from subprocess import Popen, PIPE

p = Popen(['bitcoin', 'sendtoaddress', ..], stdout=PIPE, stderr=PIPE)
output, error = p.communicate()
if p.returncode != 0: 
   print("bitcoin failed %d %s %s" % (p.returncode, output, error))

How can I use mySQL replace() to replace strings in multiple records?

This will help you.

UPDATE play_school_data SET title= REPLACE(title, "&#39;", "'") WHERE title = "Elmer&#39;s Parade";

Result:

title = Elmer's Parade

VB.NET - Remove a characters from a String

Function RemoveCharacter(ByVal stringToCleanUp, ByVal characterToRemove)
  ' replace the target with nothing
  ' Replace() returns a new String and does not modify the current one
  Return stringToCleanUp.Replace(characterToRemove, "")
End Function

Here's more information about VB's Replace function

No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

Or you can just create your own MediaTypeFormatter. I use this for text/html. If you add text/plain to it, it'll work for you too:

public class TextMediaTypeFormatter : MediaTypeFormatter
{
    public TextMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        return ReadFromStreamAsync(type, readStream, content, formatterLogger, CancellationToken.None);
    }

    public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
    {
        using (var streamReader = new StreamReader(readStream))
        {
            return await streamReader.ReadToEndAsync();
        }
    }

    public override bool CanReadType(Type type)
    {
        return type == typeof(string);
    }

    public override bool CanWriteType(Type type)
    {
        return false;
    }
}

Finally you have to assign this to the HttpMethodContext.ResponseFormatter property.

Data truncation: Data too long for column 'logo' at row 1

You are trying to insert data that is larger than allowed for the column logo.

Use following data types as per your need

TINYBLOB   :     maximum length of 255 bytes  
BLOB       :     maximum length of 65,535 bytes  
MEDIUMBLOB :     maximum length of 16,777,215 bytes  
LONGBLOB   :     maximum length of 4,294,967,295 bytes  

Use LONGBLOB to avoid this exception.

Bash function to find newest file matching pattern

Dark magic function incantation for those who want the find ... xargs ... head ... solution above, but in easy to use function form so you don't have to think:

#define the function
find_newest_file_matching_pattern_under_directory(){
    echo $(find $1 -name $2 -print0 | xargs -0 ls -1 -t | head -1)
}

#setup:
#mkdir /tmp/files_to_move
#cd /tmp/files_to_move
#touch file1.txt
#touch file2.txt

#invoke the function:
newest_file=$( find_newest_file_matching_pattern_under_directory /tmp/files_to_move/ bc* )
echo $newest_file

Prints:

file2.txt

Which is:

The filename with the oldest modified timestamp of the file under the given directory matching the given pattern.

How do I make a relative reference to another workbook in Excel?

The only solutions that I've seen to organize the external files into sub-folders has required the use of VBA to resolve a full path to the external file in the formulas. Here is a link to a site with several examples others have used:

http://www.teachexcel.com/excel-help/excel-how-to.php?i=415651

Alternatively, if you can place all of the files in the same folder instead of dividing them into sub-folders, then Excel will resolve the external references without requiring the use of VBA even if you move the files to a network location. Your formulas then become simply ='[ComponentsC.xlsx]Sheet1'!A1 with no folder names to traverse.

Using JQuery to check if no radio button in a group has been checked

Use .length refer to http://api.jquery.com/checked-selector/

if ($('input[name="html_elements"]:checked').length === 0) alert("Not checked");
else alert("Checked");

How to use jQuery to get the current value of a file input field

In Chrome 8 the path is always 'C:\fakepath\' with the correct file name.

How to log cron jobs?

Here is my code:

* * * * * your_script_fullpath >> your_log_path 2>&1

How to open a new tab using Selenium WebDriver

Just for anyone else who's looking for an answer in Ruby, Python, and C# bindings (Selenium 2.33.0).

Note that the actual keys to send depend on your OS. For example, Mac uses CMD + T, instead of Ctrl + T.

Ruby

require 'selenium-webdriver'

driver = Selenium::WebDriver.for :firefox
driver.get('http://stackoverflow.com/')

body = driver.find_element(:tag_name => 'body')
body.send_keys(:control, 't')

driver.quit

Python

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/")

body = driver.find_element_by_tag_name("body")
body.send_keys(Keys.CONTROL + 't')

driver.close()

C#

using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

namespace StackOverflowTests {

    class OpenNewTab {

        static void Main(string[] args) {

            IWebDriver driver = new FirefoxDriver();
            driver.Navigate().GoToUrl("http://stackoverflow.com/");

            IWebElement body = driver.FindElement(By.TagName("body"));
            body.SendKeys(Keys.Control + 't');

            driver.Quit();
        }
    }
}

SQL Server - SELECT FROM stored procedure

use OPENQUERY and befor Execute set 'SET FMTONLY OFF; SET NOCOUNT ON;'

Try this sample code:

SELECT top(1)*
FROM
OPENQUERY( [Server], 'SET FMTONLY OFF; SET NOCOUNT ON; EXECUTE  [database].[dbo].[storedprocedure]  value,value ')

JavaScript: Alert.Show(message) From ASP.NET Code-behind

if you are using ScriptManager on the page then you can also try using this:

System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Your Message');", true);

How to establish a connection pool in JDBC?

I would recommend using the commons-dbcp library. There are numerous examples listed on how to use it, here is the link to the move simple one. The usage is very simple:

 BasicDataSource ds = new BasicDataSource();
 ds.setDriverClassName("oracle.jdbc.driver.OracleDriver")
 ds.setUsername("scott");
 ds.setPassword("tiger");
 ds.setUrl(connectURI);
 ...
 Connection conn = ds.getConnection();

You only need to create the data source once, so make sure you read the documentation if you do not know how to do that. If you are not aware of how to properly write JDBC statements so you do not leak resources, you also might want to read this Wikipedia page.

Retrieving a random item from ArrayList

Here you go, using Generics:

private <T> T getRandomItem(List<T> list)
{
    Random random = new Random();
    int listSize = list.size();
    int randomIndex = random.nextInt(listSize);
    return list.get(randomIndex);
}

Download file from web in Python 3

Yes, definietly requests is great package to use in something related to HTTP requests. but we need to be careful with the encoding type of the incoming data as well below is an example which explains the difference


from requests import get

# case when the response is byte array
url = 'some_image_url'

response = get(url)
with open('output', 'wb') as file:
    file.write(response.content)


# case when the response is text
# Here unlikely if the reponse content is of type **iso-8859-1** we will have to override the response encoding
url = 'some_page_url'

response = get(url)
# override encoding by real educated guess as provided by chardet
r.encoding = r.apparent_encoding

with open('output', 'w', encoding='utf-8') as file:
    file.write(response.content)

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

Try using anaconda. I had the same error. One lone option was to build tensorflow from source which took long time. I tried using conda and it worked.

  1. Create a new environment in anaconda.
  2. conda -c conda-forge tensorflow

Then, it worked.

What to do with commit made in a detached head

An easy fix is to just create a new branch for that commit and checkout to it: git checkout -b <branch-name> <commit-hash>.

In this way, all the changes you made will be saved in that branch. In case you need to clean up your master branch from leftover commits be sure to run git reset --hard master.

With this, you will be rewriting your branches so be sure not to disturb anyone with these changes. Be sure to take a look at this article for a better illustration of detached HEAD state.

SQL count rows in a table

The index statistics likely need to be current, but this will return the number of rows for all tables that are not MS_SHIPPED.

select o.name, i.rowcnt 
from sys.objects o join sys.sysindexes i 
on o.object_id = i.id
where o.is_ms_shipped = 0
and i.rowcnt > 0
order by o.name

Using Gulp to Concatenate and Uglify files

It turns out that I needed to use gulp-rename and also output the concatenated file first before 'uglification'. Here's the code:

var gulp = require('gulp'),
    gp_concat = require('gulp-concat'),
    gp_rename = require('gulp-rename'),
    gp_uglify = require('gulp-uglify');

gulp.task('js-fef', function(){
    return gulp.src(['file1.js', 'file2.js', 'file3.js'])
        .pipe(gp_concat('concat.js'))
        .pipe(gulp.dest('dist'))
        .pipe(gp_rename('uglify.js'))
        .pipe(gp_uglify())
        .pipe(gulp.dest('dist'));
});

gulp.task('default', ['js-fef'], function(){});

Coming from grunt it was a little confusing at first but it makes sense now. I hope it helps the gulp noobs.

And, if you need sourcemaps, here's the updated code:

var gulp = require('gulp'),
    gp_concat = require('gulp-concat'),
    gp_rename = require('gulp-rename'),
    gp_uglify = require('gulp-uglify'),
    gp_sourcemaps = require('gulp-sourcemaps');

gulp.task('js-fef', function(){
    return gulp.src(['file1.js', 'file2.js', 'file3.js'])
        .pipe(gp_sourcemaps.init())
        .pipe(gp_concat('concat.js'))
        .pipe(gulp.dest('dist'))
        .pipe(gp_rename('uglify.js'))
        .pipe(gp_uglify())
        .pipe(gp_sourcemaps.write('./'))
        .pipe(gulp.dest('dist'));
});

gulp.task('default', ['js-fef'], function(){});

See gulp-sourcemaps for more on options and configuration.

SQL Server - Adding a string to a text column (concat equivalent)

To Join two string in SQL Query use function CONCAT(Express1,Express2,...)

Like....

SELECT CODE, CONCAT(Rtrim(FName), " " , TRrim(LName)) as Title FROM MyTable

How to make a flex item not fill the height of the flex container?

The align-items, or respectively align-content attribute controls this behaviour.

align-items defines the items' positioning perpendicularly to flex-direction.

The default flex-direction is row, therfore vertical placement can be controlled with align-items.

There is also the align-self attribute to control the alignment on a per item basis.

_x000D_
_x000D_
#a {_x000D_
  display:flex;_x000D_
_x000D_
  align-items:flex-start;_x000D_
  align-content:flex-start;_x000D_
  }_x000D_
_x000D_
#a > div {_x000D_
  _x000D_
  background-color:red;_x000D_
  padding:5px;_x000D_
  margin:2px;_x000D_
  }_x000D_
 #a > #c {_x000D_
  align-self:stretch;_x000D_
 }
_x000D_
<div id="a">_x000D_
  _x000D_
  <div id="b">left</div>_x000D_
  <div id="c">middle</div>_x000D_
  <div>right<br>right<br>right<br>right<br>right<br></div>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

css-tricks has an excellent article on the topic. I recommend reading it a couple of times.

Regex for allowing alphanumeric,-,_ and space

Try this regex

*Updated regex

/^[a-z0-9]+([-_\s]{1}[a-z0-9]+)*$/i

This will allow only single space or - or _ between the text

Ex: this-some abc123_regex

To learn : https://regexr.com

*Note: I have updated the regex based on Toto question

Python: create dictionary using dict() with integer keys?

There are also these 'ways':

>>> dict.fromkeys(range(1, 4))
{1: None, 2: None, 3: None}
>>> dict(zip(range(1, 4), range(1, 4)))
{1: 1, 2: 2, 3: 3}

Make div 100% Width of Browser Window

.myDiv {
    background-color: red;
    width: 100%;
    min-height: 100vh;
    max-height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    margin: 0 auto;
}

Basically, we're fixing the div's position regardless of it's parent, and then position it using margin: 0 auto; and settings its position at the top left corner.

How to execute Python scripts in Windows?

I encountered the same problem but in the context of needing to package my code for Windows users (coming from Linux). My package contains a number of scripts with command line options.

I need these scripts to get installed in the appropriate location on Windows users' machines so that they can invoke them from the command line. As the package is supposedly user-friendly, asking my users to change their registry to run these scripts would be impossible.

I came across a solution that the folks at Continuum use for Python scripts that come with their Anaconda package -- check out your Anaconda/Scripts directory for examples.

For a Python script test, create two files: a test.bat and a test-script.py.

test.bat looks as follows (the .bat files in Anaconda\Scripts call python.exe with a relative path which I adapted for my purposes):

@echo off
set PYFILE=%~f0
set PYFILE=%PYFILE:~0,-4%-script.py
"python.exe" "%PYFILE%" %*

test-script.py is your actual Python script:

import sys
print sys.argv

If you leave these two files in your local directory you can invoke your Python script through the .bat file by doing

test.bat hello world
['C:\\...\\test-scripy.py', 'hello', 'world']

If you copy both files to a location that is on your PATH (such as Anaconda\Scripts) then you can even invoke your script by leaving out the .bat suffix

test hello world
['C:\\...Anaconda\\Scripts\\test-scripy.py', 'hello', 'world']

Disclaimer: I have no idea what's going on and how this works and so would appreciate any explanation.

127 Return code from $?

Generally it means:

127 - command not found

but it can also mean that the command is found,
but a library that is required by the command is NOT found.

Search in all files in a project in Sublime Text 3

You can put <project> in "Where:" box to search from the current Sublime project from the Find in Files menu.

This is more useful than searching from the root folder for when your project is including or excluding particular folders or file extensions.

Git credential helper - update password

On my first attempt to Git fetch after my password change, I was told that my username/password combination was invalid. This was correct as git-credential helper had cached my old values.

However, I attempted another git fetch after restarting my terminal/command-prompt and this time the credential helper prompted me to enter in my GitHub username and password.

I suspect the initial failed Git fetch request in combination with restarting my terminal/command-prompt resolved this for me.

I hope this answer helps anybody else in a similar position in the future!

HTML5 tag for horizontal line break

You can make a div that has the same attributes as the <hr> tag. This way it is fully able to be customized. Here is some sample code:

The HTML:

<h3>This is a header.</h3>
<div class="customHr">.</div>

<p>Here is some sample paragraph text.<br>
This demonstrates what could go below a custom hr.</p>

The CSS:

.customHr {
    width: 95%
    font-size: 1px;
    color: rgba(0, 0, 0, 0);
    line-height: 1px;

    background-color: grey;
    margin-top: -6px;
    margin-bottom: 10px;
}

To see how the project turns out, here is a JSFiddle for the above code: http://jsfiddle.net/SplashHero/qmccsc06/1/

How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter?

Your Question contains the first step, but you need width and height. you can get the width and height of the screen. Here is a small edit

//gets the screen width and height
double Width = MediaQuery.of(context).size.width;
double Height = MediaQuery.of(context).size.height;

Widget background = new Image.asset(
  asset.background,
  fit: BoxFit.fill,
  width: Width,
  height: Height,
);

return new Stack(
  children: <Widget>[
    background,
    foreground,
  ],
);

You can also use Width and Height to size other objects based on screen size.

ex: width: Height/2, height: Height/2 //using height for both keeps aspect ratio

How to format LocalDate to string?

SimpleDateFormat will not work if he is starting with LocalDate which is new in Java 8. From what I can see, you will have to use DateTimeFormatter, http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html.

LocalDate localDate = LocalDate.now();//For reference
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd LLLL yyyy");
String formattedString = localDate.format(formatter);

That should print 05 May 1988. To get the period after the day and before the month, you might have to use "dd'.LLLL yyyy"

Changing the text on a label

Here is another one, I think. Just for reference. Let's set a variable to be an instantance of class StringVar

If you program Tk using the Tcl language, you can ask the system to let you know when a variable is changed. The Tk toolkit can use this feature, called tracing, to update certain widgets when an associated variable is modified.

There’s no way to track changes to Python variables, but Tkinter allows you to create variable wrappers that can be used wherever Tk can use a traced Tcl variable.

text = StringVar()
self.depositLabel = Label(self.__mainWindow, text = self.labelText, textvariable = text)
                                                                    ^^^^^^^^^^^^^^^^^
  def depositCallBack(self,event):
      text.set('change the value')

How do you attach and detach from Docker's process?

I'm on a Mac, and for some reason, Ctrl-p Ctrl-q would only work if I also held Shift

How to set the maximum memory usage for JVM?

The answer above is kind of correct, you can't gracefully control how much native memory a java process allocates. It depends on what your application is doing.

That said, depending on platform, you may be able to do use some mechanism, ulimit for example, to limit the size of a java or any other process.

Just don't expect it to fail gracefully if it hits that limit. Native memory allocation failures are much harder to handle than allocation failures on the java heap. There's a fairly good chance the application will crash but depending on how critical it is to the system to keep the process size down that might still suit you.

Selecting data frame rows based on partial string match in a column

LIKE should work in sqlite:

require(sqldf)
df <- data.frame(name = c('bob','robert','peter'),id=c(1,2,3))
sqldf("select * from df where name LIKE '%er%'")
    name id
1 robert  2
2  peter  3

simple Jquery hover enlarge

Demo Link

Tutorial Link

This will show original dimensions of Image on Hover using jQuery custom code

HTML

        <ul class="thumb">
            <li>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/1.jpg)"></div>
                </a>
            </li>
            <li>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/2.jpg)"></div>
                </a>
            </li>
            <li>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/3.jpg)"></div>
                </a>
            </li>
            <li>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/4.jpg)"></div>
                </a>
            </li>
            <li>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/5.jpg)"></div>
                </a>
            </li>
            <li>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/6.jpg)"></div>
                </a>
            </li>
            <li>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/7.jpg)"></div>
                </a>
            </li>
            <li>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/8.jpg)"></div>
                </a>
            </li>
            <li>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/9.jpg)"></div>
                </a>
            </li>
        </ul>

CSS

    ul.thumb {
        float: left;
        list-style: none;
        padding: 10px;
        width: 360px;
        margin: 80px;
    }

    ul.thumb li {
        margin: 0;
        padding: 5px;
        float: left;
        position: relative;
        /* Set the absolute positioning base coordinate */
        width: 110px;
        height: 110px;
    }

    ul.thumb li .thumbnail-wrap {
        width: 100px;
        height: 100px;
        /* Set the small thumbnail size */
        -ms-interpolation-mode: bicubic;
        /* IE Fix for Bicubic Scaling */
        border: 1px solid #ddd;
        padding: 5px;
        position: absolute;
        left: 0;
        top: 0;
        background-size: cover;
        background-repeat: no-repeat;

        -webkit-box-shadow: inset -3px 0px 40px -15px rgba(0, 0, 0, 1);
        -moz-box-shadow: inset -3px 0px 40px -15px rgba(0, 0, 0, 1);
        box-shadow: inset -3px 0px 40px -15px rgba(0, 0, 0, 1);

    }

    ul.thumb li .thumbnail-wrap.hover {
        -webkit-box-shadow: -2px 1px 22px -1px rgba(0, 0, 0, 0.75);
        -moz-box-shadow: -2px 1px 22px -1px rgba(0, 0, 0, 0.75);
        box-shadow: -2px 1px 22px -1px rgba(0, 0, 0, 0.75);
    }

    .thumnail-zoomed-wrapper {
        display: none;
        position: fixed;
        top: 0px;
        left: 0px;
        height: 100vh;
        width: 100%;
        background: rgba(0, 0, 0, 0.2);
        z-index: 99;
    }

    .thumbnail-zoomed-image {
        margin: auto;
        display: block;
        text-align: center;
        margin-top: 12%;
    }

    .thumbnail-zoomed-image img {
        max-width: 100%;
    }

    .close-image-zoom {
        z-index: 10;
        float: right;
        margin: 10px;
        cursor: pointer;
    }

jQuery

        var perc = 40;
        $("ul.thumb li").hover(function () {
            $("ul.thumb li").find(".thumbnail-wrap").css({
                "z-index": "0"
            });
            $(this).find(".thumbnail-wrap").css({
                "z-index": "10"
            });
            var imageval = $(this).find(".thumbnail-wrap").css("background-image").slice(5);
            var img;
            var thisImage = this;
            img = new Image();
            img.src = imageval.substring(0, imageval.length - 2);
            img.onload = function () {
                var imgh = this.height * (perc / 100);
                var imgw = this.width * (perc / 100);
                $(thisImage).find(".thumbnail-wrap").addClass("hover").stop()
                    .animate({
                        marginTop: "-" + (imgh / 4) + "px",
                        marginLeft: "-" + (imgw / 4) + "px",
                        width: imgw + "px",
                        height: imgh + "px"
                    }, 200);
            }
        }, function () {
            var thisImage = this;
            $(this).find(".thumbnail-wrap").removeClass("hover").stop()
                .animate({
                    marginTop: "0",
                    marginLeft: "0",
                    top: "0",
                    left: "0",
                    width: "100px",
                    height: "100px",
                    padding: "5px"
                }, 400, function () {});
        });

        //Show thumbnail in fullscreen
        $("ul.thumb li .thumbnail-wrap").click(function () {

            var imageval = $(this).css("background-image").slice(5);
            imageval = imageval.substring(0, imageval.length - 2);
            $(".thumbnail-zoomed-image img").attr({
                src: imageval
            });
            $(".thumnail-zoomed-wrapper").fadeIn();
            return false;
        });

        //Close fullscreen preview
        $(".thumnail-zoomed-wrapper .close-image-zoom").click(function () {
            $(".thumnail-zoomed-wrapper").hide();
            return false;
        });

enter image description here

WPF loading spinner

In WPF, you can now simply do:

Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait; // set the cursor to loading spinner

Mouse.OverrideCursor = System.Windows.Input.Cursors.Arrow; // set the cursor back to arrow

.gitignore file for java eclipse project

put .gitignore in your main catalog

git status (you will see which files you can commit)
git add -A
git commit -m "message"
git push

Web scraping with Java

Your best bet is to use Selenium Web Driver since it

  1. Provides visual feedback to the coder (see your scraping in action, see where it stops)

  2. Accurate and Consistent as it directly controls the browser you use.

  3. Slow. Doesn't hit web pages like HtmlUnit does but sometimes you don't want to hit too fast.

    Htmlunit is fast but is horrible at handling Javascript and AJAX.

SQL changing a value to upper or lower case

SELECT UPPER(firstname) FROM Person

SELECT LOWER(firstname) FROM Person

How do I make a new line in swift

You should be able to use \n inside a Swift string, and it should work as expected, creating a newline character. You will want to remove the space after the \n for proper formatting like so:

var example: String = "Hello World \nThis is a new line"

Which, if printed to the console, should become:

Hello World
This is a new line

However, there are some other considerations to make depending on how you will be using this string, such as:

  • If you are setting it to a UILabel's text property, make sure that the UILabel's numberOfLines = 0, which allows for infinite lines.
  • In some networking use cases, use \r\n instead, which is the Windows newline.

Edit: You said you're using a UITextField, but it does not support multiple lines. You must use a UITextView.

How to get the position of a character in Python?

more_itertools.locate is a third-party tool that finds all indicies of items that satisfy a condition.

Here we find all index locations of the letter "i".

import more_itertools as mit


s = "supercalifragilisticexpialidocious"
list(mit.locate(s, lambda x: x == "i"))
# [8, 13, 15, 18, 23, 26, 30]

What are the -Xms and -Xmx parameters when starting JVM?

Run the command java -X and you will get a list of all -X options:

C:\Users\Admin>java -X
-Xmixed           mixed mode execution (default)
-Xint             interpreted mode execution only
-Xbootclasspath:<directories and zip/jar files separated by ;>
                      set search path for bootstrap classes and resources
-Xbootclasspath/a:<directories and zip/jar files separated by ;>
                      append to end of bootstrap class path
-Xbootclasspath/p:<directories and zip/jar files separated by ;>
                      prepend in front of bootstrap class path
-Xdiag            show additional diagnostic messages
-Xnoclassgc       disable class garbage collection
-Xincgc           enable incremental garbage collection
-Xloggc:<file>    log GC status to a file with time stamps
-Xbatch           disable background compilation
-Xms<size>        set initial Java heap size.........................
-Xmx<size>        set maximum Java heap size.........................
-Xss<size>        set java thread stack size
-Xprof            output cpu profiling data
-Xfuture          enable strictest checks, anticipating future default
-Xrs              reduce use of OS signals by Java/VM (see documentation)
-Xcheck:jni       perform additional checks for JNI functions
-Xshare:off       do not attempt to use shared class data
-Xshare:auto      use shared class data if possible (default)
-Xshare:on        require using shared class data, otherwise fail.
-XshowSettings    show all settings and continue
-XshowSettings:all         show all settings and continue
-XshowSettings:vm          show all vm related settings and continue
-XshowSettings:properties  show all property settings and continue
-XshowSettings:locale      show all locale related settings and continue

The -X options are non-standard and subject to change without notice.

I hope this will help you understand Xms, Xmx as well as many other things that matters the most. :)

What is the best IDE to develop Android apps in?

If you haven't installed Eclipse yet, I'd recommend Motorola's MotoDev Studio. It does a lot of the annoying little tasks like set up your Android environment along with your paths, and adds a lot of nice built in functionality to Eclipse.

Even if you've already installed Eclipse, you can add it as a plugin (I haven't tried that myself). It is by Motorola, so they have some Motorola centric functionality as well, such as the ability to add your app to the Motorola market. Anyway if you're interested, give it a shot: http://developer.motorola.com/docstools/motodevstudio/

JOptionPane Yes or No window

Something along these lines ....

   //default icon, custom title
int n = JOptionPane.showConfirmDialog(null,"Would you like green eggs and ham?","An Inane Question",JOptionPane.YES_NO_OPTION);

String result = "?";
switch (n) {
case JOptionPane.YES_OPTION:
  result = "YES";
  break;
case JOptionPane.NO_OPTION:
  result = "NO";
  break;
default:
  ;
}
System.out.println("Replace? " + result);

you may also want to look at DialogDemo

How is Docker different from a virtual machine?

I have used Docker in production environments and staging very much. When you get used to it you will find it very powerful for building a multi container and isolated environments.

Docker has been developed based on LXC (Linux Container) and works perfectly in many Linux distributions, especially Ubuntu.

Docker containers are isolated environments. You can see it when you issue the top command in a Docker container that has been created from a Docker image.

Besides that, they are very light-weight and flexible thanks to the dockerFile configuration.

For example, you can create a Docker image and configure a DockerFile and tell that for example when it is running then wget 'this', apt-get 'that', run 'some shell script', setting environment variables and so on.

In micro-services projects and architecture Docker is a very viable asset. You can achieve scalability, resiliency and elasticity with Docker, Docker swarm, Kubernetes and Docker Compose.

Another important issue regarding Docker is Docker Hub and its community. For example, I implemented an ecosystem for monitoring kafka using Prometheus, Grafana, Prometheus-JMX-Exporter, and Docker.

For doing that, I downloaded configured Docker containers for zookeeper, kafka, Prometheus, Grafana and jmx-collector then mounted my own configuration for some of them using YAML files, or for others, I changed some files and configuration in the Docker container and I build a whole system for monitoring kafka using multi-container Dockers on a single machine with isolation and scalability and resiliency that this architecture can be easily moved into multiple servers.

Besides the Docker Hub site there is another site called quay.io that you can use to have your own Docker images dashboard there and pull/push to/from it. You can even import Docker images from Docker Hub to quay then running them from quay on your own machine.

Note: Learning Docker in the first place seems complex and hard, but when you get used to it then you can not work without it.

I remember the first days of working with Docker when I issued the wrong commands or removing my containers and all of data and configurations mistakenly.

How can I return to a parent activity correctly?

In Java class :-

    toolbar = (Toolbar) findViewById(R.id.apptool_bar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setTitle("Snapdeal");

    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

In Manifest :-

<activity
            android:name=".SubActivity"
            android:label="@string/title_activity_sub"
            android:theme="@style/AppTheme" >
            <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity"></meta-data>
    </activity>

It will help you

How to capitalize the first letter in a String in Ruby

Use capitalize. From the String documentation:

Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.

"hello".capitalize    #=> "Hello"
"HELLO".capitalize    #=> "Hello"
"123ABC".capitalize   #=> "123abc"

How to delete an element from a Slice in Golang

Remove one element from the Slice (this is called 're-slicing'):

package main

import (
    "fmt"
)

func RemoveIndex(s []int, index int) []int {
    return append(s[:index], s[index+1:]...)
}

func main() {
    all := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    fmt.Println(all) //[0 1 2 3 4 5 6 7 8 9]
    all = RemoveIndex(all, 5)
    fmt.Println(all) //[0 1 2 3 4 6 7 8 9]
}

Where is jarsigner?

This will install jdk for you and check for the jarsigner inside it

sudo apt install -y default-jdk

to find jarsigner you can use whereis jarsigner

Convert base64 string to image

Hi This is my solution

Javascript code

var base64before = document.querySelector('img').src;
var base64 = base64before.replace(/^data:image\/(png|jpg);base64,/, "");
var httpPost = new XMLHttpRequest();
var path = "your url";
var data = JSON.stringify(base64);

httpPost.open("POST", path, false);
// Set the content type of the request to json since that's what's being sent
httpPost.setRequestHeader('Content-Type', 'application/json');
httpPost.send(data);

This is my Java code.

public void saveImage(InputStream imageStream){
InputStream inStream = imageStream;

try {
    String dataString = convertStreamToString(inStream);

    byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(dataString);
    BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
    // write the image to a file
    File outputfile = new File("/Users/paul/Desktop/testkey/myImage.png");
    ImageIO.write(image, "png", outputfile);

    }catch(Exception e) {
        System.out.println(e.getStackTrace());
    }
}


static String convertStreamToString(java.io.InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

How to call function that takes an argument in a Django template?

You cannot call a function that requires arguments in a template. Write a template tag or filter instead.

back button callback in navigationController in iOS

it's probably better to override the backbutton so you can handle the event before the view is popped for things such as user confirmation.

in viewDidLoad create a UIBarButtonItem and set self.navigationItem.leftBarButtonItem to it passing in a sel

- (void) viewDidLoad
{
// change the back button to cancel and add an event handler
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@”back”
style:UIBarButtonItemStyleBordered
target:self
action:@selector(handleBack:)];

self.navigationItem.leftBarButtonItem = backButton;
[backButton release];

}
- (void) handleBack:(id)sender
{
// pop to root view controller
[self.navigationController popToRootViewControllerAnimated:YES];

}

Then you can do things like raise an UIAlertView to confirm the action, then pop the view controller, etc.

Or instead of creating a new backbutton, you can conform to the UINavigationController delegate methods to do actions when the back button is pressed.

How to Run Terminal as Administrator on Mac Pro

You can run a command as admin using

sudo <command>

You can also switch to root and every command will be run as root

sudo su

How to submit form on change of dropdown list?

Just ask assistance of JavaScript.

<select onchange="this.form.submit()">
    ...
</select>

See also:

Installing TensorFlow on Windows (Python 3.6.x)

Update 15.11.2017

It seems that by now it is working like one would expect. Running the following commands using the following pip and python version should work.


Installing with Python 3.6.x


Version

Python: 3.6.3
pip: 9.0.1


Installation Commands

The following commands are based of the following installation guide here.

using cmd

C:> pip3 install --upgrade tensorflow // cpu
C:> pip3 install --upgrade tensorflow-gpu // gpu

using Anaconda

C:> conda create -n tensorflow python=3.5 
C:> activate tensorflow
(tensorflow)C:> pip install --ignore-installed --upgrade tensorflow
(tensorflow)C:> pip install --ignore-installed --upgrade tensorflow-gpu 

Additional Information

A list of common installation problems can be found here.

You can find an example console output of a successful tensorflow cpu installation here.


Old response:

Okay to conclude; use version 3.5.2 !
Neither 3.5.1 nor 3.6.x seem to work at the moment.

Versions:

Python 3.5.2 pip 8.1.1 .. (python 3.5)

Commands:

// cpu
C:> pip install --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-0.12.0rc0-cp35-cp35m-win_amd64.whl

// gpu
C:> pip install --upgrade https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-0.12.0rc0-cp35-cp35m-win_amd64.whl

Best XML Parser for PHP

Hi I think the SimpleXml is very useful . And with it I am using xpath;

$xml = simplexml_load_file("som_xml.xml");

$blocks  = $xml->xpath('//block'); //gets all <block/> tags
$blocks2 = $xml->xpath('//layout/block'); //gets all <block/> which parent are   <layout/>  tags

I use many xml configs and this helps me to parse them really fast. SimpleXml is written on C so it's very fast.

c# razor url parameter from view

If you're doing the check inside the View, put the value in the ViewBag.

In your controller:

ViewBag["parameterName"] = Request["parameterName"];

It's worth noting that the Request and Response properties are exposed by the Controller class. They have the same semantics as HttpRequest and HttpResponse.

C++ cout hex values?

Use std::uppercase and std::hex to format integer variable a to be displayed in hexadecimal format.

#include <iostream>
int main() {
   int a = 255;

   // Formatting Integer
   std::cout << std::uppercase << std::hex << a << std::endl; // Output: FF
   std::cout << std::showbase  << std::hex << a << std::endl; // Output: 0XFF
   std::cout << std::nouppercase << std::showbase  << std::hex << a << std::endl; // Output: 0xff

   return 0;
}

List of zeros in python

$ python3
>>> from itertools import repeat
>>> list(repeat(0, 7))
[0, 0, 0, 0, 0, 0, 0]

Oracle SqlPlus - saving output in a file but don't show on screen

Try this:

SET TERMOUT OFF; 
spool M:\Documents\test;
select * from employees;
/
spool off;

Find Locked Table in SQL Server

sp_lock

When reading sp_lock information, use the OBJECT_NAME( ) function to get the name of a table from its ID number, for example:

SELECT object_name(16003073)

EDIT :

There is another proc provided by microsoft which reports objects without the ID translation : http://support.microsoft.com/kb/q255596/

Transparent background on winforms?

Here was my solution:

In the constructors add these two lines:

this.BackColor = Color.LimeGreen;
this.TransparencyKey = Color.LimeGreen;

In your form, add this method:

protected override void OnPaintBackground(PaintEventArgs e)
{
    e.Graphics.FillRectangle(Brushes.LimeGreen, e.ClipRectangle);
}

Be warned, not only is this form fully transparent inside the frame, but you can also click through it. However, it might be cool to draw an image onto it and make the form able to be dragged everywhere to create a custom shaped form.

Invoke(Delegate)

A control or window object in Windows Forms is just a wrapper around a Win32 window identified by a handle (sometimes called HWND). Most things you do with the control will eventually result in a Win32 API call that uses this handle. The handle is owned by the thread that created it (typically the main thread), and shouldn't be manipulated by another thread. If for some reason you need to do something with the control from another thread, you can use Invoke to ask the main thread to do it on your behalf.

For instance, if you want to change the text of a label from a worker thread, you can do something like this:

theLabel.Invoke(new Action(() => theLabel.Text = "hello world from worker thread!"));