Programs & Examples On #Ncurses

The ncurses package is a subroutine library for terminal-independent screen-painting and input-event handling.

How to upload file to server with HTTP POST multipart/form-data?

Top to @loop answer.

We got below error for Asp.Net MVC, Unable to connect to the remote server

Fix: After adding the below code in Web.Confing issue has been resolved for us

  <system.net>
    <defaultProxy useDefaultCredentials="true" >
    </defaultProxy>
  </system.net>

FtpWebRequest Download File

FYI, Microsoft recommends not using FtpWebRequest for new development:

We don't recommend that you use the FtpWebRequest class for new development. For more information and alternatives to FtpWebRequest, see WebRequest shouldn't be used on GitHub.

The GitHub link directs to this SO page which contains a list of third-party FTP libraries, such as FluentFTP.

Which characters make a URL invalid?

In general URIs as defined by RFC 3986 (see Section 2: Characters) may contain any of the following 84 characters:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=

Note that this list doesn't state where in the URI these characters may occur.

Any other character needs to be encoded with the percent-encoding (%hh). Each part of the URI has further restrictions about what characters need to be represented by an percent-encoded word.

Loop through list with both content and index

Like everyone else:

for i, val in enumerate(data):
    print i, val

but also

for i, val in enumerate(data, 1):
    print i, val

In other words, you can specify as starting value for the index/count generated by enumerate() which comes in handy if you don't want your index to start with the default value of zero.

I was printing out lines in a file the other day and specified the starting value as 1 for enumerate(), which made more sense than 0 when displaying information about a specific line to the user.

Programmatically set TextBlock Foreground Color

 textBlock.Foreground = new SolidColorBrush(Colors.White);

Best way to work with dates in Android SQLite

Best way to store datein SQlite DB is to store the current DateTimeMilliseconds. Below is the code snippet to do so_

  1. Get the DateTimeMilliseconds
public static long getTimeMillis(String dateString, String dateFormat) throws ParseException {
    /*Use date format as according to your need! Ex. - yyyy/MM/dd HH:mm:ss */
    String myDate = dateString;//"2017/12/20 18:10:45";
    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat/*"yyyy/MM/dd HH:mm:ss"*/);
    Date date = sdf.parse(myDate);
    long millis = date.getTime();

    return millis;
}
  1. Insert the data in your DB
public void insert(Context mContext, long dateTimeMillis, String msg) {
    //Your DB Helper
    MyDatabaseHelper dbHelper = new MyDatabaseHelper(mContext);
    database = dbHelper.getWritableDatabase();

    ContentValues contentValue = new ContentValues();
    contentValue.put(MyDatabaseHelper.DATE_MILLIS, dateTimeMillis);
    contentValue.put(MyDatabaseHelper.MESSAGE, msg);

    //insert data in DB
    database.insert("your_table_name", null, contentValue);

   //Close the DB connection.
   dbHelper.close(); 

}

Now, your data (date is in currentTimeMilliseconds) is get inserted in DB .

Next step is, when you want to retrieve data from DB you need to convert the respective date time milliseconds in to corresponding date. Below is the sample code snippet to do the same_

  1. Convert date milliseconds in to date string.
public static String getDate(long milliSeconds, String dateFormat)
{
    // Create a DateFormatter object for displaying date in specified format.
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat/*"yyyy/MM/dd HH:mm:ss"*/);

    // Create a calendar object that will convert the date and time value in milliseconds to date.
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(milliSeconds);
    return formatter.format(calendar.getTime());
}
  1. Now, Finally fetch the data and see its working...
public ArrayList<String> fetchData() {

    ArrayList<String> listOfAllDates = new ArrayList<String>();
    String cDate = null;

    MyDatabaseHelper dbHelper = new MyDatabaseHelper("your_app_context");
    database = dbHelper.getWritableDatabase();

    String[] columns = new String[] {MyDatabaseHelper.DATE_MILLIS, MyDatabaseHelper.MESSAGE};
    Cursor cursor = database.query("your_table_name", columns, null, null, null, null, null);

    if (cursor != null) {

        if (cursor.moveToFirst()){
            do{
                //iterate the cursor to get data.
                cDate = getDate(cursor.getLong(cursor.getColumnIndex(MyDatabaseHelper.DATE_MILLIS)), "yyyy/MM/dd HH:mm:ss");

                listOfAllDates.add(cDate);

            }while(cursor.moveToNext());
        }
        cursor.close();

    //Close the DB connection.
    dbHelper.close(); 

    return listOfAllDates;

}

Hope this will help all! :)

PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value

I'm in Windows 10 and the problem was that the avd's directory in my computer had non-ASCII characters in it.

Here's what to do:

Run cmd as administrator

Run the following command:

mklink /D C:\\.android C:\\Users\\-yourUsername-\\.android

(This will create a symbolic link between the path with non-ASCII characters and the new one)

In enviroment variables add ANDROID_AVD_HOME variable with value C:\\.android\avd.

Git - What is the difference between push.default "matching" and "simple"

Git v2.0 Release Notes

Backward compatibility notes

When git push [$there] does not say what to push, we have used the traditional "matching" semantics so far (all your branches were sent to the remote as long as there already are branches of the same name over there). In Git 2.0, the default is now the "simple" semantics, which pushes:

  • only the current branch to the branch with the same name, and only when the current branch is set to integrate with that remote branch, if you are pushing to the same remote as you fetch from; or

  • only the current branch to the branch with the same name, if you are pushing to a remote that is not where you usually fetch from.

You can use the configuration variable "push.default" to change this. If you are an old-timer who wants to keep using the "matching" semantics, you can set the variable to "matching", for example. Read the documentation for other possibilities.

When git add -u and git add -A are run inside a subdirectory without specifying which paths to add on the command line, they operate on the entire tree for consistency with git commit -a and other commands (these commands used to operate only on the current subdirectory). Say git add -u . or git add -A . if you want to limit the operation to the current directory.

git add <path> is the same as git add -A <path> now, so that git add dir/ will notice paths you removed from the directory and record the removal. In older versions of Git, git add <path> used to ignore removals. You can say git add --ignore-removal <path> to add only added or modified paths in <path>, if you really want to.

Reading and writing environment variables in Python?

Try using the os module.

import os

os.environ['DEBUSSY'] = '1'
os.environ['FSDB'] = '1'

# Open child processes via os.system(), popen() or fork() and execv()

someVariable = int(os.environ['DEBUSSY'])

See the Python docs on os.environ. Also, for spawning child processes, see Python's subprocess docs.

Why doesn't list have safe "get" method like dictionary?

This works if you want the first element, like my_list.get(0)

>>> my_list = [1,2,3]
>>> next(iter(my_list), 'fail')
1
>>> my_list = []
>>> next(iter(my_list), 'fail')
'fail'

I know it's not exactly what you asked for but it might help others.

Reference alias (calculated in SELECT) in WHERE clause

You can do this using cross apply

SELECT c.BalanceDue AS BalanceDue
FROM Invoices
cross apply (select (InvoiceTotal - PaymentTotal - CreditTotal) as BalanceDue) as c
WHERE  c.BalanceDue  > 0;

Is there an alternative to string.Replace that is case-insensitive?

Regex.Replace(strInput, strToken.Replace("$", "[$]"), strReplaceWith, RegexOptions.IgnoreCase);

Waiting on a list of Future

If you are using Java 8 and don't want to manipulate CompletableFutures, I have written a tool to retrieve results for a List<Future<T>> using streaming. The key is that you are forbidden to map(Future::get) as it throws.

public final class Futures
{

    private Futures()
    {}

    public static <E> Collector<Future<E>, Collection<E>, List<E>> present()
    {
        return new FutureCollector<>();
    }

    private static class FutureCollector<T> implements Collector<Future<T>, Collection<T>, List<T>>
    {
        private final List<Throwable> exceptions = new LinkedList<>();

        @Override
        public Supplier<Collection<T>> supplier()
        {
            return LinkedList::new;
        }

        @Override
        public BiConsumer<Collection<T>, Future<T>> accumulator()
        {
            return (r, f) -> {
                try
                {
                    r.add(f.get());
                }
                catch (InterruptedException e)
                {}
                catch (ExecutionException e)
                {
                    exceptions.add(e.getCause());
                }
            };
        }

        @Override
        public BinaryOperator<Collection<T>> combiner()
        {
            return (l1, l2) -> {
                l1.addAll(l2);
                return l1;
            };
        }

        @Override
        public Function<Collection<T>, List<T>> finisher()
        {
            return l -> {

                List<T> ret = new ArrayList<>(l);
                if (!exceptions.isEmpty())
                    throw new AggregateException(exceptions, ret);

                return ret;
            };

        }

        @Override
        public Set<java.util.stream.Collector.Characteristics> characteristics()
        {
            return java.util.Collections.emptySet();
        }
    }

This needs an AggregateException that works like C#'s

public class AggregateException extends RuntimeException
{
    /**
     *
     */
    private static final long serialVersionUID = -4477649337710077094L;

    private final List<Throwable> causes;
    private List<?> successfulElements;

    public AggregateException(List<Throwable> causes, List<?> l)
    {
        this.causes = causes;
        successfulElements = l;
    }

    public AggregateException(List<Throwable> causes)
    {
        this.causes = causes;
    }

    @Override
    public synchronized Throwable getCause()
    {
        return this;
    }

    public List<Throwable> getCauses()
    {
        return causes;
    }

    public List<?> getSuccessfulElements()
    {
        return successfulElements;
    }

    public void setSuccessfulElements(List<?> successfulElements)
    {
        this.successfulElements = successfulElements;
    }

}

This component acts exactly as C#'s Task.WaitAll. I am working on a variant that does the same as CompletableFuture.allOf (equivalento to Task.WhenAll)

The reason why I did this is that I am using Spring's ListenableFuture and don't want to port to CompletableFuture despite it is a more standard way

Extract only right most n letters from a string

Null Safe Methods :

Strings shorter than the max length returning the original string

String Right Extension Method

public static string Right(this string input, int count) =>
    String.Join("", (input + "").ToCharArray().Reverse().Take(count).Reverse());

String Left Extension Method

public static string Left(this string input, int count) =>
    String.Join("", (input + "").ToCharArray().Take(count));

Is there any quick way to get the last two characters in a string?

In my case, I wanted the opposite. I wanted to strip off the last 2 characters in my string. This was pretty simple:

String myString = someString.substring(0, someString.length() - 2);

Unique device identification

You can use the fingerprintJS2 library, it helps a lot with calculating a browser fingerprint.

By the way, on Panopticlick you can see how unique this usually is.

Git push error pre-receive hook declined

I solved this issue by changing remote 'origin' url from http to git protocol in .git/config

Starting with Zend Tutorial - Zend_DB_Adapter throws Exception: "SQLSTATE[HY000] [2002] No such file or directory"

I would say that you have a problem connecting from PHP to MySQL...

Something like PHP trying to find some socket file, and not finding it, maybe ?
(I've had this problem a couple of times -- not sure the error I got was exactly this one, though)


If you are running some Linux-based system, there should be a my.cnf file somewhere, that is used to configure MySQL -- on my Ubuntu, it's in /etc/mysql/.

In this file, there might be something like this :

socket = /var/run/mysqld/mysqld.sock


PHP need to use the same file -- and, depending on your distribution, the default file might not be the same as the one that MySQL uses.

In this case, adding these lines to your php.ini file might help :

mysql.default_socket = /var/run/mysqld/mysqld.sock
mysqli.default_socket = /var/run/mysqld/mysqld.sock
pdo_mysql.default_socket = /var/run/mysqld/mysqld.sock

(You'll need to restart Apache so the modification to php.ini is taken into account)

The last one should be enough for PDO, which is used by Zend Framework -- but the two previous ones will not do any harm, and can be useful for other applications.


If this doesn't help : can you connect to your database using PDO, in another script, that's totally independant of Zend Framework ?

i.e. does something like this work (quoting) :

$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

If no, the problem is definitly not with ZF, and is a configuration / installation problem of PHP.

If yes... Well, it means you have a problem with ZF, and you'll need to give us more informations about your setup (like your DSN, for instance ? )

jQuery: set selected value of dropdown list?

You need to select jQuery in the dropdown on the left and you have a syntax error because the $(document).ready should end with }); not )}; Check this link.

How to convert minutes to hours/minutes and add various time values together using jQuery?

This code can be used with timezone

javascript:

_x000D_
_x000D_
let minToHm = (m) => {_x000D_
  let h = Math.floor(m / 60);_x000D_
  h += (h < 0) ? 1 : 0;_x000D_
  let m2 = Math.abs(m % 60);_x000D_
  m2 = (m2 < 10) ? '0' + m2 : m2;_x000D_
  return (h < 0 ? '' : '+') + h + ':' + m2;_x000D_
}_x000D_
_x000D_
console.log(minToHm(210)) // "+3:30"_x000D_
console.log(minToHm(-210)) // "-3:30"_x000D_
console.log(minToHm(0)) // "+0:00"
_x000D_
_x000D_
_x000D_

minToHm(210)
"+3:30"

minToHm(-210)
"-3:30"

minToHm(0)
"+0:00"

How to output HTML from JSP <%! ... %> block?

I suppose this would help:

<%! 
   String someOutput() {
     return "Some Output";
  }
%>
...
<%= someOutput() %>

Anyway, it isn't a good idea to have code in a view.

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

You're talking about histograms, but this doesn't quite make sense. Histograms and bar charts are different things. An histogram would be a bar chart representing the sum of values per year, for example. Here, you just seem to be after bars.

Here is a complete example from your data that shows a bar of for each required value at each date:

import pylab as pl
import datetime

data = """0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014"""

values = []
dates = []

for line in data.split("\n"):
    x, y = line.split()
    values.append(int(x))
    dates.append(datetime.datetime.strptime(y, "%d-%m-%Y").date())

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(dates, values, width=100)
ax.xaxis_date()

You need to parse the date with strptime and set the x-axis to use dates (as described in this answer).

If you're not interested in having the x-axis show a linear time scale, but just want bars with labels, you can do this instead:

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(range(len(dates)), values)

EDIT: Following comments, for all the ticks, and for them to be centred, pass the range to set_ticks (and move them by half the bar width):

fig = pl.figure()
ax = pl.subplot(111)
width=0.8
ax.bar(range(len(dates)), values, width=width)
ax.set_xticks(np.arange(len(dates)) + width/2)
ax.set_xticklabels(dates, rotation=90)

How to format strings using printf() to get equal length in the output

There's also the %n modifier which can help in certain circumstances. It returns the column on which the string was so far. Example: you want to write several rows that are within the width of the first row like a table.

int width1, width2;
int values[6][2];
printf("|%s%n|%s%n|\n", header1, &width1, header2, &width2);

for(i=0; i<6; i++)
   printf("|%*d|%*d|\n", width1, values[i][0], width2, values[i][1]);

will print two columns of the same width of whatever length the two strings header1 and header2 may have. I don't know if all implementations have the %n, but Solaris and Linux do.

Validate IPv4 address in Java

/**
 * Check if ip is valid
 *
 * @param ip to be checked
 * @return <tt>true</tt> if <tt>ip</tt> is valid, otherwise <tt>false</tt>
 */
private static boolean isValid(String ip) {
    String[] bits = ip.split("\\.");
    if (bits.length != 4) {
        return false;
    }
    for (String bit : bits) {
        try {
            if (Integer.valueOf(bit) < 0 || Integer.valueOf(bit) > 255) {
                return false;
            }
        } catch (NumberFormatException e) {
            return false; /* contains other other character */
        }
    }
    return true;
}

Java function for arrays like PHP's join()?

java.util.Arrays has an 'asList' method. Together with the java.util.List/ArrayList API this gives you all you need:;

private static String[] join(String[] array1, String[] array2) {

    List<String> list = new ArrayList<String>(Arrays.asList(array1));
    list.addAll(Arrays.asList(array2));
    return list.toArray(new String[0]);
}

Add to integers in a list

You can append to the end of a list:

foo = [1, 2, 3, 4, 5]
foo.append(4)
foo.append([8,7])    
print(foo)            # [1, 2, 3, 4, 5, 4, [8, 7]]

You can edit items in the list like this:

foo = [1, 2, 3, 4, 5]
foo[3] = foo[3] + 4     
print(foo)            # [1, 2, 3, 8, 5]

Insert integers into the middle of a list:

x = [2, 5, 10]
x.insert(2, 77)
print(x)              # [2, 5, 77, 10]

How to enable LogCat/Console in Eclipse for Android?

Write "LogCat" in Quick Access edit box in your eclipse window (top right corner, just before Open Prospective button). And just select LogCat it will open-up the LogCat window in your current prospect

enter image description here

filedialog, tkinter and opening files

Did you try adding the self prefix to the fileName and replacing the method above the Button ? With the self, it becomes visible between methods.

...

def load_file(self):
    self.fileName = filedialog.askopenfilename(filetypes = (("Template files", "*.tplate")
                                                     ,("HTML files", "*.html;*.htm")
                                                     ,("All files", "*.*") ))
...

Autocompletion of @author in Intellij

Check Enable Live Templates and leave the cursor at the position desired and click Apply then OK

enter image description here

Proper way to return JSON using node or Express

Older version of Express use app.use(express.json()) or bodyParser.json() read more about bodyParser middleware

On latest version of express we could simply use res.json()

const express = require('express'),
    port = process.env.port || 3000,
    app = express()

app.get('/', (req, res) => res.json({key: "value"}))

app.listen(port, () => console.log(`Server start at ${port}`))

Best way to add Gradle support to IntelliJ Project

There is no need to remove any .iml files. Follow this:

  • close the project
  • File -> Open... and choose your newly created build.gradle
  • IntelliJ will ask you whether you want:
    • Open Existing Project
    • Delete Existing Project and Import
  • Choose the second option and you are done

Getting windbg without the whole WDK?

Try the MSDN archive link at http://archive.msdn.microsoft.com/debugtoolswindows/Release/ProjectReleases.aspx?ReleaseId=4912. It has the WinDbg MSI for both 32- and 64-bit (Version 6.12.2.633).

Fragment onCreateView and onActivityCreated called twice

I have had the same problem with a simple Activity carrying only one fragment (which would get replaced sometimes). I then realized I use onSaveInstanceState only in the fragment (and onCreateView to check for savedInstanceState), not in the activity.

On device turn the activity containing the fragments gets restarted and onCreated is called. There I did attach the required fragment (which is correct on the first start).

On the device turn Android first re-created the fragment that was visible and then called onCreate of the containing activity where my fragment was attached, thus replacing the original visible one.

To avoid that I simply changed my activity to check for savedInstanceState:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

if (savedInstanceState != null) {
/**making sure you are not attaching the fragments again as they have 
 been 
 *already added
 **/
 return; 
 }
 else{
  // following code to attach fragment initially
 }

 }

I did not even Overwrite onSaveInstanceState of the activity.

How to Generate Barcode using PHP and Display it as an Image on the same page

There is a library for this BarCode PHP. You just need to include a few files:

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

You can generate many types of barcodes, namely 1D or 2D. Add the required library:

require_once('class/BCGcode39.barcode.php');

Generate the colours:

// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);

After you have added all the codes, you will get this way:

Example

Since several have asked for an example here is what I was able to do to get it done

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

require_once('class/BCGcode128.barcode.php');

header('Content-Type: image/png');

$color_white = new BCGColor(255, 255, 255);

$code = new BCGcode128();
$code->parse('HELLO');

$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);

$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);

If you want to actually create the image file so you can save it then change

$drawing = new BCGDrawing('', $color_white);

to

$drawing = new BCGDrawing('image.png', $color_white);

SQL Server: Multiple table joins with a WHERE clause

SELECT p.Name, v.Name
FROM Production.Product p
JOIN Purchasing.ProductVendor pv
ON p.ProductID = pv.ProductID
JOIN Purchasing.Vendor v
ON pv.BusinessEntityID = v.BusinessEntityID
WHERE ProductSubcategoryID = 15
ORDER BY v.Name;

Convert date formats in bash

Maybe something changed since 2011 but this worked for me:

$ date +"%Y%m%d"
20150330

No need for the -d to get the same appearing result.

How to make layout with rounded corners..?

Use CardView in android v7 support library. Though it's a bit heavy, it solves all problem, and easy enough. Not like the set drawable background method, it could clip subviews successfully.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardBackgroundColor="@android:color/transparent"
    card_view:cardCornerRadius="5dp"
    card_view:cardElevation="0dp"
    card_view:contentPadding="0dp">
    <YOUR_LINEARLAYOUT_HERE>
</android.support.v7.widget.CardView>

Android Google Maps API V2 Zoom to Current Location

    mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
        @Override
        public void onMyLocationChange(Location location) {

                CameraUpdate center=CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
                CameraUpdate zoom=CameraUpdateFactory.zoomTo(11);
                mMap.moveCamera(center);
                mMap.animateCamera(zoom);

        }
    });

How to get UTF-8 working in Java webapps?

I'm with a similar problem, but, in filenames of a file I'm compressing with apache commons. So, i resolved it with this command:

convmv --notest -f cp1252 -t utf8 * -r

it works very well for me. Hope it help anyone ;)

What is the correct way to represent null XML elements?

You use xsi:nil when your schema semantics indicate that an element has a default value, and that the default value should be used if the element isn't present. I have to assume that there are smart people to whom the preceding sentence is not a self-evidently terrible idea, but it sounds like nine kinds of bad to me. Every XML format I've ever worked with represents null values by omitting the element. (Or attribute, and good luck marking an attribute with xsi:nil.)

How to Handle Button Click Events in jQuery?

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script>
$(document).ready(function(){
  $("#button").click(function(){
    alert("Hello");
  });
});
</script>

<input type="button" id="button" value="Click me">

Http Get using Android HttpURLConnection

Simple and Efficient Solution : use Volley

 StringRequest stringRequest = new StringRequest(Request.Method.GET, finalUrl ,
           new Response.Listener<String>() {
                    @Override
                    public void onResponse(String){
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            HashMap<String, Object> responseHashMap = new HashMap<>(Utility.toMap(jsonObject)) ;
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("api", error.getMessage().toString());
            }
        });

        RequestQueue queue = Volley.newRequestQueue(context) ;
        queue.add(stringRequest) ;

how to remove empty strings from list, then remove duplicate values from a list

Amiram Korach solution is indeed tidy. Here's an alternative for the sake of versatility.

var count = dtList.Count;
// Perform a reverse tracking.
for (var i = count - 1; i > -1; i--)
{
    if (dtList[i]==string.Empty) dtList.RemoveAt(i);
}
// Keep only the unique list items.
dtList = dtList.Distinct().ToList();

ECMAScript 6 arrow function that returns an object

You may wonder, why the syntax is valid (but not working as expected):

var func = p => { foo: "bar" }

It's because of JavaScript's label syntax:

So if you transpile the above code to ES5, it should look like:

var func = function (p) {
  foo:
  "bar"; //obviously no return here!
}

How do I get the current timezone name in Postgres 9.3?

This may or may not help you address your problem, OP, but to get the timezone of the current server relative to UTC (UT1, technically), do:

SELECT EXTRACT(TIMEZONE FROM now())/3600.0;

The above works by extracting the UT1-relative offset in minutes, and then converting it to hours using the factor of 3600 secs/hour.

Example:

SET SESSION timezone TO 'Asia/Kabul';
SELECT EXTRACT(TIMEZONE FROM now())/3600.0;
-- output: 4.5 (as of the writing of this post)

(docs).

Map a network drive to be used by a service

You could us the 'net use' command:

var p = System.Diagnostics.Process.Start("net.exe", "use K: \\\\Server\\path");
var isCompleted = p.WaitForExit(5000);

If that does not work in a service, try the Winapi and PInvoke WNetAddConnection2

Edit: Obviously I misunderstood you - you can not change the sourcecode of the service, right? In that case I would follow the suggestion by mdb, but with a little twist: Create your own service (lets call it mapping service) that maps the drive and add this mapping service to the dependencies for the first (the actual working) service. That way the working service will not start before the mapping service has started (and mapped the drive).

Add newly created specific folder to .gitignore in Git

Try /public_html/stats/* ?

But since the files in git status reported as to be commited that means you've already added them manually. In which case, of course, it's a bit too late to ignore. You can git rm --cache them (IIRC).

Is it possible to use argsort in descending order?

Just like Python, in that [::-1] reverses the array returned by argsort() and [:n] gives that last n elements:

>>> avgDists=np.array([1, 8, 6, 9, 4])
>>> n=3
>>> ids = avgDists.argsort()[::-1][:n]
>>> ids
array([3, 1, 2])

The advantage of this method is that ids is a view of avgDists:

>>> ids.flags
  C_CONTIGUOUS : False
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False

(The 'OWNDATA' being False indicates this is a view, not a copy)

Another way to do this is something like:

(-avgDists).argsort()[:n]

The problem is that the way this works is to create negative of each element in the array:

>>> (-avgDists)
array([-1, -8, -6, -9, -4])

ANd creates a copy to do so:

>>> (-avgDists_n).flags['OWNDATA']
True

So if you time each, with this very small data set:

>>> import timeit
>>> timeit.timeit('(-avgDists).argsort()[:3]', setup="from __main__ import avgDists")
4.2879798610229045
>>> timeit.timeit('avgDists.argsort()[::-1][:3]', setup="from __main__ import avgDists")
2.8372560259886086

The view method is substantially faster (and uses 1/2 the memory...)

WPF: simple TextBox data binding

Just for future needs.

In Visual Studio 2013 with .NET Framework 4.5, for a window property, try adding ElementName=window to make it work.

<Grid Name="myGrid" Height="437.274">
  <TextBox Text="{Binding Path=Name2, ElementName=window}"/>
</Grid>

How to convert a huge list-of-vector to a matrix more efficiently?

you can use as.matrix as below:

output <- as.matrix(z)

Subset and ggplot2

Here 2 options for subsetting:

Using subset from base R:

library(ggplot2)
ggplot(subset(dat,ID %in% c("P1" , "P3"))) + 
         geom_line(aes(Value1, Value2, group=ID, colour=ID))

Using subset the argument of geom_line(Note I am using plyr package to use the special . function).

library(plyr)
ggplot(data=dat)+ 
  geom_line(aes(Value1, Value2, group=ID, colour=ID),
                ,subset = .(ID %in% c("P1" , "P3")))

You can also use the complementary subsetting:

subset(dat,ID != "P2")

Spring 3.0 - Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

I have encountered the very similar problem today. For some reason IntelliJ IDEA haven't included Spring Security jar files while deploying the application. I think I should agree with the majority of posters here.

how to use "tab space" while writing in text file

You can use \t to create a tab in a file.

Make outer div be automatically the same height as its floating content

You can set the outerdiv's CSS to this

#outerdiv {
    overflow: hidden; /* make sure this doesn't cause unexpected behaviour */
}

You can also do this by adding an element at the end with clear: both. This can be added normally, with JS (not a good solution) or with :after CSS pseudo element (not widely supported in older IEs).

The problem is that containers won't naturally expand to include floated children. Be warned with using the first example, if you have any children elements outside the parent element, they will be hidden. You can also use 'auto' as the property value, but this will invoke scrollbars if any element appears outside.

You can also try floating the parent container, but depending on your design, this may be impossible/difficult.

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

Try this:

$(".datepicker").on("dp.change", function(e) {
    alert('hey');
});

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

RabbitMQ / AMQP: single queue, multiple consumers for same message?

Yes each consumer can receive the same messages. have a look at http://www.rabbitmq.com/tutorials/tutorial-three-python.html http://www.rabbitmq.com/tutorials/tutorial-four-python.html http://www.rabbitmq.com/tutorials/tutorial-five-python.html

for different ways to route messages. I know they are for python and java but its good to understand the principles, decide what you are doing and then find how to do it in JS. Its sounds like you want to do a simple fanout (tutorial 3), which sends the messages to all queues connected to the exchange.

The difference with what you are doing and what you want to do is basically that you are going to set up and exchange or type fanout. Fanout excahnges send all messages to all connected queues. Each queue will have a consumer that will have access to all the messages separately.

Yes this is commonly done, it is one of the features of AMPQ.

Java, Calculate the number of days between two dates

// http://en.wikipedia.org/wiki/Julian_day
public static int julianDay(int year, int month, int day) {
  int a = (14 - month) / 12;
  int y = year + 4800 - a;
  int m = month + 12 * a - 3;
  int jdn = day + (153 * m + 2)/5 + 365*y + y/4 - y/100 + y/400 - 32045;
  return jdn;
}

public static int diff(int y1, int m1, int d1, int y2, int m2, int d2) {
  return julianDay(y1, m1, d1) - julianDay(y2, m2, d2);
}

How to create a HTML Table from a PHP array?

PHP code:

$multiarray = array (

    array("name"=>"Argishti", "surname"=>"Yeghiazaryan"),
    array("name"=>"Armen", "surname"=>"Mkhitaryan"),
    array("name"=>"Arshak", "surname"=>"Aghabekyan"),

);

$count = 0;

foreach ($multiarray as $arrays){
    $count++;
    echo "<table>" ;               

    echo "<span>table $count</span>";
    echo "<tr>";
    foreach ($arrays as $names => $surnames){

        echo "<th>$names</th>";
        echo "<td>$surnames</td>";

    }
    echo "</tr>";
    echo "</table>";
}

CSS:

table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;``
}

How to shutdown my Jenkins safely?

The full list of commands is available at http://your-jenkins/cli

The command for a clean shutdown is http://your-jenkins/safe-shutdown

You may also want to use http://your-jenkins/safe-restart

How to get 0-padded binary representation of an integer in java?

There is no binary conversion built into the java.util.Formatter, I would advise you to either use String.replace to replace space character with zeros, as in:

String.format("%16s", Integer.toBinaryString(1)).replace(" ", "0")

Or implement your own logic to convert integers to binary representation with added left padding somewhere along the lines given in this so. Or if you really need to pass numbers to format, you can convert your binary representation to BigInteger and then format that with leading zeros, but this is very costly at runtime, as in:

String.format("%016d", new BigInteger(Integer.toBinaryString(1)))

Circular (or cyclic) imports in Python

If you do import foo (inside bar.py) and import bar (inside foo.py), it will work fine. By the time anything actually runs, both modules will be fully loaded and will have references to each other.

The problem is when instead you do from foo import abc (inside bar.py) and from bar import xyz (inside foo.py). Because now each module requires the other module to already be imported (so that the name we are importing exists) before it can be imported.

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

Transparent CSS background color

now you can use rgba in CSS properties like this:

.class {
    background: rgba(0,0,0,0.5);
}

0.5 is the transparency, change the values according to your design.

Live demo http://jsfiddle.net/EeAaB/

more info http://css-tricks.com/rgba-browser-support/

Mongoose: findOneAndUpdate doesn't return updated document

Mongoose maintainer here. You need to set the new option to true (or, equivalently, returnOriginal to false)

await User.findOneAndUpdate(filter, update, { new: true });

// Equivalent
await User.findOneAndUpdate(filter, update, { returnOriginal: false });

See Mongoose findOneAndUpdate() docs and this tutorial on updating documents in Mongoose.

SQL Select between dates

SQLLite requires dates to be in YYYY-MM-DD format. Since the data in your database and the string in your query isn't in that format, it is probably treating your "dates" as strings.

Fastest way to compute entropy in Python

The above answer is good, but if you need a version that can operate along different axes, here's a working implementation.

def entropy(A, axis=None):
    """Computes the Shannon entropy of the elements of A. Assumes A is 
    an array-like of nonnegative ints whose max value is approximately 
    the number of unique values present.

    >>> a = [0, 1]
    >>> entropy(a)
    1.0
    >>> A = np.c_[a, a]
    >>> entropy(A)
    1.0
    >>> A                   # doctest: +NORMALIZE_WHITESPACE
    array([[0, 0], [1, 1]])
    >>> entropy(A, axis=0)  # doctest: +NORMALIZE_WHITESPACE
    array([ 1., 1.])
    >>> entropy(A, axis=1)  # doctest: +NORMALIZE_WHITESPACE
    array([[ 0.], [ 0.]])
    >>> entropy([0, 0, 0])
    0.0
    >>> entropy([])
    0.0
    >>> entropy([5])
    0.0
    """
    if A is None or len(A) < 2:
        return 0.

    A = np.asarray(A)

    if axis is None:
        A = A.flatten()
        counts = np.bincount(A) # needs small, non-negative ints
        counts = counts[counts > 0]
        if len(counts) == 1:
            return 0. # avoid returning -0.0 to prevent weird doctests
        probs = counts / float(A.size)
        return -np.sum(probs * np.log2(probs))
    elif axis == 0:
        entropies = map(lambda col: entropy(col), A.T)
        return np.array(entropies)
    elif axis == 1:
        entropies = map(lambda row: entropy(row), A)
        return np.array(entropies).reshape((-1, 1))
    else:
        raise ValueError("unsupported axis: {}".format(axis))

How to get the last characters in a String in Java, regardless of String size

This code works for me perfectly:

String numbers = text.substring(Math.max(0, text.length() - 7));

Grouping switch statement cases together?

You can't remove keyword case. But your example can be written shorter like this:

switch ((Answer - 1) / 4)                                      
{
   case 0:
      cout << "You need more cars.";
      break;                                        
   case 1:
      cout << "Now you need a house.";
      break;                                        
   default:
      cout << "What are you? A peace-loving hippie freak?";
}

How can I override Bootstrap CSS styles?

If you are planning to make any rather big changes, it might be a good idea to make them directly in bootstrap itself and rebuild it. Then, you could reduce the amount of data loaded.

Please refer to Bootstrap on GitHub for the build guide.

Android Studio Stuck at Gradle Download on create new project

For Windows Users

Use your Network Resource Monitor

enter image description here

Open Task Manager [Ctrl+Shift+Esc]

Performance Tab

Open Resource Monitor (From the bottom)

First i decided to wait after reading answers here. But how long..? How to make sure it will finish.? They should have provided percentage of download, but they have not. So to know some kind of progress is going on, open this network resource monitor, it will show you some kind of download is going on for the Studio64.exe. IF not (if it shows 0B/Sec), then either network is not available or the application is not responding.

Installing Apache Maven Plugin for Eclipse

  1. In Eclipse Select Help -> Marketplace

  2. Enter "Maven" in Find box and click on Go button

  3. Click on "Install" button for Maven Integration for Eclipse (Juno and newer)

With this, maven should get install without any problem.

Take nth column in a text file

You can use the cut command:

cut -d' ' -f3,5 < datafile.txt

prints

1657 19.6117
1410 18.8302
3078 18.6695
2434 14.0508
3129 13.5495

the

  • -d' ' - mean, use space as a delimiter
  • -f3,5 - take and print 3rd and 5th column

The cut is much faster for large files as a pure shell solution. If your file is delimited with multiple whitespaces, you can remove them first, like:

sed 's/[\t ][\t ]*/ /g' < datafile.txt | cut -d' ' -f3,5

where the (gnu) sed will replace any tab or space characters with a single space.

For a variant - here is a perl solution too:

perl -lanE 'say "$F[2] $F[4]"' < datafile.txt

bootstrap 3 wrap text content within div for horizontal alignment

1) Maybe oveflow: hidden; will do the trick?

2) You need to set the size of each div with the text and button so that each of these divs have the same height. Then for your button:

button {
  position: absolute;
  bottom: 0;
}

PHP foreach with Nested Array?

As I understand , all of previous answers , does not make an Array output, In my case : I have a model with parent-children structure (simplified code here):

public function parent(){

    return $this->belongsTo('App\Models\Accounting\accounting_coding', 'parent_id');
}


public function children()
{

    return $this->hasMany('App\Models\Accounting\accounting_coding', 'parent_id');
}

and if you want to have all of children IDs as an Array , This approach is fine and working for me :

public function allChildren()
{
    $allChildren = [];
    if ($this->has_branch) {

        foreach ($this->children as $child) {

            $subChildren = $child->allChildren();

            if (count($subChildren) == 1) {
                $allChildren  [] = $subChildren[0];
            } else if (count($subChildren) > 1) {
                $allChildren += $subChildren;
            }
        }
    }
    $allChildren  [] = $this->id;//adds self Id to children Id list

    return $allChildren; 
}

the allChildren() returns , all of childrens as a simple Array .

How to define hash tables in Bash?

Prior to bash 4 there is no good way to use associative arrays in bash. Your best bet is to use an interpreted language that actually has support for such things, like awk. On the other hand, bash 4 does support them.

As for less good ways in bash 3, here is a reference than might help: http://mywiki.wooledge.org/BashFAQ/006

Javascript, Time and Date: Getting the current minute, hour, day, week, month, year of a given millisecond time

Additionally, how do I retrieve the number of days of a given month?

Aside from calculating it yourself (and consequently having to get leap years right), you can use a Date calculation to do it:

var y= 2010, m= 11;            // December 2010 - trap: months are 0-based in JS

var next= Date.UTC(y, m+1);    // timestamp of beginning of following month
var end= new Date(next-1);     // date for last second of this month
var lastday= end.getUTCDate(); // 31

In general for timestamp/date calculations I'd recommend using the UTC-based methods of Date, like getUTCSeconds instead of getSeconds(), and Date.UTC to get a timestamp from a UTC date, rather than new Date(y, m), so you don't have to worry about the possibility of weird time discontinuities where timezone rules change.

FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison

I've compared a few of the methods possible for doing this, including pandas, several numpy methods, and a list comprehension method.

First, let's start with a baseline:

>>> import numpy as np
>>> import operator
>>> import pandas as pd

>>> x = [1, 2, 1, 2]
>>> %time count = np.sum(np.equal(1, x))
>>> print("Count {} using numpy equal with ints".format(count))
CPU times: user 52 µs, sys: 0 ns, total: 52 µs
Wall time: 56 µs
Count 2 using numpy equal with ints

So, our baseline is that the count should be correct 2, and we should take about 50 us.

Now, we try the naive method:

>>> x = ['s', 'b', 's', 'b']
>>> %time count = np.sum(np.equal('s', x))
>>> print("Count {} using numpy equal".format(count))
CPU times: user 145 µs, sys: 24 µs, total: 169 µs
Wall time: 158 µs
Count NotImplemented using numpy equal
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/ipykernel_launcher.py:1: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
  """Entry point for launching an IPython kernel.

And here, we get the wrong answer (NotImplemented != 2), it takes us a long time, and it throws the warning.

So we'll try another naive method:

>>> %time count = np.sum(x == 's')
>>> print("Count {} using ==".format(count))
CPU times: user 46 µs, sys: 1 µs, total: 47 µs
Wall time: 50.1 µs
Count 0 using ==

Again, the wrong answer (0 != 2). This is even more insidious because there's no subsequent warnings (0 can be passed around just like 2).

Now, let's try a list comprehension:

>>> %time count = np.sum([operator.eq(_x, 's') for _x in x])
>>> print("Count {} using list comprehension".format(count))
CPU times: user 55 µs, sys: 1 µs, total: 56 µs
Wall time: 60.3 µs
Count 2 using list comprehension

We get the right answer here, and it's pretty fast!

Another possibility, pandas:

>>> y = pd.Series(x)
>>> %time count = np.sum(y == 's')
>>> print("Count {} using pandas ==".format(count))
CPU times: user 453 µs, sys: 31 µs, total: 484 µs
Wall time: 463 µs
Count 2 using pandas ==

Slow, but correct!

And finally, the option I'm going to use: casting the numpy array to the object type:

>>> x = np.array(['s', 'b', 's', 'b']).astype(object)
>>> %time count = np.sum(np.equal('s', x))
>>> print("Count {} using numpy equal".format(count))
CPU times: user 50 µs, sys: 1 µs, total: 51 µs
Wall time: 55.1 µs
Count 2 using numpy equal

Fast and correct!

Why not use tables for layout in HTML?

I still don't quite understand how divs / CSS make it easier to change a page design when you consider the amount of testing to ensure the changes work on all browsers, especially with all the hacks and so on. Its a hugely frustrating and tedious process which wastes large amounts of time and money. Thankfully the 508 legislation only applies to the USA (land of the free - yeah right) and so being as I am based in the UK, I can develop web sites in whatever style I choose. Contrary to popular (US) belief, legislation made in Washington doesn't apply to the rest of the world - thank goodness for that. It must have been a good day in the world of web design the day the legislation came into force. I think I'm becoming increasingly cynical as I get older with 25 years in the IT industry but I feel sure this kind of legislation is just to protect jobs. In reality anyone can knock together a reasonable web page with a couple of tables. It takes a lot more effort and knowledge to do this with DIVs / CSS. In my experience it can take hours and hours Googling to find solutions to quite simple problems and reading incomprehensible articles in forums full of idealistic zealots all argueing about the 'right' way to do things. You can't just dip your toe in the water and get things to work properly in every case. It also seems to me that the lack of a definitive guide to using DIVS / CSS "out of the box", that applies to all situations, working on browsers, and written using 'normal' language with no geek speak, also smells of a bit of protectionism.
I'm an application developer and I would say it takes almost twice as long to figure out layout problems and test against all browsers than it does to create the basic application, design and implement business objects, and create the database back end. My time = money, both for me and my customers alike so I am sorry if I don't reject all the pro DIV / CSS arguments in favour of cutting costs and providing value for money for my customers. Maybe its just the way that developers minds work, but it seems to me far easier to change a complex table structure than it is to modify DIVs / CSS. Thankfully it now appears that a solution to these issues is now available - its called WPF.

How do you make Git work with IntelliJ?

git.exe is common for any git based applications like GitHub, Bitbucket etc. Some times it is possible that you have already installed another git based application so git.exe will be present in the bin folder of that application.

For example if you installed bitbucket before github in your PC, you will find git.exe in C:\Users\{username}\AppData\Local\Atlassian\SourceTree\git_local\bin instead of C:\Users\{username}\AppData\Local\GitHub\PortableGit.....\bin.

HTML favicon won't show on google chrome

I moved ico file to root folder and link it. It worked for me. Also, in chrome, I have to wait 30 mins to get cache cleared and new changes to take affect.

How to reduce a huge excel file

I save files in .XLSB format to cut size. The XLSB also allows for VBA and macros to stay with the file. I've seen 50 meg files down to less than 10 with the Binary formatting.

Create a branch in Git from another branch

If you want create a new branch from any of the existing branches in Git, just follow the options.

First change/checkout into the branch from where you want to create a new branch. For example, if you have the following branches like:

  • master
  • dev
  • branch1

So if you want to create a new branch called "subbranch_of_b1" under the branch named "branch1" follow the steps:

  1. Checkout or change into "branch1"

    git checkout branch1
    
  2. Now create your new branch called "subbranch_of_b1" under the "branch1" using the following command.

    git checkout -b subbranch_of_b1 branch1
    

    The above will create a new branch called subbranch_of_b1 under the branch branch1 (note that branch1 in the above command isn't mandatory since the HEAD is currently pointing to it, you can precise it if you are on a different branch though).

  3. Now after working with the subbranch_of_b1 you can commit and push or merge it locally or remotely.

A sample Graphical Illustration Of Creating Branches Under another Branch

push the subbranch_of_b1 to remote

 git push origin subbranch_of_b1 

How to get min, seconds and milliseconds from datetime.now() in python?

Sorry to open an old thread but I'm posting just in case it helps someone. This seems to be the easiest way to do this in Python 3.

from datetime import datetime

Date = str(datetime.now())[:10]
Hour = str(datetime.now())[11:13]
Minute = str(datetime.now())[14:16]
Second = str(datetime.now())[17:19]
Millisecond = str(datetime.now())[20:]

If you need the values as a number just cast them as an int e.g

Hour = int(str(datetime.now())[11:13])

What is std::move(), and when should it be used?

std::move itself does nothing rather than a static_cast. According to cppreference.com

It is exactly equivalent to a static_cast to an rvalue reference type.

Thus, it depends on the type of the variable you assign to after the move, if the type has constructors or assign operators that takes a rvalue parameter, it may or may not steal the content of the original variable, so, it may leave the original variable to be in an unspecified state:

Unless otherwise specified, all standard library objects that have been moved from being placed in a valid but unspecified state.

Because there is no special move constructor or move assign operator for built-in literal types such as integers and raw pointers, so, it will be just a simple copy for these types.

T-SQL: Deleting all duplicate rows but keeping one

Here's my twist on it, with a runnable example. Note this will only work in the situation where Id is unique, and you have duplicate values in other columns.

DECLARE @SampleData AS TABLE (Id int, Duplicate varchar(20))

INSERT INTO @SampleData
SELECT 1, 'ABC' UNION ALL
SELECT 2, 'ABC' UNION ALL
SELECT 3, 'LMN' UNION ALL
SELECT 4, 'XYZ' UNION ALL
SELECT 5, 'XYZ'

DELETE FROM @SampleData WHERE Id IN (
    SELECT Id FROM (
        SELECT 
            Id
            ,ROW_NUMBER() OVER (PARTITION BY [Duplicate] ORDER BY Id) AS [ItemNumber]
            -- Change the partition columns to include the ones that make the row distinct
        FROM 
            @SampleData
    ) a WHERE ItemNumber > 1 -- Keep only the first unique item
)

SELECT * FROM @SampleData

And the results:

Id          Duplicate
----------- ---------
1           ABC
3           LMN
4           XYZ

Not sure why that's what I thought of first... definitely not the simplest way to go but it works.

What is the different between RESTful and RESTless

REST stands for REpresentational State Transfer and goes a little something like this:

We have a bunch of uniquely addressable 'entities' that we want made available via a web application. Those entities each have some identifier and can be accessed in various formats. REST defines a bunch of stuff about what GET, POST, etc mean for these purposes.

the basic idea with REST is that you can attach a bunch of 'renderers' to different entities so that they can be available in different formats easily using the same HTTP verbs and url formats.

For more clarification on what RESTful means and how it is used google rails. Rails is a RESTful framework so there's loads of good information available in its docs and associated blog posts. Worth a read even if you arent keen to use the framework. For example: http://www.sitepoint.com/restful-rails-part-i/

RESTless means not restful. If you have a web app that does not adhere to RESTful principles then it is not RESTful

org.hibernate.MappingException: Unknown entity

I encountered the same problem when I switched to AnnotationSessionFactoryBean. I was using entity.hbm.xml before.

I found that My class was missing following annotation which resolved the issue in my case:

@Entity
@Table(name = "MyTestEntity")
@XmlRootElement

Insert Unicode character into JavaScript

The answer is correct, but you don't need to declare a variable. A string can contain your character:

"This string contains omega, that looks like this: \u03A9"

Unfortunately still those codes in ASCII are needed for displaying UTF-8, but I am still waiting (since too many years...) the day when UTF-8 will be same as ASCII was, and ASCII will be just a remembrance of the past.

What is default list styling (CSS)?

I used to set this CSS to remove the reset :

ul { 
   list-style-type: disc; 
   list-style-position: inside; 
}
ol { 
   list-style-type: decimal; 
   list-style-position: inside; 
}
ul ul, ol ul { 
   list-style-type: circle; 
   list-style-position: inside; 
   margin-left: 15px; 
}
ol ol, ul ol { 
   list-style-type: lower-latin; 
   list-style-position: inside; 
   margin-left: 15px; 
}

EDIT : with a specific class of course...

Pass correct "this" context to setTimeout callback?

In browsers other than Internet Explorer, you can pass parameters to the function together after the delay:

var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);

So, you can do this:

var timeoutID = window.setTimeout(function (self) {
  console.log(self); 
}, 500, this);

This is better in terms of performance than a scope lookup (caching this into a variable outside of the timeout / interval expression), and then creating a closure (by using $.proxy or Function.prototype.bind).

The code to make it work in IEs from Webreflection:

/*@cc_on
(function (modifierFn) {
  // you have to invoke it as `window`'s property so, `window.setTimeout`
  window.setTimeout = modifierFn(window.setTimeout);
  window.setInterval = modifierFn(window.setInterval);
})(function (originalTimerFn) {
    return function (callback, timeout){
      var args = [].slice.call(arguments, 2);
      return originalTimerFn(function () { 
        callback.apply(this, args) 
      }, timeout);
    }
});
@*/

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

Determine the type of an object?

type() is a better solution than isinstance(), particularly for booleans:

True and False are just keywords that mean 1 and 0 in python. Thus,

isinstance(True, int)

and

isinstance(False, int)

both return True. Both booleans are an instance of an integer. type(), however, is more clever:

type(True) == int

returns False.

How to convert JTextField to String and String to JTextField?

The JTextField offers a getText() and a setText() method - those are for getting and setting the content of the text field.

How can I see all the "special" characters permissible in a varchar or char field in SQL Server?

EDIT based on comments:

If you have line breaks in your result set and want to remove them, make your query this way:

SELECT
    REPLACE(REPLACE(YourColumn1,CHAR(13),' '),CHAR(10),' ')
   ,REPLACE(REPLACE(YourColumn2,CHAR(13),' '),CHAR(10),' ')
   ,REPLACE(REPLACE(YourColumn3,CHAR(13),' '),CHAR(10),' ')
   --^^^^^^^^^^^^^^^           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   --only add the above code to strings that are having line breaks, not to numbers or dates
   FROM YourTable...
   WHERE ...

This will replace all the line breaks with a space character.

Run this to "get" all characters permitted in a char() and varchar():

;WITH AllNumbers AS
(
    SELECT 1 AS Number
    UNION ALL
    SELECT Number+1
        FROM AllNumbers
        WHERE Number+1<256
)
SELECT Number AS ASCII_Value,CHAR(Number) AS ASCII_Char FROM AllNumbers
OPTION (MAXRECURSION 256)

OUTPUT:

ASCII_Value ASCII_Char
----------- ----------
1           
2           
3           
4           
5           
6           
7           
8           
9               
10          

11          
12          
13          

14          
15          
16          
17          
18          
19          
20          
21          
22          
23          
24          
25          
26          
27          
28          
29          
30          
31          
32           
33          !
34          "
35          #
36          $
37          %
38          &
39          '
40          (
41          )
42          *
43          +
44          ,
45          -
46          .
47          /
48          0
49          1
50          2
51          3
52          4
53          5
54          6
55          7
56          8
57          9
58          :
59          ;
60          <
61          =
62          >
63          ?
64          @
65          A
66          B
67          C
68          D
69          E
70          F
71          G
72          H
73          I
74          J
75          K
76          L
77          M
78          N
79          O
80          P
81          Q
82          R
83          S
84          T
85          U
86          V
87          W
88          X
89          Y
90          Z
91          [
92          \
93          ]
94          ^
95          _
96          `
97          a
98          b
99          c
100         d
101         e
102         f
103         g
104         h
105         i
106         j
107         k
108         l
109         m
110         n
111         o
112         p
113         q
114         r
115         s
116         t
117         u
118         v
119         w
120         x
121         y
122         z
123         {
124         |
125         }
126         ~
127         
128         €
129         
130         ‚
131         ƒ
132         „
133         …
134         †
135         ‡
136         ˆ
137         ‰
138         Š
139         ‹
140         Œ
141         
142         Ž
143         
144         
145         ‘
146         ’
147         “
148         ”
149         •
150         –
151         —
152         ˜
153         ™
154         š
155         ›
156         œ
157         
158         ž
159         Ÿ
160          
161         ¡
162         ¢
163         £
164         ¤
165         ¥
166         ¦
167         §
168         ¨
169         ©
170         ª
171         «
172         ¬
173         ­
174         ®
175         ¯
176         °
177         ±
178         ²
179         ³
180         ´
181         µ
182         ¶
183         ·
184         ¸
185         ¹
186         º
187         »
188         ¼
189         ½
190         ¾
191         ¿
192         À
193         Á
194         Â
195         Ã
196         Ä
197         Å
198         Æ
199         Ç
200         È
201         É
202         Ê
203         Ë
204         Ì
205         Í
206         Î
207         Ï
208         Ð
209         Ñ
210         Ò
211         Ó
212         Ô
213         Õ
214         Ö
215         ×
216         Ø
217         Ù
218         Ú
219         Û
220         Ü
221         Ý
222         Þ
223         ß
224         à
225         á
226         â
227         ã
228         ä
229         å
230         æ
231         ç
232         è
233         é
234         ê
235         ë
236         ì
237         í
238         î
239         ï
240         ð
241         ñ
242         ò
243         ó
244         ô
245         õ
246         ö
247         ÷
248         ø
249         ù
250         ú
251         û
252         ü
253         ý
254         þ
255         ÿ

(255 row(s) affected)

How to convert a Drawable to a Bitmap?

Android provides a non straight foward solution: BitmapDrawable. To get the Bitmap , we'll have to provide the resource id R.drawable.flower_pic to the a BitmapDrawable and then cast it to a Bitmap.

Bitmap bm = ((BitmapDrawable) getResources().getDrawable(R.drawable.flower_pic)).getBitmap();

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

This could be solved without VBA by the following technique.

In this example I am counting all the threes (3) in the range A:A of the sheets Page M904, Page M905 and Page M906.

List all the sheet names in a single continuous range like in the following example. Here listed in the range D3:D5.

enter image description here

Then by having the lookup value in cell B2, the result can be found in cell B4 by using the following formula:

=SUMPRODUCT(COUNTIF(INDIRECT("'"&D3:D5&"'!A:A"), B2))

Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

I removed the mode from

<tx:annotation-driven mode="aspectj"
transaction-manager="transactionManager" />

to make this work

Make HTML5 video poster be same size as video itself

I came up with this idea and it works perfectly. Okay so basically we want to get rid of the videos first frame from the display and then resize the poster to the videos actual size. If we then set the dimensions we have completed one of these tasks. Then only one remains. So now, the only way I know to get rid of the first frame is to actually define a poster. However we are going to give the video a faked one, one that doesn't exist. This will result in a blank display with the background transparent. I.e. our parent div's background will be visible.

Simple to use, however it might not work with all web browsers if you want to resize the dimension of the background of the div to the dimension of the video since my code is using "background-size".

HTML/HTML5:

<div class="video_poster">
    <video poster="dasdsadsakaslmklda.jpg" controls>
        <source src="videos/myvideo.mp4" type="video/mp4">
        Your browser does not support the video tag.
    </video>
<div>

CSS:

video{
    width:694px;
    height:390px;
}
.video_poster{
    width:694px;
    height:390px;
    background-size:694px 390px;
    background-image:url(images/myvideo_poster.jpg);
}

TypeError: unsupported operand type(s) for /: 'str' and 'str'

The first thing you should do is learn to read error messages. What does it tell you -- that you can't use two strings with the divide operator.

So, ask yourself why they are strings and how do you make them not-strings. They are strings because all input is done via strings. And the way to make then not-strings is to convert them.

One way to convert a string to an integer is to use the int function. For example:

percent = (int(pyc) / int(tpy)) * 100

php exec() is not executing the command

You might also try giving the full path to the binary you're trying to run. That solved my problem when trying to use ImageMagick.

How do I check which version of NumPy I'm using?

You can get numpy version using Terminal or a Python code.

In a Terminal (bash) using Ubuntu:

pip list | grep numpy

In python 3.6.7, this code shows the numpy version:

import numpy
print (numpy.version.version)

If you insert this code in the file shownumpy.py, you can compile it:

python shownumpy.py

or

python3 shownumpy.py

I've got this output:

1.16.1

Node.js Generate html

You can use jsdom

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { document } = (new JSDOM(`...`)).window;

or, take a look at cheerio, it may more suitable in your case.

how to send a post request with a web browser

with a form, just set method to "post"

<form action="blah.php" method="post">
  <input type="text" name="data" value="mydata" />
  <input type="submit" />
</form>

How Does Modulus Divison Work

Lets say you have 17 mod 6.

what total of 6 will get you the closest to 17, it will be 12 because if you go over 12 you will have 18 which is more that the question of 17 mod 6. You will then take 12 and minus from 17 which will give you your answer, in this case 5.

17 mod 6=5

How to use SVG markers in Google Maps API v3

As mentioned by others in this thread, don't forget to explicitly set the width and height attributes in the svg like so:

<svg id="some_id" data-name="some_name" xmlns="http://www.w3.org/2000/svg"
     viewBox="0 0 26 42"
     width="26px" height="42px">

if you don't do that no js manipulation can help you as gmaps will not have a frame of reference and always use a standard size.

(i know it has been mentioned in some comments, but they are easy to miss. This information helped me in various cases)

jQuery form input select by id

For example like this:

var value = $("#a").find("#b").val()

What does question mark and dot operator ?. mean in C# 6.0?

This is relatively new to C# which makes it easy for us to call the functions with respect to the null or non-null values in method chaining.

old way to achieve the same thing was:

var functionCaller = this.member;
if (functionCaller!= null)
    functionCaller.someFunction(var someParam);

and now it has been made much easier with just:

member?.someFunction(var someParam);

I strongly recommend this doc page.

How to serialize Joda DateTime with Jackson JSON processor?

https://stackoverflow.com/a/10835114/1113510

Although you can put an annotation for each date field, is better to do a global configuration for your object mapper. If you use jackson you can configure your spring as follow:

<bean id="jacksonObjectMapper" class="com.company.CustomObjectMapper" />

<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
    factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" >
</bean>

For CustomObjectMapper:

public class CustomObjectMapper extends ObjectMapper {

    public CustomObjectMapper() {
        super();
        configure(Feature.WRITE_DATES_AS_TIMESTAMPS, false);
        setDateFormat(new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'ZZZ (z)"));
    }
}

Of course, SimpleDateFormat can use any format you need.

jquery UI dialog: how to initialize without a title bar?

This is the easiest way to do it and it will only remove the titlebar in that one specific dialog;

$('.dialog_selector').find('.ui-dialog-titlebar').hide();

Auto-increment on partial primary key with Entity Framework Core

Specifying the column type as serial for PostgreSQL to generate the id.

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column(Order=1, TypeName="serial")]
public int ID { get; set; }

https://www.postgresql.org/docs/current/static/datatype-numeric.html#DATATYPE-SERIAL

Is there a NumPy function to return the first index of something in an array?

The numpy_indexed package (disclaimer, I am its author) contains a vectorized equivalent of list.index for numpy.ndarray; that is:

sequence_of_arrays = [[0, 1], [1, 2], [-5, 0]]
arrays_to_query = [[-5, 0], [1, 0]]

import numpy_indexed as npi
idx = npi.indices(sequence_of_arrays, arrays_to_query, missing=-1)
print(idx)   # [2, -1]

This solution has vectorized performance, generalizes to ndarrays, and has various ways of dealing with missing values.

Best way to check if an PowerShell Object exist?

Incase you you're like me and you landed here trying to find a way to tell if your PowerShell variable is this particular flavor of non-existent:

COM object that has been separated from its underlying RCW cannot be used.

Then here's some code that worked for me:

function Count-RCW([__ComObject]$ComObj){
   try{$iuk = [System.Runtime.InteropServices.Marshal]::GetIUnknownForObject($ComObj)}
   catch{return 0}
   return [System.Runtime.InteropServices.Marshal]::Release($iuk)-1
}

example usage:

if((Count-RCW $ExcelApp) -gt 0){[System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($ExcelApp)}

mashed together from other peoples' better answers:

and some other cool things to know:

How to unzip a file in Powershell?

Using expand-archive but auto-creating directories named after the archive:

function unzip ($file) {
    $dirname = (Get-Item $file).Basename
    New-Item -Force -ItemType directory -Path $dirname
    expand-archive $file -OutputPath $dirname -ShowProgress
}

How to serialize an object to XML without getting xmlns="..."?

If you want to get rid of the extra xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" and xmlns:xsd="http://www.w3.org/2001/XMLSchema", but still keep your own namespace xmlns="http://schemas.YourCompany.com/YourSchema/", you use the same code as above except for this simple change:

//  Add lib namespace with empty prefix  
ns.Add("", "http://schemas.YourCompany.com/YourSchema/");   

Why does the C++ STL not provide any "tree" containers?

In a way, std::map is a tree (it is required to have the same performance characteristics as a balanced binary tree) but it doesn't expose other tree functionality. The likely reasoning behind not including a real tree data structure was probably just a matter of not including everything in the stl. The stl can be looked as a framework to use in implementing your own algorithms and data structures.

In general, if there's a basic library functionality that you want, that's not in the stl, the fix is to look at BOOST.

Otherwise, there's a bunch of libraries out there, depending on the needs of your tree.

How to make HTML open a hyperlink in another window or tab?

<a href="http://www.starfall.com/" target="_blank">Starfall</a>

Whether it opens in a tab or another window though is up to how a user has configured her browser.

jQuery: Count number of list elements?

try

$("#mylist").children().length

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

My problem was one of my elements had the xmlns attribute:

<?xml version="1.0" encoding="utf-8"?>
<RETS ReplyCode="0">
    <RETS-RESPONSE xmlns="blahblah">
        ...
    </RETS-RESPONSE>
</RETS>

No matter what I tried the xmlns attribute seemed to be breaking the serializer, so I removed any trace of xmlns="..." from the xml file:

<?xml version="1.0" encoding="utf-8"?>
<RETS ReplyCode="0">
    <RETS-RESPONSE>
        ...
    </RETS-RESPONSE>
</RETS>

and voila! Everything worked.

I now parse the xml file to remove this attribute before deserializing. Not sure why this works, maybe my case is different since the element containing the xmlns attribute is not the root element.

How to get Spinner selected item value to string?

    spinnerType = (AppCompatSpinner) findViewById(R.id.account_type);
    spinnerType.setPrompt("Select Type");

    spinnerType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            TypeItem clickedItem = (TypeItem) parent.getItemAtPosition(position);
            String TypeName = clickedItem.getTypeName();
            Toast.makeText(AddAccount.this, TypeName + " selected", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

Why is IoC / DI not common in Python?

pytest fixtures all based on DI (source)

Extract elements of list at odd positions

For the odd positions, you probably want:

>>>> list_ = list(range(10))
>>>> print list_[1::2]
[1, 3, 5, 7, 9]
>>>>

Getting a list of values from a list of dicts

For a very simple case like this, a comprehension, as in Ismail Badawi's answer is definitely the way to go.

But when things get more complicated, and you need to start writing multi-clause or nested comprehensions with complex expressions in them, it's worth looking into other alternatives. There are a few different (quasi-)standard ways to specify XPath-style searches on nested dict-and-list structures, such as JSONPath, DPath, and KVC. And there are nice libraries on PyPI for them.

Here's an example with the library named dpath, showing how it can simplify something just a bit more complicated:

>>> dd = {
...     'fruits': [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3}],
...     'vehicles': [{'value': 'cars', 'blah':4}]}

>>> {key: [{'value': d['value']} for d in value] for key, value in dd.items()}
{'fruits': [{'value': 'apple'}, {'value': 'banana'}],
 'vehicles': [{'value': 'cars'}]}

>>> dpath.util.search(dd, '*/*/value')
{'fruits': [{'value': 'apple'}, {'value': 'banana'}],
 'vehicles': [{'value': 'cars'}]}

Or, using jsonpath-ng:

>>> [d['value'] for key, value in dd.items() for d in value]
['apple', 'banana', 'cars']
>>> [m.value for m in jsonpath_ng.parse('*.[*].value').find(dd)]
['apple', 'banana', 'cars']

This one may not look quite as simple at first glance, because find returns match objects, which include all kinds of things besides just the matched value, such as a path directly to each item. But for more complex expressions, being able to specify a path like '*.[*].value' instead of a comprehension clause for each * can make a big difference. Plus, JSONPath is a language-agnostic specification, and there are even online testers that can be very handy for debugging.

How to search in an array with preg_match?

Use preg_grep

$array = preg_grep(
    '/(my\n+string\n+)/i',
    array( 'file' , 'my string  => name', 'this')
);

How to select an element inside "this" in jQuery?

I use this to get the Parent, similarly for child

$( this ).children( 'li.target' ).css("border", "3px double red");

Good Luck

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

I don't know whether this has appeared obvious here. I would like to point out that as far as client-side (browser) JavaScript is concerned, you can add type="module" to both external as well as internal js scripts.

Say, you have a file 'module.js':

var a = 10;
export {a};

You can use it in an external script, in which you do the import, eg.:

<!DOCTYPE html><html><body>
<script type="module" src="test.js"></script><!-- Here use type="module" rather than type="text/javascript" -->
</body></html>

test.js:

import {a} from "./module.js";
alert(a);

You can also use it in an internal script, eg.:

<!DOCTYPE html><html><body>
<script type="module">
    import {a} from "./module.js";
    alert(a);
</script>
</body></html>

It is worthwhile mentioning that for relative paths, you must not omit the "./" characters, ie.:

import {a} from "module.js";     // this won't work

'Operation is not valid due to the current state of the object' error during postback

If your stack trace looks like following then you are sending a huge load of json objects to server

Operation is not valid due to the current state of the object. 
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
    at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
    at System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(String input)
    at Failing.Page_Load(Object sender, EventArgs e) 
    at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
    at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
    at System.Web.UI.Control.OnLoad(EventArgs e)
    at System.Web.UI.Control.LoadRecursive()
    at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

For resolution, please update your web config with following key. If you are not able to get the stack trace then please use fiddler. If it still does not help then please try increasing the number to 10000 or something

<configuration>
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="1000" />
</appSettings>
</configuration>

For more details, please read this Microsoft kb article

What is the Swift equivalent of respondsToSelector?

Functions are first-class types in Swift, so you can check whether an optional function defined in a protocol has been implemented by comparing it to nil:

if (someObject.someMethod != nil) {
    someObject.someMethod!(someArgument)
} else {
    // do something else
}

Get length of array?

Function

Public Function ArrayLen(arr As Variant) As Integer
    ArrayLen = UBound(arr) - LBound(arr) + 1
End Function

Usage

Dim arr(1 To 3) As String  ' Array starting at 1 instead of 0: nightmare fuel
Debug.Print ArrayLen(arr)  ' Prints 3.  Everything's going to be ok.

c++ parse int from string

You can use boost::lexical_cast:

#include <iostream>
#include <boost/lexical_cast.hpp>

int main( int argc, char* argv[] ){
std::string s1 = "10";
std::string s2 = "abc";
int i;

   try   {
      i = boost::lexical_cast<int>( s1 );
   }
   catch( boost::bad_lexical_cast & e ){
      std::cout << "Exception caught : " << e.what() << std::endl;
   }

   try   {
      i = boost::lexical_cast<int>( s2 );
   }
   catch( boost::bad_lexical_cast & e ){
      std::cout << "Exception caught : " << e.what() << std::endl;
   }

   return 0;
}

Is there a difference between /\s/g and /\s+/g?

\s means "one space", and \s+ means "one or more spaces".

But, because you're using the /g flag (replace all occurrences) and replacing with the empty string, your two expressions have the same effect.

How to make a vertical SeekBar in Android?

Working example

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;

public class VerticalSeekBar extends SeekBar {

    public VerticalSeekBar(Context context) {
        super(context);
    }

    public VerticalSeekBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public VerticalSeekBar(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(h, w, oldh, oldw);
    }

   @Override
   public synchronized void setProgress(int progress)  // it is necessary for calling setProgress on click of a button
   {
    super.setProgress(progress);
    onSizeChanged(getWidth(), getHeight(), 0, 0); 
   }
    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(heightMeasureSpec, widthMeasureSpec);
        setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
    }

    protected void onDraw(Canvas c) {
        c.rotate(-90);
        c.translate(-getHeight(), 0);

        super.onDraw(c);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isEnabled()) {
            return false;
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
                setProgress(getMax() - (int) (getMax() * event.getY() / getHeight()));
                onSizeChanged(getWidth(), getHeight(), 0, 0);
                break;

            case MotionEvent.ACTION_CANCEL:
                break;
        }
        return true;
    }
}

There, paste the code and save it. Now use it in your XML layout:

<android.widget.VerticalSeekBar
  android:id="@+id/seekBar1"
  android:layout_width="wrap_content"
  android:layout_height="200dp"
  />

Make sure to create a package android.widget and create VerticalSeekBar.java under this package

best way to get folder and file list in Javascript

In my project I use this function for getting huge amount of files. It's pretty fast (put require("FS") out to make it even faster):

var _getAllFilesFromFolder = function(dir) {

    var filesystem = require("fs");
    var results = [];

    filesystem.readdirSync(dir).forEach(function(file) {

        file = dir+'/'+file;
        var stat = filesystem.statSync(file);

        if (stat && stat.isDirectory()) {
            results = results.concat(_getAllFilesFromFolder(file))
        } else results.push(file);

    });

    return results;

};

usage is clear:

_getAllFilesFromFolder(__dirname + "folder");

How to use BeanUtils.copyProperties?

There are two BeanUtils.copyProperties(parameter1, parameter2) in Java.

One is

org.apache.commons.beanutils.BeanUtils.copyProperties(Object dest, Object orig)

Another is

org.springframework.beans.BeanUtils.copyProperties(Object source, Object target)

Pay attention to the opposite position of parameters.

How to generate Javadoc from command line

Oracle provides some simple examples:

http://docs.oracle.com/javase/8/docs/technotes/tools/windows/javadoc.html#CHDJBGFC

Assuming you are in ~/ and the java source tree is in ./saxon_source/net and you want to recurse through the whole source tree net is both a directory and the top package name.

mkdir saxon_docs
javadoc -d saxon_docs -sourcepath saxon_source -subpackages net

The opposite of Intersect()

This code enumerates each sequence only once and uses Select(x => x) to hide the result to get a clean Linq-style extension method. Since it uses HashSet<T> its runtime is O(n + m) if the hashes are well distributed. Duplicate elements in either list are omitted.

public static IEnumerable<T> SymmetricExcept<T>(this IEnumerable<T> seq1,
    IEnumerable<T> seq2)
{
    HashSet<T> hashSet = new HashSet<T>(seq1);
    hashSet.SymmetricExceptWith(seq2);
    return hashSet.Select(x => x);
}

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

Why does this AttributeError in python occur?

AttributeError is raised when attribute of the object is not available.

An attribute reference is a primary followed by a period and a name:

attributeref ::= primary "." identifier

To return a list of valid attributes for that object, use dir(), e.g.:

dir(scipy)

So probably you need to do simply: import scipy.sparse

Difference between using gradlew and gradle

gradlew is a wrapper(w - character) that uses gradle.

Under the hood gradlew performs three main things:

  • Download and install the correct gradle version
  • Parse the arguments
  • Call a gradle task

Using Gradle Wrapper we can distribute/share a project to everybody to use the same version and Gradle's functionality(compile, build, install...) even if it has not been installed.

To create a wrapper run:

gradle wrapper

This command generate:

gradle-wrapper.properties will contain the information about the Gradle distribution

*./ Is used on Unix to specify the current directory

remove inner shadow of text input

Add border: none or border: 0 to remove border at all, or border: 1px solid #ccc to make border thin and flat.

To remove ghost padding in Firefox, you can use ::-moz-focus-inner:

::-moz-focus-inner {
    border: 0;
    padding: 0;
}

See live demo.

AWS : The config profile (MyName) could not be found

In my case, I had the variable named "AWS_PROFILE" on Environment variables with an old value.

enter image description here

Using Docker-Compose, how to execute multiple commands

I ran into this while trying to get my jenkins container set up to build docker containers as the jenkins user.

I needed to touch the docker.sock file in the Dockerfile as i link it later on in the docker-compose file. Unless i touch'ed it first, it didn't yet exist. This worked for me.

Dockerfile:

USER root
RUN apt-get update && \
apt-get -y install apt-transport-https \
ca-certificates \
curl \
software-properties-common && \
curl -fsSL https://download.docker.com/linux/$(. /etc/os-release; 
echo "$ID")/gpg > /tmp/dkey; apt-key add /tmp/dkey && \
add-apt-repository \
"deb [arch=amd64] https://download.docker.com/linux/$(. /etc/os-release; echo "$ID") \
$(lsb_release -cs) \
stable" && \
apt-get update && \
apt-get -y install docker-ce
RUN groupmod -g 492 docker && \
usermod -aG docker jenkins  && \
touch /var/run/docker.sock && \
chmod 777 /var/run/docker.sock

USER Jenkins

docker-compose.yml:

version: '3.3'
services:
jenkins_pipeline:
    build: .
    ports:
      - "8083:8083"
      - "50083:50080"
    volumes:
        - /root/pipeline/jenkins/mount_point_home:/var/jenkins_home
        - /var/run/docker.sock:/var/run/docker.sock

creating batch script to unzip a file without additional zip tools

Here's my overview about built-in zi/unzip (compress/decompress) capabilities in windows - How can I compress (/ zip ) and uncompress (/ unzip ) files and folders with batch file without using any external tools?

To unzip file you can use this script :

zipjs.bat unzip -source C:\myDir\myZip.zip -destination C:\MyDir -keep yes -force no

#include errors detected in vscode

The error message "Please update your includePath" does not necessarily mean there is actually a problem with the includePath. The problem may be that VSCode is using the wrong compiler or wrong IntelliSense mode. I have written instructions in this answer on how to troubleshoot and align your VSCode C++ configuration with your compiler and project.

InvalidKeyException : Illegal Key Size - Java code throwing exception for encryption class - how to fix?

So the problem must be with your JCE Unlimited Strength installation.

Be sure you overwrite the local_policy.jar and US_export_policy.jar in both your JDK's jdk1.6.0_25\jre\lib\security\ and in your JRE's lib\security\ folder.

In my case I would place the new .jars in:

C:\Program Files\Java\jdk1.6.0_25\jre\lib\security

and

C:\Program Files\Java\jre6\lib\security


If you are running Java 8 and you encounter this issue. Below steps should help!

Go to your JRE installation (e.g - jre1.8.0_181\lib\security\policy\unlimited) copy local_policy.jar and replace it with 'local_policy.jar' in your JDK installation directory (e.g - jdk1.8.0_141\jre\lib\security).

UITableView - change section header color

Using UIAppearance you can change it for all headers in your application like this:

UITableViewHeaderFooterView.appearance().backgroundColor = theme.subViewBackgroundColor

Return value from exec(@sql)

declare @nReturn int = 0 EXEC @nReturn = Stored Procedures

How do I send a file as an email attachment using Linux command line?

I once wrote this function for ksh on Solaris (uses Perl for base64 encoding):

# usage: email_attachment to cc subject body attachment_filename
email_attachment() {
    to="$1"
    cc="$2"
    subject="$3"
    body="$4"
    filename="${5:-''}"
    boundary="_====_blah_====_$(date +%Y%m%d%H%M%S)_====_"
    {
        print -- "To: $to"
        print -- "Cc: $cc"
        print -- "Subject: $subject"
        print -- "Content-Type: multipart/mixed; boundary=\"$boundary\""
        print -- "Mime-Version: 1.0"
        print -- ""
        print -- "This is a multi-part message in MIME format."
        print -- ""
        print -- "--$boundary"
        print -- "Content-Type: text/plain; charset=ISO-8859-1"
        print -- ""
        print -- "$body"
        print -- ""
        if [[ -n "$filename" && -f "$filename" && -r "$filename" ]]; then
            print -- "--$boundary"
            print -- "Content-Transfer-Encoding: base64"
            print -- "Content-Type: application/octet-stream; name=$filename"
            print -- "Content-Disposition: attachment; filename=$filename"
            print -- ""
            print -- "$(perl -MMIME::Base64 -e 'open F, shift; @lines=<F>; close F; print MIME::Base64::encode(join(q{}, @lines))' $filename)"
            print -- ""
        fi
        print -- "--${boundary}--"
    } | /usr/lib/sendmail -oi -t
}

git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054

you need to increase the buffer size (it's due to the large repository size), so you have to increase it

git config http.postBuffer 524288000

Althought you must have an initializd repository, just porceed as the following

git init
git config http.postBuffer 524288000
git remote add origin <REPO URL>
git pull origin master
...

Eclipse error: R cannot be resolved to a variable

Try to delete the import line import com.your.package.name.app.R, then, any resource calls such as mView= (View) mView.findViewById(R.id.resource_name); will highlight the 'R' with an error, a 'Quick fix' will prompt you to import R, and there will be at least two options:

  • android.R
  • your.package.name.R

Select the R corresponding to your package name, and you should be good to go. Hope that helps.

Insert a string at a specific index

If anyone is looking for a way to insert text at multiple indices in a string, try this out:

String.prototype.insertTextAtIndices = function(text) {
    return this.replace(/./g, function(character, index) {
        return text[index] ? text[index] + character : character;
    });
};

For example, you can use this to insert <span> tags at certain offsets in a string:

var text = {
    6: "<span>",
    11: "</span>"
};

"Hello world!".insertTextAtIndices(text); // returns "Hello <span>world</span>!"

Running Windows batch file commands asynchronously

Use the START command:

start [programPath]

If the path to the program contains spaces remember to add quotes. In this case you also need to provide a title for the opening console window

start "[title]" "[program path]"

If you need to provide arguments append them at the end (outside the command quotes)

start "[title]" "[program path]" [list of command args]

Use the /b option to avoid opening a new console window (but in that case you cannot interrupt the application using CTRL-C

anaconda - path environment variable in windows

C:\Users\<Username>\AppData\Local\Continuum\anaconda2

For me this was the default installation directory on Windows 7. Found it via Rusy's answer

WAMP Server doesn't load localhost

Change the port 80 to port 8080 and restart all services and access like localhost:8080/

It will work fine.

Difference between return 1, return 0, return -1 and exit?

To indicate execution status.

status 0 means the program succeeded.

status different from 0 means the program exited due to error or anomaly.

return n; from your main entry function will terminate your process and report to the parent process (the one that executed your process) the result of your process. 0 means SUCCESS. Other codes usually indicates a failure and its meaning.

How to get all child inputs of a div element (jQuery)

var i = $("#panel input");

should work :-)

the > will only fetch direct children, no children's children
the : is for using pseudo-classes, eg. :hover, etc.

you can read about available css-selectors of pseudo-classes here: http://docs.jquery.com/DOM/Traversing/Selectors#CSS_Selectors

How to add text to an existing div with jquery

we can do it in more easy way like by adding a function on button and on click we call that function for append.

<div id="Content">
<button id="Add" onclick="append();">Add Text</button>
</div> 
<script type="text/javascript">
function append()
{
$('<p>Text</p>').appendTo('#Content');
}
</script>

"cannot resolve symbol R" in Android Studio

First solution

Rebuild your gradle or invalidate/restart your system.

Second solution

delete .gradle and .idea folder from your android project. So you can solve "R" problem

and also remove redline error occur without any reason you get.

How can I convert string to datetime with format specification in JavaScript?

No sophisticated date/time formatting routines exist in JavaScript.

You will have to use an external library for formatted date output, "JavaScript Date Format" from Flagrant Badassery looks very promising.

For the input conversion, several suggestions have been made already. :)

How to use HTTP GET in PowerShell?

Downloading Wget is not necessary; the .NET Framework has web client classes built in.

$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")

Scroll to the top of the page using JavaScript?

If you'd like to scroll to any element with an ID, try this:

$('a[href^="#"]').bind('click.smoothscroll',function (e) {
    e.preventDefault();
    var target = this.hash;
    $target = $(target);
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 700, 'swing', function () {
        window.location.hash = target;
    });
});``

How to make a movie out of images in python

I use the ffmpeg-python binding. You can find more information here.

import ffmpeg
(
    ffmpeg
    .input('/path/to/jpegs/*.jpg', pattern_type='glob', framerate=25)
    .output('movie.mp4')
    .run()
)

What is the difference between private and protected members of C++ classes?

private is preferred for member data. Members in C++ classes are private by default.

public is preferred for member functions, though it is a matter of opinion. At least some methods must be accessible. public is accessible to all. It is the most flexible option and least safe. Anybody can use them, and anybody can misuse them.

private is not accessible at all. Nobody can use them outside the class, and nobody can misuse them. Not even in derived classes.

protected is a compromise because it can be used in derived classes. When you derive from a class, you have a good understanding of the base class, and you are careful not to misuse these members.

MFC is a C++ wrapper for Windows API, it prefers public and protected. Classes generated by Visual Studio wizard have an ugly mix of protected, public, and private members. But there is some logic to MFC classes themselves.

Members such as SetWindowText are public because you often need to access these members.

Members such as OnLButtonDown, handle notifications received by the window. They should not be accessed, therefore they are protected. You can still access them in the derived class to override these functions.

Some members have to do threads and message loops, they should not be accessed or override, so they are declared as private

In C++ structures, members are public by default. Structures are usually used for data only, not methods, therefore public declaration is considered safe.

How to execute Ant build in command line

is it still actual?

As I can see you wrote <target depends="build-subprojects,build-project" name="build"/>, then you wrote <target name="build-subprojects"/> (it does nothing). Could it be a reason? Does this <echo message="${ant.project.name}: ${ant.file}"/> print appropriate message? If no then target is not running. Take a look at the next link http://www.sqaforums.com/showflat.php?Number=623277

Android Crop Center of Bitmap

While most of the above answers provide a way to do this, there is already a built-in way to accomplish this and it's 1 line of code (ThumbnailUtils.extractThumbnail())

int dimension = getSquareCropDimensionForBitmap(bitmap);
bitmap = ThumbnailUtils.extractThumbnail(bitmap, dimension, dimension);

...

//I added this method because people keep asking how 
//to calculate the dimensions of the bitmap...see comments below
public int getSquareCropDimensionForBitmap(Bitmap bitmap)
{
    //use the smallest dimension of the image to crop to
    return Math.min(bitmap.getWidth(), bitmap.getHeight());
}

If you want the bitmap object to be recycled, you can pass options that make it so:

bitmap = ThumbnailUtils.extractThumbnail(bitmap, dimension, dimension, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);

From: ThumbnailUtils Documentation

public static Bitmap extractThumbnail (Bitmap source, int width, int height)

Added in API level 8 Creates a centered bitmap of the desired size.

Parameters source original bitmap source width targeted width height targeted height

I was getting out of memory errors sometimes when using the accepted answer, and using ThumbnailUtils resolved those issues for me. Plus, this is much cleaner and more reusable.

JavaFX 2.1 TableView refresh items

Same problem here, i tried some solutions and the best for me is following:

In initialize-method of controller, create an empty observableList and set it to the table:

obsBericht = FXCollections.observableList(new ArrayList<Bericht>(0));
tblBericht.setItems(obsBericht);

In your update-method, just use the observableList, clear it and add the refreshed data:

obsBericht.clear();
obsBericht.addAll(FXCollections.observableList(DatabaseHelper.getBerichte()));
// tblBericht.setItems(obsBericht);

It's not necessary to set the items of the table again

Find a class somewhere inside dozens of JAR files?

Filename: searchForFiles.py

import os, zipfile, glob, sys

def main():
    searchFile = sys.argv[1] #class file to search for, sent from batch file below (optional, see second block of code below)
    listOfFilesInJar = []
    for file in glob.glob("*.jar"):
        archive = zipfile.ZipFile(file, 'r')
        for x in archive.namelist():
            if str(searchFile) in str(x):
                listOfFilesInJar.append(file)

    for something in listOfFilesInJar:
        print("location of "+str(searchFile)+": ",something)

if __name__ == "__main__":
    sys.exit(main())

You can easily run this by making a .bat file with the following text (replace "AddWorkflows.class" with the file you are searching for):

(File: CallSearchForFiles.bat)

@echo off
python -B -c "import searchForFiles;x=searchForFiles.main();" AddWorkflows.class
pause

You can double-click CallSearchForFiles.bat to run it, or call it from the command line "CallSearchForFiles.bat SearchFile.class"

Click to See Example Output

How can I disable editing cells in a WPF Datagrid?

The WPF DataGrid has an IsReadOnly property that you can set to True to ensure that users cannot edit your DataGrid's cells.

You can also set this value for individual columns in your DataGrid as needed.

Draw in Canvas by finger, Android

Regarding the beautiful code of Raghunandan above.

Many have asked how to "clear" the drawing. Here's how to do that:

public void clearDrawing()
    {
    Utils.Log("RaghunandanDraw, how to clear....");

    setDrawingCacheEnabled(false);
    // don't forget that one and the match below,
    // or you just keep getting a duplicate when you save.

    onSizeChanged(width, height, width, height);
    invalidate();

    setDrawingCacheEnabled(true);
    }

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
    {
    super.onSizeChanged(w, h, oldw, oldh);

    width = w;      // don't forget these
    height = h;

    mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    mCanvas = new Canvas(mBitmap);
    }

Many have asked how to "save" the drawing. Here's how to do that:

public DrawingView(Context c)
  {
  circlePaint.setStrokeJoin(Paint.Join.MITER);
  circlePaint.setStrokeWidth(4f); 
  etc...

  // in the class where you set up the view, add this:
  setDrawingCacheEnabled( true );
  }

public void saveDrawing()
  {
  Bitmap whatTheUserDrewBitmap = getDrawingCache();
  // don't forget to clear it (see above) or you just get duplicates

  // almost always you will want to reduce res from the very high screen res
  whatTheUserDrewBitmap =
         ThumbnailUtils.extractThumbnail(whatTheUserDrewBitmap, 256, 256);
  // NOTE that's an incredibly useful trick for cropping/resizing squares
  // while handling all memory problems etc
  // http://stackoverflow.com/a/17733530/294884

  // you can now save the bitmap to a file, or display it in an ImageView:
  ImageView testArea = ...
  testArea.setImageBitmap( whatTheUserDrewBitmap );

  // these days you often need a "byte array". for example,
  // to save to parse.com or other cloud services
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  whatTheUserDrewBitmap.compress(Bitmap.CompressFormat.PNG, 0, baos);
  byte[] yourByteArray;
  yourByteArray = baos.toByteArray();
  }

Hope it helps someone as this has helped me.

Get combobox value in Java swing

If the string is empty, comboBox.getSelectedItem().toString() will give a NullPointerException. So better to typecast by (String).

MySQL & Java - Get id of the last inserted value (JDBC)

Alternatively you can do:

Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();

ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
    risultato=rs.getString(1);
}

But use Sean Bright's answer instead for your scenario.

How to convert int[] into List<Integer> in Java?

If you are using java 8, we can use the stream API to convert it into a list.

List<Integer> list = Arrays.stream(arr)     // IntStream 
                                .boxed()        // Stream<Integer>
                                .collect(Collectors.toList());

You can also use the IntStream to convert as well.

List<Integer> list = IntStream.of(arr) // return Intstream
                                    .boxed()        // Stream<Integer>
                                    .collect(Collectors.toList());

There are other external library like guava and apache commons also available convert it.

cheers.

How to escape the % (percent) sign in C's printf?

Yup, use printf("hello%%"); and it's done.

pandas groupby sort descending order

This kind of operation is covered under hierarchical indexing. Check out the examples here

When you groupby, you're making new indices. If you also pass a list through .agg(). you'll get multiple columns. I was trying to figure this out and found this thread via google.

It turns out if you pass a tuple corresponding to the exact column you want sorted on.

Try this:

# generate toy data 
ex = pd.DataFrame(np.random.randint(1,10,size=(100,3)), columns=['features', 'AUC', 'recall'])

# pass a tuple corresponding to which specific col you want sorted. In this case, 'mean' or 'AUC' alone are not unique. 
ex.groupby('features').agg(['mean','std']).sort_values(('AUC', 'mean'))

This will output a df sorted by the AUC-mean column only.

Read file from aws s3 bucket using node fs

I prefer Buffer.from(data.Body).toString('utf8'). It supports encoding parameters. With other AWS services (ex. Kinesis Streams) someone may want to replace 'utf8' encoding with 'base64'.

new AWS.S3().getObject(
  { Bucket: this.awsBucketName, Key: keyName }, 
  function(err, data) {
    if (!err) {
      const body = Buffer.from(data.Body).toString('utf8');
      console.log(body);
    }
  }
);

Mac SQLite editor

You may like SQLPro for SQLite (previously SQLite Professional - App Store).

The app has a few neat features such as:

  • Auto-completion and syntax highlighting.
  • Versions Integration (rollback to previous versions).
  • Inline data filtering.
  • The ability to load sqlite extensions.
  • SQLite 2 Compatibility.
  • Exporting options to CSV, JSON, XML and MySQL.
  • Importing from CSV, JSON or XML.
  • Column reordering.
  • Full screen support.

SQLPro for SQLite overview screenshot

There is a seven day trial available via the website. If you purchase via our website, use the promo code STACK25 to save 25%.

Disclaimer: I'm the developer.

Spin or rotate an image on hover

Here is my code, this flips on hover and flips back off-hover.

CSS:

.flip-container {
  background: transparent;
  display: inline-block;
}

.flip-this {
  position: relative;
  width: 100%;
  height: 100%;
  transition: transform 0.6s;
  transform-style: preserve-3d;
}

.flip-container:hover .flip-this {
  transition: 0.9s;
  transform: rotateY(180deg);
}

HTML:

<div class="flip-container">
    <div class="flip-this">
        <img width="100" alt="Godot icon" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/6a/Godot_icon.svg/512px-Godot_icon.svg.png">
    </div>
</div>

Fiddle this

How to change identity column values programmatically?

If the column is not a PK you could always create a NEW column in the table with the incremented numbers, drop the original and then alter the new one to be the old.

curious as to why you might need to do this... most I've ever had to futz with Identity columns was to backfill numbers and I just ended up using DBCC CHECKIDENT ( tablename,RESEED,newnextnumber)

good luck!

What and where are the stack and heap?

(I have moved this answer from another question that was more or less a dupe of this one.)

The answer to your question is implementation specific and may vary across compilers and processor architectures. However, here is a simplified explanation.

  • Both the stack and the heap are memory areas allocated from the underlying operating system (often virtual memory that is mapped to physical memory on demand).
  • In a multi-threaded environment each thread will have its own completely independent stack but they will share the heap. Concurrent access has to be controlled on the heap and is not possible on the stack.

The heap

  • The heap contains a linked list of used and free blocks. New allocations on the heap (by new or malloc) are satisfied by creating a suitable block from one of the free blocks. This requires updating list of blocks on the heap. This meta information about the blocks on the heap is also stored on the heap often in a small area just in front of every block.
  • As the heap grows new blocks are often allocated from lower addresses towards higher addresses. Thus you can think of the heap as a heap of memory blocks that grows in size as memory is allocated. If the heap is too small for an allocation the size can often be increased by acquiring more memory from the underlying operating system.
  • Allocating and deallocating many small blocks may leave the heap in a state where there are a lot of small free blocks interspersed between the used blocks. A request to allocate a large block may fail because none of the free blocks are large enough to satisfy the allocation request even though the combined size of the free blocks may be large enough. This is called heap fragmentation.
  • When a used block that is adjacent to a free block is deallocated the new free block may be merged with the adjacent free block to create a larger free block effectively reducing the fragmentation of the heap.

The heap

The stack

  • The stack often works in close tandem with a special register on the CPU named the stack pointer. Initially the stack pointer points to the top of the stack (the highest address on the stack).
  • The CPU has special instructions for pushing values onto the stack and popping them back from the stack. Each push stores the value at the current location of the stack pointer and decreases the stack pointer. A pop retrieves the value pointed to by the stack pointer and then increases the stack pointer (don't be confused by the fact that adding a value to the stack decreases the stack pointer and removing a value increases it. Remember that the stack grows to the bottom). The values stored and retrieved are the values of the CPU registers.
  • When a function is called the CPU uses special instructions that push the current instruction pointer, i.e. the address of the code executing on the stack. The CPU then jumps to the function by setting the instruction pointer to the address of the function called. Later, when the function returns, the old instruction pointer is popped from the stack and execution resumes at the code just after the call to the function.
  • When a function is entered, the stack pointer is decreased to allocate more space on the stack for local (automatic) variables. If the function has one local 32 bit variable four bytes are set aside on the stack. When the function returns, the stack pointer is moved back to free the allocated area.
  • If a function has parameters, these are pushed onto the stack before the call to the function. The code in the function is then able to navigate up the stack from the current stack pointer to locate these values.
  • Nesting function calls work like a charm. Each new call will allocate function parameters, the return address and space for local variables and these activation records can be stacked for nested calls and will unwind in the correct way when the functions return.
  • As the stack is a limited block of memory, you can cause a stack overflow by calling too many nested functions and/or allocating too much space for local variables. Often the memory area used for the stack is set up in such a way that writing below the bottom (the lowest address) of the stack will trigger a trap or exception in the CPU. This exceptional condition can then be caught by the runtime and converted into some kind of stack overflow exception.

The stack

Can a function be allocated on the heap instead of a stack?

No, activation records for functions (i.e. local or automatic variables) are allocated on the stack that is used not only to store these variables, but also to keep track of nested function calls.

How the heap is managed is really up to the runtime environment. C uses malloc and C++ uses new, but many other languages have garbage collection.

However, the stack is a more low-level feature closely tied to the processor architecture. Growing the heap when there is not enough space isn't too hard since it can be implemented in the library call that handles the heap. However, growing the stack is often impossible as the stack overflow only is discovered when it is too late; and shutting down the thread of execution is the only viable option.

Difference between session affinity and sticky session?

This article clarifies the question for me and discusses other types of load balancer persistence.

Dave's Thoughts: Load balancer persistence (sticky sessions)

Which method performs better: .Any() vs .Count() > 0?

The exact details differ a bit in .NET Framework vs .NET Core, but it also somewhat depends on what you're doing: if you're using an ICollection or ICollection<T> type (such as with List<T>) there is a .Count property that's cheap to access, whereas other types might require enumeration.

TL;DR:

Use .Count > 0 if the property exists, and otherwise .Any().

Using .Count() > 0 is never the best option, and in some cases could be dramatically slower.

This applies to both .NET Framework and .NET Core.


Now we can dive into the details..

Lists and Collections

Let's start with a very common case: using List<T> (which is also ICollection<T>).

The .Count property is implemented as:

    private int _size;

    public int Count {
        get {
            Contract.Ensures(Contract.Result<int>() >= 0);
            return _size; 
        }
    }

What this is saying is _size is maintained by Add(),Remove() etc, and since it's just accessing a field this is an extremely cheap operation -- we don't need to iterate over values.

ICollection and ICollection<T> both have .Count and most types that implement them are likely to do so in a similar way.

Other IEnumerables

Any other IEnumerable types that aren't also ICollection require starting enumeration to determine if they're empty or not. The key factor affecting performance is if we end up enumerating a single item (ideal) or the entire collection (relatively expensive).

If the collection is actually causing I/O such as by reading from a database or disk, this could be a big performance hit.


.NET Framework .Any()

In .NET Framework (4.8), the Any() implementation is:

public static bool Any<TSource>(this IEnumerable<TSource> source) {
    if (source == null) throw Error.ArgumentNull("source");
    using (IEnumerator<TSource> e = source.GetEnumerator()) {
        if (e.MoveNext()) return true;
    }
    return false;
}

This means no matter what, it's going to get a new enumerator object and try iterating once. This is more expensive than calling the List<T>.Count property, but at least it's not iterating the entire list.

.NET Framework .Count()

In .NET Framework (4.8), the Count() implementation is (basically):

public static int Count<TSource>(this IEnumerable<TSource> source)
{
    ICollection<TSource> collection = source as ICollection<TSource>;
    if (collection != null)
    { 
        return collection.Count;
    }
    int num = 0;
    using (IEnumerator<TSource> enumerator = source.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            num = checked(num + 1);
        }
        return num;
    }
}

If available, ICollection.Count is used, but otherwise the collection is enumerated.


.NET Core .Any()

The LINQ Any() implementation in .NET Core is much smarter. You can see the complete source here but the relevant bits to this discussion:

    public static bool Any<TSource>(this IEnumerable<TSource> source)
    {
        //..snip..
        
        if (source is ICollection<TSource> collectionoft)
        {
            return collectionoft.Count != 0;
        }
        
        //..snip..

        using (IEnumerator<TSource> e = source.GetEnumerator())
        {
            return e.MoveNext();
        }
    }

Because a List<T> is an ICollection<T>, this will call the Count property (and though it calls another method, there's no extra allocations).

.NET Core .Count()

The .NET Core implementation (source) is basically the same as .NET Framework (see above), and so it will use ICollection.Count if available, and otherwise enumerates the collection.


Summary

.NET Framework

  • With ICollection:

    • .Count > 0 is best
    • .Count() > 0 is fine, but ultimately just calls ICollection.Count
    • .Any() is going to be slower, as it enumerates a single item
  • With non-ICollection (no .Count property)

    • .Any() is best, as it only enumerates a single item
    • .Count() > 0 is bad as it causes complete enumeration

.NET Core

  • .Count > 0 is best, if available (ICollection)
  • .Any() is fine, and will either do ICollection.Count > 0 or enumerate a single item
  • .Count() > 0 is bad as it causes complete enumeration

Titlecase all entries into a form_for text field

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base   before_save do |place|     place.city = place.city.downcase.titleize     place.country = place.country.downcase.titleize   end end 

You can also check out the Ruby on Rails guide for more info.


To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>   

This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

How to update the value stored in Dictionary in C#?

  1. update - modify existent only. To avoid side effect of indexer use:

    int val;
    if (dic.TryGetValue(key, out val))
    {
        // key exist
        dic[key] = val;
    }
    
  2. update or (add new if value doesn't exist in dic)

    dic[key] = val;
    

    for instance:

    d["Two"] = 2; // adds to dictionary because "two" not already present
    d["Two"] = 22; // updates dictionary because "two" is now present
    

How to set width to 100% in WPF

It is the container of the Grid that is imposing on its width. In this case, that's a ListBoxItem, which is left-aligned by default. You can set it to stretch as follows:

<ListBox>
    <!-- other XAML omitted, you just need to add the following bit -->
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

C/C++ macro string concatenation

You don't need that sort of solution for string literals, since they are concatenated at the language level, and it wouldn't work anyway because "s""1" isn't a valid preprocessor token.

[Edit: In response to the incorrect "Just for the record" comment below that unfortunately received several upvotes, I will reiterate the statement above and observe that the program fragment

#define PPCAT_NX(A, B) A ## B
PPCAT_NX("s", "1")

produces this error message from the preprocessing phase of gcc: error: pasting ""s"" and ""1"" does not give a valid preprocessing token

]

However, for general token pasting, try this:

/*
 * Concatenate preprocessor tokens A and B without expanding macro definitions
 * (however, if invoked from a macro, macro arguments are expanded).
 */
#define PPCAT_NX(A, B) A ## B

/*
 * Concatenate preprocessor tokens A and B after macro-expanding them.
 */
#define PPCAT(A, B) PPCAT_NX(A, B)

Then, e.g., both PPCAT_NX(s, 1) and PPCAT(s, 1) produce the identifier s1, unless s is defined as a macro, in which case PPCAT(s, 1) produces <macro value of s>1.

Continuing on the theme are these macros:

/*
 * Turn A into a string literal without expanding macro definitions
 * (however, if invoked from a macro, macro arguments are expanded).
 */
#define STRINGIZE_NX(A) #A

/*
 * Turn A into a string literal after macro-expanding it.
 */
#define STRINGIZE(A) STRINGIZE_NX(A)

Then,

#define T1 s
#define T2 1
STRINGIZE(PPCAT(T1, T2)) // produces "s1"

By contrast,

STRINGIZE(PPCAT_NX(T1, T2)) // produces "T1T2"
STRINGIZE_NX(PPCAT_NX(T1, T2)) // produces "PPCAT_NX(T1, T2)"

#define T1T2 visit the zoo
STRINGIZE(PPCAT_NX(T1, T2)) // produces "visit the zoo"
STRINGIZE_NX(PPCAT(T1, T2)) // produces "PPCAT(T1, T2)"

Writing to a TextBox from another thread?

Here is the what I have done to avoid CrossThreadException and writing to the textbox from another thread.

Here is my Button.Click function- I want to generate a random number of threads and then get their IDs by calling the getID() method and the TextBox value while being in that worker thread.

private void btnAppend_Click(object sender, EventArgs e) 
{
    Random n = new Random();

    for (int i = 0; i < n.Next(1,5); i++)
    {
        label2.Text = "UI Id" + ((Thread.CurrentThread.ManagedThreadId).ToString());
        Thread t = new Thread(getId);
        t.Start();
    }
}

Here is getId (workerThread) code:

public void getId()
{
    int id = Thread.CurrentThread.ManagedThreadId;
    //Note that, I have collected threadId just before calling this.Invoke
    //method else it would be same as of UI thread inside the below code block 
    this.Invoke((MethodInvoker)delegate ()
    {
        inpTxt.Text += "My id is" +"--"+id+Environment.NewLine; 
    });
}

How to display Base64 images in HTML?

You need to specify correct Content-type, Content-encoding and charset like

 data:image/jpeg;charset=utf-8;base64, 

according to the syntax of the data URI scheme:

 data:[<media type>][;charset=<character set>][;base64],<data>

Comparing two hashmaps for equal values and same key sets?

Simply use :

mapA.equals(mapB);

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings

Configure nginx with multiple locations with different root folders on subdomain

A little more elaborate example.

Setup: You have a website at example.com and you have a web app at example.com/webapp

...
server {
  listen 443 ssl;
  server_name example.com;

  root   /usr/share/nginx/html/website_dir;
  index  index.html index.htm;
  try_files $uri $uri/ /index.html;

  location /webapp/ {
    alias  /usr/share/nginx/html/webapp_dir/;
    index  index.html index.htm;
    try_files $uri $uri/ /webapp/index.html;
  }
}
...

I've named webapp_dir and website_dir on purpose. If you have matching names and folders you can use the root directive.

This setup works and is tested with Docker.

NB!!! Be careful with the slashes. Put them exactly as in the example.

Working with dictionaries/lists in R

You do not even need lists if your "number" values are all of the same mode. If I take Dirk Eddelbuettel's example:

> foo <- c(12, 22, 33)
> names(foo) <- c("tic", "tac", "toe")
> foo
tic tac toe
 12  22  33
> names(foo)
[1] "tic" "tac" "toe"

Lists are only required if your values are either of mixed mode (for example characters and numbers) or vectors.

For both lists and vectors, an individual element can be subsetted by name:

> foo["tac"]
tac 
 22 

Or for a list:

> foo[["tac"]]
[1] 22

JDBC ODBC Driver Connection

Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.

 import java.sql.*;  
 public class UserLogin
 {
     public static void main(String[] args)
     {
        try
        {    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            // C:\\databaseFileName.accdb" - location of your database 
           String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";

            // specify url, username, pasword - make sure these are valid 
            Connection conn = DriverManager.getConnection(url, "username", "password");

            System.out.println("Connection Succesfull");
         } 
         catch (Exception e) 
         {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());

          }
      }
  }

Why is "npm install" really slow?

I see from your screenshot that you are using WSL on Windows. And, with Windows, comes virus scanners, and virus scanning can make NPM install very slow!

Adding an exemption or disabling virus scanning during install can greatly speed it up, but potentially this is undesirable given the possibility of malicious NPM packages

One link suggests triple install time https://ikriv.com/blog/?p=2174

I have not profiled extensively myself though

env: node: No such file or directory in mac

Let's see, I sorted that on a different way. in my case I had as path something like ~/.local/bin which seems that it is not the way it wants.

Try to use the full path, like /Users/tobias/.local/bin, I mean, change the PATH variable from ~/.local/bin to /Users/tobias/.local/bin or $HOME/.local/bin .

Now it works.

What is the difference between Builder Design pattern and Factory Design pattern?

Factory: Used for creating an instance of an object where the dependencies of the object are entirely held by the factory. For the abstract factory pattern, there are often many concrete implementations of the same abstract factory. The right implementation of the factory is injected via dependency injection.

Builder: Used to build immutable objects, when the dependencies of the object to be instantiated are partly known in advance and partly provided by the client of the builder.

Logging request/response messages when using HttpClient

Network tracing also available for next objects (see article on msdn)

  • System.Net.Sockets Some public methods of the Socket, TcpListener, TcpClient, and Dns classes
  • System.Net Some public methods of the HttpWebRequest, HttpWebResponse, FtpWebRequest, and FtpWebResponse classes, and SSL debug information (invalid certificates, missing issuers list, and client certificate errors.)
  • System.Net.HttpListener Some public methods of the HttpListener, HttpListenerRequest, and HttpListenerResponse classes.
  • System.Net.Cache Some private and internal methods in System.Net.Cache.
  • System.Net.Http Some public methods of the HttpClient, DelegatingHandler, HttpClientHandler, HttpMessageHandler, MessageProcessingHandler, and WebRequestHandler classes.
  • System.Net.WebSockets.WebSocket Some public methods of the ClientWebSocket and WebSocket classes.

Put next lines of code to the configuration file

<configuration>  
  <system.diagnostics>  
    <sources>  
      <source name="System.Net" tracemode="includehex" maxdatasize="1024">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Cache">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Http">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Sockets">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.WebSockets">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
    </sources>  
    <switches>  
      <add name="System.Net" value="Verbose"/>  
      <add name="System.Net.Cache" value="Verbose"/>  
      <add name="System.Net.Http" value="Verbose"/>  
      <add name="System.Net.Sockets" value="Verbose"/>  
      <add name="System.Net.WebSockets" value="Verbose"/>  
    </switches>  
    <sharedListeners>  
      <add name="System.Net"  
        type="System.Diagnostics.TextWriterTraceListener"  
        initializeData="network.log"  
      />  
    </sharedListeners>  
    <trace autoflush="true"/>  
  </system.diagnostics>  
</configuration>  

TSQL DATETIME ISO 8601

You technically have two options when speaking of ISO dates.

In general, if you're filtering specifically on Date values alone OR looking to persist date in a neutral fashion. Microsoft recommends using the language neutral format of ymd or y-m-d. Which are both valid ISO formats.

Note that the form '2007-02-12' is considered language-neutral only for the data types DATE, DATETIME2, and DATETIMEOFFSET.

Because of this, your safest bet is to persist/filter based on the always netural ymd format.

The code:

select convert(char(10), getdate(), 126) -- ISO YYYY-MM-DD
select convert(char(8), getdate(), 112) -- ISO YYYYMMDD (safest)

How to Lock Android App's Orientation to Portrait in Phones and Landscape in Tablets?

Just Add:

android:screenOrientation="portrait"

in "AndroidManifest.xml" :

<activity
android:screenOrientation="portrait"
android:name=".MainActivity"
android:label="@string/app_name">
</activity>

Background color of text in SVG

Instead of using a <text> tag, the <foreignObject> tag can be used, which allows for XHTML content with CSS.