Programs & Examples On #Base tag

What are the recommendations for html <base> tag?

Drupal initially relied on the <base> tag, and later on took the decision to not use due to problems with HTTP crawlers & caches.

I generally don't like to post links. But this one is really worth sharing as it could benefit those looking for the details of a real-world experience with the <base> tag:

http://drupal.org/node/13148

Start an external application from a Google Chrome Extension?

Previously, you would do this through NPAPI plugins.

However, Google is now phasing out NPAPI for Chrome, so the preferred way to do this is using the native messaging API. The external application would have to register a native messaging host in order to exchange messages with your application.

Generating UML from C++ code?

I have used Rational Rose and Rational Rhapsody for reverse engineering large projects. I would prefer Rational Rhapsody for getting the UML class files for C++ !

Set the intervals of x-axis using r

You can use axis:

> axis(side=1, at=c(0:23))

That is, something like this:

plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()

Difference between clean, gradlew clean

You should use this one too:

./gradlew :app:dependencies (Mac and Linux) -With ./

gradlew :app:dependencies (Windows) -Without ./

The libs you are using internally using any other versions of google play service.If yes then remove or update those libs.

How to automatically generate N "distinct" colors?

For the sake of generations to come I add here the accepted answer in Python.

import numpy as np
import colorsys

def _get_colors(num_colors):
    colors=[]
    for i in np.arange(0., 360., 360. / num_colors):
        hue = i/360.
        lightness = (50 + np.random.rand() * 10)/100.
        saturation = (90 + np.random.rand() * 10)/100.
        colors.append(colorsys.hls_to_rgb(hue, lightness, saturation))
    return colors

How to check for a Null value in VB.NET

 If Short.TryParse(editTransactionRow.pay_id, New Short) Then editTransactionRow.pay_id.ToString()

SQL conditional SELECT

In SQL, you do it this way:

SELECT  CASE WHEN @selectField1 = 1 THEN Field1 ELSE NULL END,
        CASE WHEN @selectField2 = 1 THEN Field2 ELSE NULL END
FROM    Table

Relational model does not imply dynamic field count.

Instead, if you are not interested in a field value, you just select a NULL instead and parse it on the client.

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

In Swift 3, you can simply use CGPoint.zero or CGRect.zero in place of CGRectZero or CGPointZero.

However, in Swift 4, CGRect.zero and 'CGPoint.zero' will work

INSERT ... ON DUPLICATE KEY (do nothing)

Use ON DUPLICATE KEY UPDATE ...,
Negative : because the UPDATE uses resources for the second action.

Use INSERT IGNORE ...,
Negative : MySQL will not show any errors if something goes wrong, so you cannot handle the errors. Use it only if you don’t care about the query.

Check image width and height before upload with Javascript

Attach the function to the onchange method of the input type file /onchange="validateimg(this)"/

   function validateimg(ctrl) { 
        var fileUpload = ctrl;
        var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
        if (regex.test(fileUpload.value.toLowerCase())) {
            if (typeof (fileUpload.files) != "undefined") {
                var reader = new FileReader();
                reader.readAsDataURL(fileUpload.files[0]);
                reader.onload = function (e) {
                    var image = new Image();
                    image.src = e.target.result;
                    image.onload = function () {
                        var height = this.height;
                        var width = this.width;
                        if (height < 1100 || width < 750) {
                            alert("At least you can upload a 1100*750 photo size.");
                            return false;
                        }else{
                            alert("Uploaded image has valid Height and Width.");
                            return true;
                        }
                    };
                }
            } else {
                alert("This browser does not support HTML5.");
                return false;
            }
        } else {
            alert("Please select a valid Image file.");
            return false;
        }
    }

Displaying a Table in Django from Database

The easiest way is to use a for loop template tag.

Given the view:

def MyView(request):
    ...
    query_results = YourModel.objects.all()
    ...
    #return a response to your template and add query_results to the context

You can add a snippet like this your template...

<table>
    <tr>
        <th>Field 1</th>
        ...
        <th>Field N</th>
    </tr>
    {% for item in query_results %}
    <tr> 
        <td>{{ item.field1 }}</td>
        ...
        <td>{{ item.fieldN }}</td>
    </tr>
    {% endfor %}
</table>

This is all covered in Part 3 of the Django tutorial. And here's Part 1 if you need to start there.

How to get the selected item of a combo box to a string variable in c#

SelectedText = this.combobox.SelectionBoxItem.ToString();

Detect if a jQuery UI dialog box is open

jQuery dialog has an isOpen property that can be used to check if a jQuery dialog is open or not.

You can see example at this link: http://www.codegateway.com/2012/02/detect-if-jquery-dialog-box-is-open.html

Sum function in VBA

Function is not a property/method from range.

If you want to sum values then use the following:

Range("A1").Value = Application.Sum(Range(Cells(2, 1), Cells(3, 2)))

EDIT:

if you want the formula then use as follows:

Range("A1").Formula = "=SUM(" & Range(Cells(2, 1), Cells(3, 2)).Address(False, False) & ")"

'The two false after Adress is to define the address as relative (A2:B3).
'If you omit the parenthesis clause or write True instead, you can set the address
'as absolute ($A$2:$B$3).

In case you are allways going to use the same range address then you can use as Rory sugested:

Range("A1").Formula ="=Sum(A2:B3)"

PHP: Convert any string to UTF-8 without knowing the original character set, or at least try

public function convertToUtf8($text) {
    if(!$this->html)
        $this->html = cURL('http://'.$this->url, array('timeout' => 15));

    $html = $this->html;
    preg_match('/<meta.*?charset=(|\")(.*?)("|\")/i', $html, $matches);

    $charset = $matches[2];

    if($charset)
        return mb_convert_encoding($text, 'UTF-8', $charset);
    else
        return $text;
}

cURL default options:

curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

I tried something like this. It helped me. If found on meta charset info, I'm converting, otherwise doing nothing.

How to find out which processes are using swap space in Linux?

I suppose you could get a good guess by running top and looking for active processes using a lot of memory. Doing this programatically is harder---just look at the endless debates about the Linux OOM killer heuristics.

Swapping is a function of having more memory in active use than is installed, so it is usually hard to blame it on a single process. If it is an ongoing problem, the best solution is to install more memory, or make other systemic changes.

Bash: Echoing a echo command with a variable in bash

You just need to use single quotes:

$ echo "$TEST"
test
$ echo '$TEST'
$TEST

Inside single quotes special characters are not special any more, they are just normal characters.

Convert Json string to Json object in Swift 4

Using JSONSerialization always felt unSwifty and unwieldy, but it is even more so with the arrival of Codable in Swift 4. If you wield a [String:Any] in front of a simple struct it will ... hurt. Check out this in a Playground:

import Cocoa

let data = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]".data(using: .utf8)!

struct Form: Codable {
    let id: Int
    let name: String
    let description: String?

    private enum CodingKeys: String, CodingKey {
        case id = "form_id"
        case name = "form_name"
        case description = "form_desc"
    }
}

do {
    let f = try JSONDecoder().decode([Form].self, from: data)
    print(f)
    print(f[0])
} catch {
    print(error)
}

With minimal effort handling this will feel a whole lot more comfortable. And you are given a lot more information if your JSON does not parse properly.

How to bring a window to the front?

I tested your answers and only Stefan Reich's one worked for me. Although I couldn't manage to restore the window to its previous state (maximized/normal). I found this mutation better:

view.setState(java.awt.Frame.ICONIFIED);
view.setState(java.awt.Frame.NORMAL);

That is setState instead of setExtendedState.

Pass entire form as data in jQuery Ajax function

There's a function that does exactly this:

http://api.jquery.com/serialize/

var data = $('form').serialize();
$.post('url', data);

List of tables, db schema, dump etc using the Python sqlite3 API

The FASTEST way of doing this in python is using Pandas (version 0.16 and up).

Dump one table:

db = sqlite3.connect('database.db')
table = pd.read_sql_query("SELECT * from table_name", db)
table.to_csv(table_name + '.csv', index_label='index')

Dump all tables:

import sqlite3
import pandas as pd


def to_csv():
    db = sqlite3.connect('database.db')
    cursor = db.cursor()
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
    tables = cursor.fetchall()
    for table_name in tables:
        table_name = table_name[0]
        table = pd.read_sql_query("SELECT * from %s" % table_name, db)
        table.to_csv(table_name + '.csv', index_label='index')
    cursor.close()
    db.close()

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

As I mentioned in your other question:

The problem to do with that fact, that you invented your own non-standard attributes (which you shouldn't have done in the first place), and now new standardized attributes (or attributes in the process of being standardized) are colliding with them.

The proper solution is to completely remove your invented attributes and replace them with something sensible, for example classes (class="Montantetextfield fieldname-Montante required allow-decimal-values"), or store them in JavaScript:

var validationData = {
  "Montante": {fieldname: "Montante", required: true, allowDecimalValues: true}
}

If the proper solution isn't viable, you'll have to rename them. In that case you should use the prefix data-... because that is reserved by HTML5 for such purposes, and it's less likely to collide with something - but it still could, so you should seriously consider the first solution - even it is more work to change.

Gradle task - pass arguments to Java application

Since Gradle 4.9, the command line arguments can be passed with --args. For example, if you want to launch the application with command line arguments foo --bar, you can use

gradle run --args='foo --bar'

See Also Gradle Application Plugin

How to upgrade Gradle wrapper

How to use a dot "." to access members of dictionary?

The answer of @derek73 is very neat, but it cannot be pickled nor (deep)copied, and it returns None for missing keys. The code below fixes this.

Edit: I did not see the answer above that addresses the exact same point (upvoted). I'm leaving the answer here for reference.

class dotdict(dict):
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

    def __getattr__(self, name):
        try:
            return self[name]
        except KeyError:
            raise AttributeError(name)

char initial value in Java

Perhaps 0 or '\u0000' would do?

Warning about `$HTTP_RAW_POST_DATA` being deprecated

I got this error message when sending data from a html form (Post method). All I had to do was change the encoding in the form from "text/plain" to "application/x-www-form-urlencoded" or "multipart/form-data". The error message was very misleading.

Rename a dictionary key

I am using @wim 's answer above, with dict.pop() when renaming keys, but I found a gotcha. Cycling through the dict to change the keys, without separating the list of old keys completely from the dict instance, resulted in cycling new, changed keys into the loop, and missing some existing keys.

To start with, I did it this way:

for current_key in my_dict:
    new_key = current_key.replace(':','_')
    fixed_metadata[new_key] = fixed_metadata.pop(current_key)

I found that cycling through the dict in this way, the dictionary kept finding keys even when it shouldn't, i.e., the new keys, the ones I had changed! I needed to separate the instances completely from each other to (a) avoid finding my own changed keys in the for loop, and (b) find some keys that were not being found within the loop for some reason.

I am doing this now:

current_keys = list(my_dict.keys())
for current_key in current_keys:
    and so on...

Converting the my_dict.keys() to a list was necessary to get free of the reference to the changing dict. Just using my_dict.keys() kept me tied to the original instance, with the strange side effects.

Waiting for Target Device to Come Online

Fix for this issue is simple :

  • Go to SDK tools > SDK Tools
  • Check Android Emulator and click Apply

and sometimes you might see there's an update available next to it, you just need to let it finish the update

How do I download and save a file locally on iOS using objective C?

Sometime ago I implemented an easy to use "download manager" library: PTDownloadManager. You could give it a shot!

Find the nth occurrence of substring in a string

Here's a more Pythonic version of the straightforward iterative solution:

def find_nth(haystack, needle, n):
    start = haystack.find(needle)
    while start >= 0 and n > 1:
        start = haystack.find(needle, start+len(needle))
        n -= 1
    return start

Example:

>>> find_nth("foofoofoofoo", "foofoo", 2)
6

If you want to find the nth overlapping occurrence of needle, you can increment by 1 instead of len(needle), like this:

def find_nth_overlapping(haystack, needle, n):
    start = haystack.find(needle)
    while start >= 0 and n > 1:
        start = haystack.find(needle, start+1)
        n -= 1
    return start

Example:

>>> find_nth_overlapping("foofoofoofoo", "foofoo", 2)
3

This is easier to read than Mark's version, and it doesn't require the extra memory of the splitting version or importing regular expression module. It also adheres to a few of the rules in the Zen of python, unlike the various re approaches:

  1. Simple is better than complex.
  2. Flat is better than nested.
  3. Readability counts.

How do I clear/delete the current line in terminal?

or if your using vi mode, hit Esc followed by cc

to get back what you just erased, Esc and then p :)

How to tell if browser/tab is active

I would try to set a flag on the window.onfocus and window.onblur events.

The following snippet has been tested on Firefox, Safari and Chrome, open the console and move between tabs back and forth:

var isTabActive;

window.onfocus = function () { 
  isTabActive = true; 
}; 

window.onblur = function () { 
  isTabActive = false; 
}; 

// test
setInterval(function () { 
  console.log(window.isTabActive ? 'active' : 'inactive'); 
}, 1000);

Try it out here.

Explain __dict__ attribute

Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes. Quoting from the documentation for __dict__

A dictionary or other mapping object used to store an object's (writable) attributes.

Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:

def func():
    pass

func.temp = 1

print(func.__dict__)

class TempClass:
    a = 1
    def temp_function(self):
        pass

print(TempClass.__dict__)

will output

{'temp': 1}
{'__module__': '__main__', 
 'a': 1, 
 'temp_function': <function TempClass.temp_function at 0x10a3a2950>, 
 '__dict__': <attribute '__dict__' of 'TempClass' objects>, 
 '__weakref__': <attribute '__weakref__' of 'TempClass' objects>, 
 '__doc__': None}

How to center align the ActionBar title in Android?

Here is a complete Kotlin + androidx solution, building upon the answer from @Stanislas Heili. I hope it may be useful to others. It's for the case when you have an activity that hosts multiple fragments, with only one fragment active at the same time.

In your activity:

private lateinit var customTitle: AppCompatTextView

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // stuff here
    customTitle = createCustomTitleTextView()
    // other stuff here
}

private fun createCustomTitleTextView(): AppCompatTextView {
    val mTitleTextView = AppCompatTextView(this)
    TextViewCompat.setTextAppearance(mTitleTextView, R.style.your_style_or_null);

    val layoutParams = ActionBar.LayoutParams(
        ActionBar.LayoutParams.WRAP_CONTENT,
        ActionBar.LayoutParams.WRAP_CONTENT
    )
    layoutParams.gravity = Gravity.CENTER
    supportActionBar?.setCustomView(mTitleTextView, layoutParams)
    supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM

    return mTitleTextView
}

override fun setTitle(title: CharSequence?) {
    customTitle.text = title
}

override fun setTitle(titleId: Int) {
    customTitle.text = getString(titleId)
}

In your fragments:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    activity?.title = "some title for fragment"
}

Python : List of dict, if exists increment a dict value, if not append a new dict

This always works fine for me:

for url in list_of_urls:
    urls.setdefault(url, 0)
    urls[url] += 1

Choosing the default value of an Enum type without having to change values

Actually an enum's default is the first element in the enum whose value is 0.

So for example:

public enum Animals
{
    Cat,
    Dog,
    Pony = 0,
}
//its value will actually be Cat not Pony unless you assign a non zero value to Cat.
Animals animal;

What is the correct "-moz-appearance" value to hide dropdown arrow of a <select> element

While you can't yet get Firefox to remove the dropdown arrow (see MatTheCat's post), you can hide your "stylized" background image from showing in Firefox.

-moz-background-position: -9999px -9999px!important;

This will position it out of frame, leaving you with the default select box arrow – while keeping the stylized version in Webkit.

In Python, can I call the main() of an imported module?

Assuming you are trying to pass the command line arguments as well.

import sys
import myModule


def main():
    # this will just pass all of the system arguments as is
    myModule.main(*sys.argv)

    # all the argv but the script name
    myModule.main(*sys.argv[1:])

What, why or when it is better to choose cshtml vs aspx?

Razor is a view engine for ASP.NET MVC, and also a template engine. Razor code and ASP.NET inline code (code mixed with markup) both get compiled first and get turned into a temporary assembly before being executed. Thus, just like C# and VB.NET both compile to IL which makes them interchangable, Razor and Inline code are both interchangable.

Therefore, it's more a matter of style and interest. I'm more comfortable with razor, rather than ASP.NET inline code, that is, I prefer Razor (cshtml) pages to .aspx pages.

Imagine that you want to get a Human class, and render it. In cshtml files you write:

<div>Name is @Model.Name</div>

While in aspx files you write:

<div>Name is <%= Human.Name %></div>

As you can see, @ sign of razor makes mixing code and markup much easier.

Insert/Update/Delete with function in SQL Server

"Functions have only READ-ONLY Database Access" If DML operations would be allowed in functions then function would be prety similar to stored Procedure.

Curl Command to Repeat URL Request

If you want to add an interval before executing the cron the next time you can add a sleep

for i in {1..100}; do echo $i && curl "http://URL" >> /tmp/output.log && sleep 120; done

How do you set the Content-Type header for an HttpClient request?

If you don't mind a small library dependency, Flurl.Http [disclosure: I'm the author] makes this uber-simple. Its PostJsonAsync method takes care of both serializing the content and setting the content-type header, and ReceiveJson deserializes the response. If the accept header is required you'll need to set that yourself, but Flurl provides a pretty clean way to do that too:

using Flurl.Http;

var result = await "http://example.com/"
    .WithHeader("Accept", "application/json")
    .PostJsonAsync(new { ... })
    .ReceiveJson<TResult>();

Flurl uses HttpClient and Json.NET under the hood, and it's a PCL so it'll work on a variety of platforms.

PM> Install-Package Flurl.Http

How to SELECT WHERE NOT EXIST using LINQ?

        Dim result2 = From s In mySession.Query(Of CSucursal)()
                      Where (From c In mySession.Query(Of CCiudad)()
                             From cs In mySession.Query(Of CCiudadSucursal)()
                             Where cs.id_ciudad Is c
                             Where cs.id_sucursal Is s
                             Where c.id = IdCiudad
                             Where s.accion <> "E" AndAlso s.accion <> Nothing
                             Where cs.accion <> "E" AndAlso cs.accion <> Nothing
                             Select c.descripcion).Single() Is Nothing
                      Where s.accion <> "E" AndAlso s.accion <> Nothing
                      Select s.id, s.Descripcion

What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?

I am deploying VB6 IIS Applications to my remote dedicated server with 75 folders. The reason I was getting this error is the Default Document was not set on one of the folders, an oversight, so the URL hitting that folder did not know which page to server up, and thus threw the error mentioned in this thread.

How to return result of a SELECT inside a function in PostgreSQL?

Use RETURN QUERY:

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt   text   -- also visible as OUT parameter inside function
               , cnt   bigint
               , ratio bigint) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt
        , count(*) AS cnt                 -- column alias only visible inside
        , (count(*) * 100) / _max_tokens  -- I added brackets
   FROM  (
      SELECT t.txt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      LIMIT  _max_tokens
      ) t
   GROUP  BY t.txt
   ORDER  BY cnt DESC;                    -- potential ambiguity 
END
$func$  LANGUAGE plpgsql;

Call:

SELECT * FROM word_frequency(123);

Explanation:

  • It is much more practical to explicitly define the return type than simply declaring it as record. This way you don't have to provide a column definition list with every function call. RETURNS TABLE is one way to do that. There are others. Data types of OUT parameters have to match exactly what is returned by the query.

  • Choose names for OUT parameters carefully. They are visible in the function body almost anywhere. Table-qualify columns of the same name to avoid conflicts or unexpected results. I did that for all columns in my example.

    But note the potential naming conflict between the OUT parameter cnt and the column alias of the same name. In this particular case (RETURN QUERY SELECT ...) Postgres uses the column alias over the OUT parameter either way. This can be ambiguous in other contexts, though. There are various ways to avoid any confusion:

    1. Use the ordinal position of the item in the SELECT list: ORDER BY 2 DESC. Example:
    2. Repeat the expression ORDER BY count(*).
    3. (Not applicable here.) Set the configuration parameter plpgsql.variable_conflict or use the special command #variable_conflict error | use_variable | use_column in the function. See:
  • Don't use "text" or "count" as column names. Both are legal to use in Postgres, but "count" is a reserved word in standard SQL and a basic function name and "text" is a basic data type. Can lead to confusing errors. I use txt and cnt in my examples.

  • Added a missing ; and corrected a syntax error in the header. (_max_tokens int), not (int maxTokens) - type after name.

  • While working with integer division, it's better to multiply first and divide later, to minimize the rounding error. Even better: work with numeric (or a floating point type). See below.

Alternative

This is what I think your query should actually look like (calculating a relative share per token):

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt            text
               , abs_cnt        bigint
               , relative_share numeric) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt, t.cnt
        , round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2)  -- AS relative_share
   FROM  (
      SELECT t.txt, count(*) AS cnt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      GROUP  BY t.txt
      ORDER  BY cnt DESC
      LIMIT  _max_tokens
      ) t
   ORDER  BY t.cnt DESC;
END
$func$  LANGUAGE plpgsql;

The expression sum(t.cnt) OVER () is a window function. You could use a CTE instead of the subquery - pretty, but a subquery is typically cheaper in simple cases like this one.

A final explicit RETURN statement is not required (but allowed) when working with OUT parameters or RETURNS TABLE (which makes implicit use of OUT parameters).

round() with two parameters only works for numeric types. count() in the subquery produces a bigint result and a sum() over this bigint produces a numeric result, thus we deal with a numeric number automatically and everything just falls into place.

Can't find the 'libpq-fe.h header when trying to install pg gem

I could solve this in another way. I didn't find the library on my system. Thus I installed it using an app from PostgreSQL main website. In my case (OS X) I found the file under /Library/PostgreSQL/9.1/include/ once the installation was over. You may also have the file somewhere else depending on your system if you already have PostgreSQL installed.

Thanks to this link on how to add an additional path for gem installation, I could point the gem to the lib with this command:

export CONFIGURE_ARGS="with-pg-include=/Library/PostgreSQL/9.1/include/"
gem install pg

After that, it works, because it now knows where to find the missing library. Just replace the path with the right location for your libpq-fe.h

Regular expression for first and last name

The following expression will work on any language supported by UTF-16 and will ensure that there's a minimum of two components to the name (i.e. first + last), but will also allow any number of middle names.

/^(\S+ )+\S+$/u

At the time of this writing it seems none of the other answers meet all of that criteria. Even ^\p{L}{2,}$, which is the closest, falls short because it will also match "invisible" characters, such as U+FEFF (Zero Width No-Break Space).

How do you implement a Stack and a Queue in JavaScript?

Create a pair of classes that provide the various methods that each of these data structures has (push, pop, peek, etc). Now implement the methods. If you're familiar with the concepts behind stack/queue, this should be pretty straightforward. You can implement the stack with an array, and a queue with a linked list, although there are certainly other ways to go about it. Javascript will make this easy, because it is weakly typed, so you don't even have to worry about generic types, which you'd have to do if you were implementing it in Java or C#.

Re-enabling window.alert in Chrome

In Chrome Browser go to setting , clear browsing history and then reload the page

Convert pandas DataFrame into list of lists

There is a built in method which would be the fastest method also, calling tolist on the .values np array:

df.values.tolist()

[[0.0, 3.61, 380.0, 3.0],
 [1.0, 3.67, 660.0, 3.0],
 [1.0, 3.19, 640.0, 4.0],
 [0.0, 2.93, 520.0, 4.0]]

How to center a <p> element inside a <div> container?

To get left/right centering, then applying text-align: center to the div and margin: auto to the p.

For vertical positioning you should make sure you understand the different ways of doing so, this is a commonly asked problem: Vertical alignment of elements in a div

pypi UserWarning: Unknown distribution option: 'install_requires'

In conclusion:

distutils doesn't support install_requires or entry_points, setuptools does.

change from distutils.core import setup in setup.py to from setuptools import setup or refactor your setup.py to use only distutils features.

I came here because I hadn't realized entry_points was only a setuptools feature.

If you are here wanting to convert setuptools to distutils like me:

  1. remove install_requires from setup.py and just use requirements.txt with pip
  2. change entry_points to scripts (doc) and refactor any modules relying on entry_points to be full scripts with shebangs and an entry point.

How to convert a string to lower case in Bash?

Using GNU sed:

sed 's/.*/\L&/'

Example:

$ foo="Some STRIng";
$ foo=$(echo "$foo" | sed 's/.*/\L&/')
$ echo "$foo"
some string

MySQL case sensitive query

Whilst the listed answer is correct, may I suggest that if your column is to hold case sensitive strings you read the documentation and alter your table definition accordingly.

In my case this amounted to defining my column as:

`tag` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT ''

This is in my opinion preferential to adjusting your queries.

How to check whether a string contains a substring in JavaScript?

ECMAScript 6 introduced String.prototype.includes:

_x000D_
_x000D_
const string = "foo";_x000D_
const substring = "oo";_x000D_
_x000D_
console.log(string.includes(substring));
_x000D_
_x000D_
_x000D_

includes doesn’t have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found:

_x000D_
_x000D_
var string = "foo";_x000D_
var substring = "oo";_x000D_
_x000D_
console.log(string.indexOf(substring) !== -1);
_x000D_
_x000D_
_x000D_

How can I use xargs to copy files that have spaces and quotes in their names?

If you are using Bash, you can convert stdout to an array of lines by mapfile:

find . | grep "FooBar" | (mapfile -t; cp "${MAPFILE[@]}" ~/foobar)

The benefits are:

  • It's built-in, so it's faster.
  • Execute the command with all file names in one time, so it's faster.
  • You can append other arguments to the file names. For cp, you can also:

    find . -name '*FooBar*' -exec cp -t ~/foobar -- {} +
    

    however, some commands don't have such feature.

The disadvantages:

  • Maybe not scale well if there are too many file names. (The limit? I don't know, but I had tested with 10 MB list file which includes 10000+ file names with no problem, under Debian)

Well... who knows if Bash is available on OS X?

Reactjs setState() with a dynamic key name?

Your state with dictionary update some key without losing other value

state = 
{   
    name:"mjpatel"  
    parsedFilter:
    {
      page:2,
      perPage:4,
      totalPages: 50,
    }
}

Solution is below

 let { parsedFilter } = this.state
 this.setState({
      parsedFilter: {
        ...this.state.parsedFilter,
        page: 5
      }
  });

here update value for key "page" with value 5

Linux c++ error: undefined reference to 'dlopen'

this doesn't work:

gcc -ldl dlopentest.c

But this does:

gcc dlopentest.c -ldl

That's one annoying "feature" for sure

I was struggling with it when writing heredoc syntax and found some interesting facts. With CC=Clang, this works:

$CC -ldl -x c -o app.exe - << EOF
#include <dlfcn.h>
#include <stdio.h>
int main(void)
{
  if(dlopen("libc.so.6", RTLD_LAZY | RTLD_GLOBAL))
    printf("libc.so.6 loading succeeded\n");
  else
    printf("libc.so.6 loading failed\n");
  return 0;
}
EOF

./app.exe

as well as all of these:

  • $CC -ldl -x c -o app.exe - << EOF
  • $CC -x c -ldl -o app.exe - << EOF
  • $CC -x c -o app.exe -ldl - << EOF
  • $CC -x c -o app.exe - -ldl << EOF

However, with CC=gcc, only the last variant works; -ldl after - (the stdin argument symbol).

Convert textbox text to integer

If your SQL database allows Null values for that field try using int? value like that :

if (this.txtboxname.Text == "" || this.txtboxname.text == null)
     value = null;
else
     value = Convert.ToInt32(this.txtboxname.Text);

Take care that Convert.ToInt32 of a null value returns 0 !

Convert.ToInt32(null) returns 0

Font size relative to the user's screen resolution?

You might try this tool: http://fittextjs.com/

I haven't used this second tool, but it seems similar: https://github.com/zachleat/BigText

How can I create an observable with a delay

What you want is a timer:

// RxJS v6+
import { timer } from 'rxjs';

//emit [1, 2, 3] after 1 second.
const source = timer(1000).map(([1, 2, 3]);
//output: [1, 2, 3]
const subscribe = source.subscribe(val => console.log(val));

How to list npm user-installed packages?

I prefer tools with some friendly gui!

I used npm-gui which gives you list of local and global packages

The package is at https://www.npmjs.com/package/npm-gui and https://github.com/q-nick/npm-gui

//Once
npm install -g npm-gui

cd c:\your-prject-folder
npm-gui localhost:9000

At your browser http:\\localhost:9000

npm-gui

How to select rows for a specific date, ignoring time in SQL Server

Something like this:

select 
  * 
from sales 
where salesDate >= '11/11/2010' 
  AND salesDate < (Convert(datetime, '11/11/2010') + 1)

Decimal to Hexadecimal Converter in Java

Here's mine

public static String dec2Hex(int num)
{
    String hex = "";

    while (num != 0)
    {
        if (num % 16 < 10)
            hex = Integer.toString(num % 16) + hex;
        else
            hex = (char)((num % 16)+55) + hex;
        num = num / 16;
    }

    return hex;
}

LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

Syntactic sugar, makes it more obvious to the casual reader that the join isn't an inner one.

Populating spinner directly in the layout xml

In regards to the first comment: If you do this you will get an error(in Android Studio). This is in regards to it being out of the Android namespace. If you don't know how to fix this error, check the example out below. Hope this helps!

Example -Before :

<string-array name="roomSize">
    <item>Small(0-4)</item>
    <item>Medium(4-8)</item>
    <item>Large(9+)</item>
</string-array>

Example - After:

<string-array android:name="roomSize">
    <item>Small(0-4)</item>
    <item>Medium(4-8)</item>
    <item>Large(9+)</item>
</string-array>

Reversing an Array in Java

 public void swap(int[] arr,int a,int b)
 {
    int temp=arr[a];
    arr[a]=arr[b];
    arr[b]=temp;        
}
public int[] reverseArray(int[] arr){
    int size=arr.length-1;

    for(int i=0;i<size;i++){

        swap(arr,i,size--); 

    }

    return arr;
}

Get Time from Getdate()

Let's try this

select convert(varchar, getdate(), 108) 

Just try a few moment ago

Check if url contains string with JQuery

use href with indexof

<script type="text/javascript">
 $(document).ready(function () {
   if(window.location.href.indexOf("added-to-cart=555") > -1) {
   alert("your url contains the added-to-cart=555");
  }
});
</script>

How to position two divs horizontally within another div

This should do what you are looking for:

<html>
    <head>
        <style type="text/css">
            #header {
                text-align: center;
            }
            #wrapper {
                margin:0 auto;
                width:600px;
            }
            #submain {
                margin:0 auto;
                width:600px;
            }
            #sub-left {
                float:left;
                width:300px;
            }
            #sub-right {
                float:right;
                width:240px;
                text-align: right;
            }
        </style>

    </head>
    <body>
        <div id="wrapper">
            <div id="header"><h1>Head</h1></div>
            <div id="sub-main">
                <div id="sub-left">
                    Right
                </div>
                <div id="sub-right">
                    Left
                </div>
            </div>
        </div>
    </body>
</html>

And you can control the entire document with the wrapper class, or just the two columns with the sub-main class.

How to change the DataTable Column Name?

 dtTempColumn.Columns["EXCELCOLUMNS"].ColumnName = "COLUMN_NAME";                        
 dtTempColumn.AcceptChanges();

How to git ignore subfolders / subdirectories?

Besides putting the correct entries in your .gitignore file, if you're trying to ignore something already added to the repo, you have to do git rm -r /path/to/dir and commit that before you add the dir to your .gitignore file. Otherwise the only thing git will ignore is your ignore directive.

Using jQuery to test if an input has focus

Have you thought about using mouseOver and mouseOut to simulate this. Also look into mouseEnter and mouseLeave

implement addClass and removeClass functionality in angular2

If you want to due this in component.ts

HTML:

<button class="class1 class2" (click)="clicked($event)">Click me</button>

Component:

clicked(event) {
  event.target.classList.add('class3'); // To ADD
  event.target.classList.remove('class1'); // To Remove
  event.target.classList.contains('class2'); // To check
  event.target.classList.toggle('class4'); // To toggle
}

For more options, examples and browser compatibility visit this link.

Get current index from foreach loop

Use Enumerable.Select<TSource, TResult> Method (IEnumerable<TSource>, Func<TSource, Int32, TResult>)

list = list.Cast<object>().Select( (v, i) => new {Value= v, Index = i});

foreach(var row in list)
{
    bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row.Value)).IsChecked;
    row.Index ...
}

Combining two Series into a DataFrame in pandas

Not sure I fully understand your question, but is this what you want to do?

pd.DataFrame(data=dict(s1=s1, s2=s2), index=s1.index)

(index=s1.index is not even necessary here)

Using crontab to execute script every minute and another every 24 hours

every minute:

* * * * * /path/to/php /var/www/html/a.php

every 24hours (every midnight):

0 0 * * * /path/to/php /var/www/html/reset.php

See this reference for how crontab works: http://adminschoice.com/crontab-quick-reference, and this handy tool to build cron jobx: http://www.htmlbasix.com/crontab.shtml

Content Security Policy: The page's settings blocked the loading of a resource

I got around this by upgrading both the version of Angular that I was using (from v8 -> v9) and the version of TypeScript (from 3.5.3 -> latest).

How to convert integer to char in C?

A char in C is already a number (the character's ASCII code), no conversion required.

If you want to convert a digit to the corresponding character, you can simply add '0':

c = i +'0';

The '0' is a character in the ASCll table.

How can I limit the visible options in an HTML <select> dropdown?

A minor but important modification to existing solutions aiming at preserving framework styling (i.e. Bootstrap): replace this.size=0 with this.removeAttribute('size').

<select class="custom-select" onmousedown="if(this.options.length>5){this.size=5}"
    onchange='this.blur()' onblur="this.removeAttribute('size')">
    <option>option1</option>
    <option>option2</option>
    <option>option3</option>
    <option>option4</option>
    <option>option5</option>
    <option>option6</option>
    <option>option7</option>
</select>

SQL Server Profiler - How to filter trace to only display events from one database?

In SQL 2005, you first need to show the Database Name column in your trace. The easiest thing to do is to pick the Tuning template, which has that column added already.

Assuming you have the Tuning template selected, to filter:

  • Click the "Events Selection" tab
  • Click the "Column Filters" button
  • Check Show all Columns (Right Side Down)
  • Select "DatabaseName", click the plus next to Like in the right-hand pane, and type your database name.

I always save the trace to a table too so I can do LIKE queries on the trace data after the fact.

ERROR: Sonar server 'http://localhost:9000' can not be reached

For others who ran into this issue in a project that is not using a sonar-runners.property file, you may find (as I did) that you need to tweak your pom.xml file, adding a sonar.host.url property.

For example, I needed to add the following line under the 'properties' element:

<sonar.host.url>https://sonar.my-internal-company-domain.net</sonar.host.url>

Where the url points to our internal sonar deployment.

Converting a string to a date in a cell

Have you tried the =DateValue() function?

To include time value, just add the functions together:

=DateValue(A1)+TimeValue(A1)

Changing the cursor in WPF sometimes works, sometimes doesn't

Do you need the cursor to be a "wait" cursor only when it's over that particular page/usercontrol? If not, I'd suggest using Mouse.OverrideCursor:

Mouse.OverrideCursor = Cursors.Wait;
try
{
    // do stuff
}
finally
{
    Mouse.OverrideCursor = null;
}

This overrides the cursor for your application rather than just for a part of its UI, so the problem you're describing goes away.

How to get the cookie value in asp.net website

FormsAuthentication.Decrypt takes the actual value of the cookie, not the name of it. You can get the cookie value like

HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value;

and decrypt that.

Enter key pressed event handler

The KeyDown event only triggered at the standard TextBox or MaskedTextBox by "normal" input keys, not ENTER or TAB and so on.

One can get special keys like ENTER by overriding the IsInputKey method:

public class CustomTextBox : System.Windows.Forms.TextBox
{
    protected override bool IsInputKey(Keys keyData)
    {
        if (keyData == Keys.Return)
            return true;
        return base.IsInputKey(keyData);
    }
}

Then one can use the KeyDown event in the following way:

CustomTextBox ctb = new CustomTextBox();
ctb.KeyDown += new KeyEventHandler(tb_KeyDown);

private void tb_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
          //Enter key is down

          //Capture the text
          if (sender is TextBox)
          {
              TextBox txb = (TextBox)sender;
              MessageBox.Show(txb.Text);
          }
    }
}

Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await

In redux-saga, the equivalent of the above example would be

export function* loginSaga() {
  while(true) {
    const { user, pass } = yield take(LOGIN_REQUEST)
    try {
      let { data } = yield call(request.post, '/login', { user, pass });
      yield fork(loadUserData, data.uid);
      yield put({ type: LOGIN_SUCCESS, data });
    } catch(error) {
      yield put({ type: LOGIN_ERROR, error });
    }  
  }
}

export function* loadUserData(uid) {
  try {
    yield put({ type: USERDATA_REQUEST });
    let { data } = yield call(request.get, `/users/${uid}`);
    yield put({ type: USERDATA_SUCCESS, data });
  } catch(error) {
    yield put({ type: USERDATA_ERROR, error });
  }
}

The first thing to notice is that we're calling the api functions using the form yield call(func, ...args). call doesn't execute the effect, it just creates a plain object like {type: 'CALL', func, args}. The execution is delegated to the redux-saga middleware which takes care of executing the function and resuming the generator with its result.

The main advantage is that you can test the generator outside of Redux using simple equality checks

const iterator = loginSaga()

assert.deepEqual(iterator.next().value, take(LOGIN_REQUEST))

// resume the generator with some dummy action
const mockAction = {user: '...', pass: '...'}
assert.deepEqual(
  iterator.next(mockAction).value, 
  call(request.post, '/login', mockAction)
)

// simulate an error result
const mockError = 'invalid user/password'
assert.deepEqual(
  iterator.throw(mockError).value, 
  put({ type: LOGIN_ERROR, error: mockError })
)

Note we're mocking the api call result by simply injecting the mocked data into the next method of the iterator. Mocking data is way simpler than mocking functions.

The second thing to notice is the call to yield take(ACTION). Thunks are called by the action creator on each new action (e.g. LOGIN_REQUEST). i.e. actions are continually pushed to thunks, and thunks have no control on when to stop handling those actions.

In redux-saga, generators pull the next action. i.e. they have control when to listen for some action, and when to not. In the above example the flow instructions are placed inside a while(true) loop, so it'll listen for each incoming action, which somewhat mimics the thunk pushing behavior.

The pull approach allows implementing complex control flows. Suppose for example we want to add the following requirements

  • Handle LOGOUT user action

  • upon the first successful login, the server returns a token which expires in some delay stored in a expires_in field. We'll have to refresh the authorization in the background on each expires_in milliseconds

  • Take into account that when waiting for the result of api calls (either initial login or refresh) the user may logout in-between.

How would you implement that with thunks; while also providing full test coverage for the entire flow? Here is how it may look with Sagas:

function* authorize(credentials) {
  const token = yield call(api.authorize, credentials)
  yield put( login.success(token) )
  return token
}

function* authAndRefreshTokenOnExpiry(name, password) {
  let token = yield call(authorize, {name, password})
  while(true) {
    yield call(delay, token.expires_in)
    token = yield call(authorize, {token})
  }
}

function* watchAuth() {
  while(true) {
    try {
      const {name, password} = yield take(LOGIN_REQUEST)

      yield race([
        take(LOGOUT),
        call(authAndRefreshTokenOnExpiry, name, password)
      ])

      // user logged out, next while iteration will wait for the
      // next LOGIN_REQUEST action

    } catch(error) {
      yield put( login.error(error) )
    }
  }
}

In the above example, we're expressing our concurrency requirement using race. If take(LOGOUT) wins the race (i.e. user clicked on a Logout Button). The race will automatically cancel the authAndRefreshTokenOnExpiry background task. And if the authAndRefreshTokenOnExpiry was blocked in middle of a call(authorize, {token}) call it'll also be cancelled. Cancellation propagates downward automatically.

You can find a runnable demo of the above flow

Find control by name from Windows Forms controls

TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";

If Controls.Find is not found "textBox1" => error. You must add code.

If(tbx != null)

Edit:

TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
If(tbx != null)
   tbx.Text = "found!";

How do you Make A Repeat-Until Loop in C++?

do
{
  //  whatever
} while ( !condition );

Secure random token in Node.js

Simple function that gets you a token that is URL safe and has base64 encoding! It's a combination of 2 answers from above.

const randomToken = () => {
    crypto.randomBytes(64).toString('base64').replace(/\//g,'_').replace(/\+/g,'-');
}

Connecting to Microsoft SQL server using Python

Minor addition to what has been said before. You likely want to return a dataframe. This would be done as

import pypyodbc 
import pandas as pd

cnxn = pypyodbc.connect("Driver={SQL Server Native Client 11.0};"
                        "Server=server_name;"
                        "Database=db_name;"
                        "uid=User;pwd=password")
df = pd.read_sql_query('select * from table', cnxn)

Python: get key of index in dictionary

Python dictionaries have a key and a value, what you are asking for is what key(s) point to a given value.

You can only do this in a loop:

[k for (k, v) in i.iteritems() if v == 0]

Note that there can be more than one key per value in a dict; {'a': 0, 'b': 0} is perfectly legal.

If you want ordering you either need to use a list or a OrderedDict instance instead:

items = ['a', 'b', 'c']
items.index('a') # gives 0
items[0]         # gives 'a'

Determine the path of the executing BASH script

echo Running from `dirname $0`

not:first-child selector

As I used ul:not(:first-child) is a perfect solution.

div ul:not(:first-child) {
    background-color: #900;
}

Why is this a perfect because by using ul:not(:first-child), we can apply CSS on inner elements. Like li, img, span, a tags etc.

But when used others solutions:

div ul + ul {
  background-color: #900;
}

and

div li~li {
    color: red;
}

and

ul:not(:first-of-type) {}

and

div ul:nth-child(n+2) {
    background-color: #900;
}

These restrict only ul level CSS. Suppose we cannot apply CSS on li as `div ul + ul li'.

For inner level elements the first Solution works perfectly.

div ul:not(:first-child) li{
        background-color: #900;
    }

and so on ...

PHP preg_replace special characters

do this in two steps:

  1. replace not letter characters with this regex:

    [\/\&%#\$]

  2. replace quotes with this regex:

    [\"\']

and use preg_replace:

$stringWithoutNonLetterCharacters = preg_replace("/[\/\&%#\$]/", "_", $yourString);
$stringWithQuotesReplacedWithSpaces = preg_replace("/[\"\']/", " ", $stringWithoutNonLetterCharacters);

How do I combine two lists into a dictionary in Python?

If there are duplicate keys in the first list that map to different values in the second list, like a 1-to-many relationship, but you need the values to be combined or added or something instead of updating, you can do this:

i = iter(["a", "a", "b", "c", "b"])
j = iter([1,2,3,4,5])
k = list(zip(i, j))
for (x,y) in k:
    if x in d:
        d[x] = d[x] + y #or whatever your function needs to be to combine them
    else:
        d[x] = y

In that example, d == {'a': 3, 'c': 4, 'b': 8}

WiX tricks and tips

  1. Keep variables in a separate wxi include file. Enables re-use, variables are faster to find and (if needed) allows for easier manipulation by an external tool.

  2. Define Platform variables for x86 and x64 builds

    <!-- Product name as you want it to appear in Add/Remove Programs-->
    <?if $(var.Platform) = x64 ?>
      <?define ProductName = "Product Name (64 bit)" ?>
      <?define Win64 = "yes" ?>
      <?define PlatformProgramFilesFolder = "ProgramFiles64Folder" ?>
    <?else ?>
      <?define ProductName = "Product Name" ?>
      <?define Win64 = "no" ?>
      <?define PlatformProgramFilesFolder = "ProgramFilesFolder" ?>
    <?endif ?>
    
  3. Store the installation location in the registry, enabling upgrades to find the correct location. For example, if a user sets custom install directory.

     <Property Id="INSTALLLOCATION">
        <RegistrySearch Id="RegistrySearch" Type="raw" Root="HKLM" Win64="$(var.Win64)"
                  Key="Software\Company\Product" Name="InstallLocation" />
     </Property>
    

    Note: WiX guru Rob Mensching has posted an excellent blog entry which goes into more detail and fixes an edge case when properties are set from the command line.

    Examples using 1. 2. and 3.

    <?include $(sys.CURRENTDIR)\Config.wxi?>
    <Product ... >
      <Package InstallerVersion="200" InstallPrivileges="elevated"
               InstallScope="perMachine" Platform="$(var.Platform)"
               Compressed="yes" Description="$(var.ProductName)" />
    

    and

    <Directory Id="TARGETDIR" Name="SourceDir">
      <Directory Id="$(var.PlatformProgramFilesFolder)">
        <Directory Id="INSTALLLOCATION" Name="$(var.InstallName)">
    
  4. The simplest approach is always do major upgrades, since it allows both new installs and upgrades in the single MSI. UpgradeCode is fixed to a unique Guid and will never change, unless we don't want to upgrade existing product.

    Note: In WiX 3.5 there is a new MajorUpgrade element which makes life even easier!

  5. Creating an icon in Add/Remove Programs

    <Icon Id="Company.ico" SourceFile="..\Tools\Company\Images\Company.ico" />
    <Property Id="ARPPRODUCTICON" Value="Company.ico" />
    <Property Id="ARPHELPLINK" Value="http://www.example.com/" />
    
  6. On release builds we version our installers, copying the msi file to a deployment directory. An example of this using a wixproj target called from AfterBuild target:

    <Target Name="CopyToDeploy" Condition="'$(Configuration)' == 'Release'">
      <!-- Note we append AssemblyFileVersion, changing MSI file name only works with Major Upgrades -->
      <Copy SourceFiles="$(OutputPath)$(OutputName).msi" 
            DestinationFiles="..\Deploy\Setup\$(OutputName) $(AssemblyFileVersion)_$(Platform).msi" />
    </Target>
    
  7. Use heat to harvest files with wildcard (*) Guid. Useful if you want to reuse WXS files across multiple projects (see my answer on multiple versions of the same product). For example, this batch file automatically harvests RoboHelp output.

    @echo off  
    robocopy ..\WebHelp "%TEMP%\WebHelpTemp\WebHelp" /E /NP /PURGE /XD .svn  
    "%WIX%bin\heat" dir "%TEMP%\WebHelp" -nologo -sfrag -suid -ag -srd -dir WebHelp -out WebHelp.wxs -cg WebHelpComponent -dr INSTALLLOCATION -var var.WebDeploySourceDir 
    

    There's a bit going on, robocopy is stripping out Subversion working copy metadata before harvesting; the -dr root directory reference is set to our installation location rather than default TARGETDIR; -var is used to create a variable to specify the source directory (web deployment output).

  8. Easy way to include the product version in the welcome dialog title by using Strings.wxl for localization. (Credit: saschabeaumont. Added as this great tip is hidden in a comment)

    <WixLocalization Culture="en-US" xmlns="http://schemas.microsoft.com/wix/2006/localization">
        <String Id="WelcomeDlgTitle">{\WixUI_Font_Bigger}Welcome to the [ProductName] [ProductVersion] Setup Wizard</String>
    </WixLocalization>
    
  9. Save yourself some pain and follow Wim Coehen's advice of one component per file. This also allows you to leave out (or wild-card *) the component GUID.

  10. Rob Mensching has a neat way to quickly track down problems in MSI log files by searching for value 3. Note the comments regarding internationalization.

  11. When adding conditional features, it's more intuitive to set the default feature level to 0 (disabled) and then set the condition level to your desired value. If you set the default feature level >= 1, the condition level has to be 0 to disable it, meaning the condition logic has to be the opposite to what you'd expect, which can be confusing :)

    <Feature Id="NewInstallFeature" Level="0" Description="New installation feature" Absent="allow">
      <Condition Level="1">NOT UPGRADEFOUND</Condition>
    </Feature>
    <Feature Id="UpgradeFeature" Level="0" Description="Upgrade feature" Absent="allow">
      <Condition Level="1">UPGRADEFOUND</Condition>
    </Feature>
    

How to sort in mongoose?

Starting from 4.x the sort methods have been changed. If you are using >4.x. Try using any of the following.

Post.find({}).sort('-date').exec(function(err, docs) { ... });
Post.find({}).sort({date: -1}).exec(function(err, docs) { ... });
Post.find({}).sort({date: 'desc'}).exec(function(err, docs) { ... });
Post.find({}).sort({date: 'descending'}).exec(function(err, docs) { ... });
Post.find({}).sort([['date', -1]]).exec(function(err, docs) { ... });
Post.find({}, null, {sort: '-date'}, function(err, docs) { ... });
Post.find({}, null, {sort: {date: -1}}, function(err, docs) { ... });

Changing Tint / Background color of UITabBar

Following is the perfect solution for this. This works fine with me for iOS5 and iOS4.

//---- For providing background image to tabbar
UITabBar *tabBar = [tabBarController tabBar]; 

if ([tabBar respondsToSelector:@selector(setBackgroundImage:)]) {
    // ios 5 code here
    [tabBar setBackgroundImage:[UIImage imageNamed:@"image.png"]];
} 
else {
    // ios 4 code here
    CGRect frame = CGRectMake(0, 0, 480, 49);
    UIView *tabbg_view = [[UIView alloc] initWithFrame:frame];
    UIImage *tabbag_image = [UIImage imageNamed:@"image.png"];
    UIColor *tabbg_color = [[UIColor alloc] initWithPatternImage:tabbag_image];
    tabbg_view.backgroundColor = tabbg_color;
    [tabBar insertSubview:tabbg_view atIndex:0];
}

How to load images dynamically (or lazily) when users scrolls them into view

(Edit: replaced broken links with archived copies)

Dave Artz of AOL gave a great talk on optimization at jQuery Conference Boston last year. AOL uses a tool called Sonar for on-demand loading based on scroll position. Check the code for the particulars of how it compares scrollTop (and others) to the element offset to detect if part or all of the element is visible.

jQuery Sonar

Dave talks about Sonar in these slides. Sonar starts on slide 46, while the overall "load on demand" discussion starts on slide 33.

100% width background image with an 'auto' height

Add the css:

   html,body{
        height:100%;
        }
    .bg-img {
        background: url(image.jpg) no-repeat center top; 
        background-size: cover; 
        height:100%;     
    }

And html is:

<div class="bg-mg"></div>

CSS: stretching background image to 100% width and height of screen?

Unable to find the requested .Net Framework Data Provider in Visual Studio 2010 Professional

i had the same problem in visual studio 2019 and it resolved by searching in the searchbar inside visual studio: manage NuGet packages > oracle.ManagedDataAccess (first result) install it. and then it should works!

How do I search an SQL Server database for a string?

This will search every column of every table in a specific database. Create the stored procedure on the database that you want to search in.

The Ten Most Asked SQL Server Questions And Their Answers:

CREATE PROCEDURE FindMyData_String
    @DataToFind NVARCHAR(4000),
    @ExactMatch BIT = 0
AS
SET NOCOUNT ON

DECLARE @Temp TABLE(RowId INT IDENTITY(1,1), SchemaName sysname, TableName sysname, ColumnName SysName, DataType VARCHAR(100), DataFound BIT)

    INSERT  INTO @Temp(TableName,SchemaName, ColumnName, DataType)
    SELECT  C.Table_Name,C.TABLE_SCHEMA, C.Column_Name, C.Data_Type
    FROM    Information_Schema.Columns AS C
            INNER Join Information_Schema.Tables AS T
                ON C.Table_Name = T.Table_Name
        AND C.TABLE_SCHEMA = T.TABLE_SCHEMA
    WHERE   Table_Type = 'Base Table'
            And Data_Type In ('ntext','text','nvarchar','nchar','varchar','char')


DECLARE @i INT
DECLARE @MAX INT
DECLARE @TableName sysname
DECLARE @ColumnName sysname
DECLARE @SchemaName sysname
DECLARE @SQL NVARCHAR(4000)
DECLARE @PARAMETERS NVARCHAR(4000)
DECLARE @DataExists BIT
DECLARE @SQLTemplate NVARCHAR(4000)

SELECT  @SQLTemplate = CASE WHEN @ExactMatch = 1
                            THEN 'If Exists(Select *
                                          From   ReplaceTableName
                                          Where  Convert(nVarChar(4000), [ReplaceColumnName])
                                                       = ''' + @DataToFind + '''
                                          )
                                     Set @DataExists = 1
                                 Else
                                     Set @DataExists = 0'
                            ELSE 'If Exists(Select *
                                          From   ReplaceTableName
                                          Where  Convert(nVarChar(4000), [ReplaceColumnName])
                                                       Like ''%' + @DataToFind + '%''
                                          )
                                     Set @DataExists = 1
                                 Else
                                     Set @DataExists = 0'
                            END,
        @PARAMETERS = '@DataExists Bit OUTPUT',
        @i = 1

SELECT @i = 1, @MAX = MAX(RowId)
FROM   @Temp

WHILE @i <= @MAX
    BEGIN
        SELECT  @SQL = REPLACE(REPLACE(@SQLTemplate, 'ReplaceTableName', QUOTENAME(SchemaName) + '.' + QUOTENAME(TableName)), 'ReplaceColumnName', ColumnName)
        FROM    @Temp
        WHERE   RowId = @i


        PRINT @SQL
        EXEC SP_EXECUTESQL @SQL, @PARAMETERS, @DataExists = @DataExists OUTPUT

        IF @DataExists =1
            UPDATE @Temp SET DataFound = 1 WHERE RowId = @i

        SET @i = @i + 1
    END

SELECT  SchemaName,TableName, ColumnName
FROM    @Temp
WHERE   DataFound = 1
GO

To run it, just do this:

exec FindMyData_string 'google', 0

It works amazingly well!!!

How do I force detach Screen from another SSH session?

try with screen -d -r or screen -D -RR

Build .so file from .c file using gcc command line

To generate a shared library you need first to compile your C code with the -fPIC (position independent code) flag.

gcc -c -fPIC hello.c -o hello.o

This will generate an object file (.o), now you take it and create the .so file:

gcc hello.o -shared -o libhello.so

EDIT: Suggestions from the comments:

You can use

gcc -shared -o libhello.so -fPIC hello.c

to do it in one step. – Jonathan Leffler

I also suggest to add -Wall to get all warnings, and -g to get debugging information, to your gcc commands. – Basile Starynkevitch

Lint: How to ignore "<key> is not translated in <language>" errors?

In addition,

Not project dependent properities, Eclipse Preferences.
In Mac, Eclipse > Preferences

enter image description here

The point of test %eax %eax

You are right, that test "and"s the two operands. But the result is discarded, the only thing that stays, and thats the important part, are the flags. They are set and thats the reason why the test instruction is used (and exist).

JE jumps not when equal (it has the meaning when the instruction before was a comparison), what it really does, it jumps when the ZF flag is set. And as it is one of the flags that is set by test, this instruction sequence (test x,x; je...) has the meaning that it is jumped when x is 0.

For questions like this (and for more details) I can just recommend a book about x86 instruction, e.g. even when it is really big, the Intel documentation is very good and precise.

addEventListener, "change" and option selection

The problem is that you used the select option, this is where you went wrong. Select signifies that a textbox or textArea has a focus. What you need to do is use change. "Fires when a new choice is made in a select element", also used like blur when moving away from a textbox or textArea.

function start(){
      document.getElementById("activitySelector").addEventListener("change", addActivityItem, false);
      }

function addActivityItem(){
      //option is selected
      alert("yeah");
}

window.addEventListener("load", start, false);

Convert UTC dates to local time in PHP

Here I am sharing the script, convert UTC timestamp to Indian timestamp:-

    // create a $utc object with the UTC timezone
    $IST = new DateTime('2016-12-12 12:12:12', new DateTimeZone('UTC'));

    // change the timezone of the object without changing it's time
    $IST->setTimezone(new DateTimeZone('Asia/Kolkata'));

    // format the datetime
   echo $IST->format('Y-m-d H:i:s T');

swift How to remove optional String Character

You need to unwrap the optional before you try to use it via string interpolation. The safest way to do that is via optional binding:

if let color = colorChoiceSegmentedControl.titleForSegmentAtIndex(colorChoiceSegmentedControl.selectedSegmentIndex) {
    println(color) // "Red"

    let imageURLString = "http://hahaha.com/ha.php?color=\(color)"
    println(imageURLString) // http://hahaha.com/ha.php?color=Red
}

VBA Macro On Timer style to run code every set number of seconds, i.e. 120 seconds

When the workbook first opens, execute this code:

alertTime = Now + TimeValue("00:02:00")
Application.OnTime alertTime, "EventMacro"

Then just have a macro in the workbook called "EventMacro" that will repeat it.

Public Sub EventMacro()
    '... Execute your actions here'
    alertTime = Now + TimeValue("00:02:00")
    Application.OnTime alertTime, "EventMacro"
End Sub

What certificates are trusted in truststore?

Trust store generally (actually should only contain root CAs but this rule is violated in general) contains the certificates that of the root CAs (public CAs or private CAs). You can verify the list of certs in trust store using

keytool -list -v -keystore truststore.jks

Create an array or List of all dates between two dates

I know this is an old post but try using an extension method:

    public static IEnumerable<DateTime> Range(this DateTime startDate, DateTime endDate)
    {
        return Enumerable.Range(0, (endDate - startDate).Days + 1).Select(d => startDate.AddDays(d));
    }

and use it like this

    var dates = new DateTime(2000, 1, 1).Range(new DateTime(2000, 1, 31));

Feel free to choose your own dates, you don't have to restrict yourself to January 2000.

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

ETag vs Header Expires

One additional thing I would like to mention that some of the answers may have missed is the downside to having both ETags and Expires/Cache-control in your headers.

Depending on your needs it may just add extra bytes in your headers which may increase packets which means more TCP overhead. Again, you should see if the overhead of having both things in your headers is necessary or will it just add extra weight in your requests which reduces performance.

You can read more about it on this excellent blog post by Kyle Simpson: http://calendar.perfplanet.com/2010/bloated-request-response-headers/

writing integer values to a file using out.write()

write() only takes a single string argument, so you could do this:

outf.write(str(num))

or

outf.write('{}'.format(num))  # more "modern"
outf.write('%d' % num)        # deprecated mostly

Also note that write will not append a newline to your output so if you need it you'll have to supply it yourself.

Aside:

Using string formatting would give you more control over your output, so for instance you could write (both of these are equivalent):

num = 7
outf.write('{:03d}\n'.format(num))

num = 12
outf.write('%03d\n' % num)          

to get three spaces, with leading zeros for your integer value followed by a newline:

007
012

format() will be around for a long while, so it's worth learning/knowing.

Member '<method>' cannot be accessed with an instance reference

This causes the error:

MyClass aCoolObj = new MyClass();
aCoolObj.MyCoolStaticMethod();

This is the fix:

MyClass.MyCoolStaticMethod();

Explanation:

You can't call a static method from an instance of an object. The whole point of static methods is to not be tied to instances of objects, but instead to persist through all instances of that object, and/or to be used without any instances of the object.

Using If/Else on a data frame

Try this

frame$twohouses <- ifelse(frame$data>1, 2, 1)
 frame
   data twohouses
1     0         1
2     1         1
3     2         2
4     3         2
5     4         2
6     2         2
7     3         2
8     1         1
9     4         2
10    3         2
11    2         2
12    4         2
13    0         1
14    1         1
15    2         2
16    0         1
17    2         2
18    1         1
19    2         2
20    0         1
21    4         2

convert htaccess to nginx

Rewrite rules are pretty much written the same way with nginx: http://wiki.nginx.org/HttpRewriteModule#rewrite

Which rules are causing you trouble? I could help you translate those!

How to zip a file using cmd line?

If you are using Ubuntu Linux:

  1. Install zip

    sudo apt-get install zip
    
  2. Zip your folder:

    zip -r {filename.zip} {foldername}
    

If you are using Microsoft Windows:

Windows does not come with a command-line zip program, despite Windows Explorer natively supporting Zip files since the Plus! pack for Windows 98.

I recommend the open-source 7-Zip utility which includes a command-line executable and supports many different archive file types, especially its own *.7z format which offers superior compression ratios to traditional (PKZIP) *.zip files:

  1. Download 7-Zip from the 7-Zip home page

  2. Add the path to 7z.exe to your PATH environment variable. See this QA: How to set the path and environment variables in Windows

  3. Open a new command-prompt window and use this command to create a PKZIP *.zip file:

    7z a -tzip {yourfile.zip} {yourfolder}
    

Cross-platform Java:

If you have the Java JDK installed then you can use the jar utility to create Zip files, as *.jar files are essentially just renamed *.zip (PKZIP) files:

jar -cfM {yourfile.zip} {yourfolder}

Explanation: * -c compress * -f specify filename * -M do not include a MANIFEST file

How to switch to new window in Selenium for Python?

On top of the answers already given, to open a new tab the javascript command window.open() can be used.

For example:

# Opens a new tab
self.driver.execute_script("window.open()")

# Switch to the newly opened tab
self.driver.switch_to.window(self.driver.window_handles[1])

# Navigate to new URL in new tab
self.driver.get("https://google.com")
# Run other commands in the new tab here

You're then able to close the original tab as follows

# Switch to original tab
self.driver.switch_to.window(self.driver.window_handles[0])

# Close original tab
self.driver.close()

# Switch back to newly opened tab, which is now in position 0
self.driver.switch_to.window(self.driver.window_handles[0])

Or close the newly opened tab

# Close current tab
self.driver.close()

# Switch back to original tab
self.driver.switch_to.window(self.driver.window_handles[0])

Hope this helps.

Timeout jQuery effects

Update: As of jQuery 1.4 you can use the .delay( n ) method. http://api.jquery.com/delay/

$('.notice').fadeIn().delay(2000).fadeOut('slow'); 

Note: $.show() and $.hide() by default are not queued, so if you want to use $.delay() with them, you need to configure them that way:

$('.notice')
    .show({duration: 0, queue: true})
    .delay(2000)
    .hide({duration: 0, queue: true});

You could possibly use the Queue syntax, this might work:

jQuery(function($){ 

var e = $('.notice'); 
e.fadeIn(); 
e.queue(function(){ 
  setTimeout(function(){ 
    e.dequeue(); 
  }, 2000 ); 
}); 
e.fadeOut('fast'); 

}); 

or you could be really ingenious and make a jQuery function to do it.

(function($){ 

  jQuery.fn.idle = function(time)
  { 
      var o = $(this); 
      o.queue(function()
      { 
         setTimeout(function()
         { 
            o.dequeue(); 
         }, time);
      });
  };
})(jQuery);

which would ( in theory , working on memory here ) permit you do to this:

$('.notice').fadeIn().idle(2000).fadeOut('slow'); 

How can I plot a histogram such that the heights of the bars sum to 1 in matplotlib?

Here is another simple solution using np.histogram() method.

myarray = np.random.random(100)
results, edges = np.histogram(myarray, normed=True)
binWidth = edges[1] - edges[0]
plt.bar(edges[:-1], results*binWidth, binWidth)

You can indeed check that the total sums up to 1 with:

> print sum(results*binWidth)
1.0

In Firebase, is there a way to get the number of children of a node without loading all the node data?

This is a little late in the game as several others have already answered nicely, but I'll share how I might implement it.

This hinges on the fact that the Firebase REST API offers a shallow=true parameter.

Assume you have a post object and each one can have a number of comments:

{
 "posts": {
  "$postKey": {
   "comments": {
     ...  
   }
  }
 }
}

You obviously don't want to fetch all of the comments, just the number of comments.

Assuming you have the key for a post, you can send a GET request to https://yourapp.firebaseio.com/posts/[the post key]/comments?shallow=true.

This will return an object of key-value pairs, where each key is the key of a comment and its value is true:

{
 "comment1key": true,
 "comment2key": true,
 ...,
 "comment9999key": true
}

The size of this response is much smaller than requesting the equivalent data, and now you can calculate the number of keys in the response to find your value (e.g. commentCount = Object.keys(result).length).

This may not completely solve your problem, as you are still calculating the number of keys returned, and you can't necessarily subscribe to the value as it changes, but it does greatly reduce the size of the returned data without requiring any changes to your schema.

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

For Swift 3 and XCode 8, this worked. Follow below steps to achieve this:-

viewDidLoad()
    {
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        var width = UIScreen.main.bounds.width
        layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
    width = width - 10
    layout.itemSize = CGSize(width: width / 2, height: width / 2)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        collectionView!.collectionViewLayout = layout
    }

Count the number of items in my array list

You want to count the number of itemids in your array. Simply use:

int counter=list.size();

Less code increases efficiency. Do not re-invent the wheel...

Android: I am unable to have ViewPager WRAP_CONTENT

I was just answering a very similar question about this, and happened to find this when looking for a link to back up my claims, so lucky you :)

My other answer:
The ViewPager does not support wrap_content as it (usually) never have all its children loaded at the same time, and can therefore not get an appropriate size (the option would be to have a pager that changes size every time you have switched page).

You can however set a precise dimension (e.g. 150dp) and match_parent works as well.
You can also modify the dimensions dynamically from your code by changing the height-attribute in its LayoutParams.

For your needs you can create the ViewPager in its own xml-file, with the layout_height set to 200dp, and then in your code, rather than creating a new ViewPager from scratch, you can inflate that xml-file:

LayoutInflater inflater = context.getLayoutInflater();
inflater.inflate(R.layout.viewpagerxml, layout, true);

Making custom right-click context menus for my web-app

I have a nice and easy implementation using bootstrap as follows.

<select class="custom-select" id="list" multiple></select>

<div class="dropdown-menu" id="menu-right-click" style=>
    <h6 class="dropdown-header">Actions</h6>
    <a class="dropdown-item" href="" onclick="option1();">Option 1</a>
    <a class="dropdown-item" href="" onclick="option2();">Option 2</a>
</div>

<script>
    $("#menu-right-click").hide();

    $(document).on("contextmenu", "#list", function (e) {
        $("#menu-right-click")
            .css({
                position: 'absolute',
                left: e.pageX,
                top: e.pageY,
                display: 'block'
            })
        return false;
    });

    function option1() {
        // something you want...
        $("#menu-right-click").hide();
    }

    function option2() {
        // something else 
        $("#menu-right-click").hide();
    }
</script>

Get class name of object as string in Swift

Swift 5.1

You can get class, struct, enum, protocol and NSObject names though Self.self.

print("\(Self.self)")

assignment operator overloading in c++

Under the circumstances, you're almost certainly better off skipping the check for self-assignment -- when you're only assigning one member that seems to be a simple type (probably a double), it's generally faster to do that assignment than avoid it, so you'd end up with:

SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
    itsRadius = rhs.getRadius(); // or just `itsRadius = rhs.itsRadius;`
    return *this;
}

I realize that many older and/or lower quality books advise checking for self assignment. At least in my experience, however, it's sufficiently rare that you're better off without it (and if the operator depends on it for correctness, it's almost certainly not exception safe).

As an aside, I'd note that to define a circle, you generally need a center and a radius, and when you copy or assign, you want to copy/assign both.

Best way to generate xml?

Use lxml.builder class, from: http://lxml.de/tutorial.html#the-e-factory

import lxml.builder as lb
from lxml import etree

nstext = "new story"
story = lb.E.Asset(
  lb.E.Attribute(nstext, name="Name", act="set"),
  lb.E.Relation(lb.E.Asset(idref="Scope:767"),
            name="Scope", act="set")
  )

print 'story:\n', etree.tostring(story, pretty_print=True)

Output:

story:
<Asset>
  <Attribute name="Name" act="set">new story</Attribute>
  <Relation name="Scope" act="set">
    <Asset idref="Scope:767"/>
  </Relation>
</Asset>

How to parse JSON with VBA without external libraries?

Call me simple but I just declared a Variant and split the responsetext from my REST GET on the quote comma quote between each item, then got the value I wanted by looking for the last quote with InStrRev. I'm sure that's not as elegant as some of the other suggestions but it works for me.

         varLines = Split(.responsetext, """,""")
        strType = Mid(varLines(8), InStrRev(varLines(8), """") + 1)

Set Label Text with JQuery

The checkbox is in a td, so need to get the parent first:

$("input:checkbox").on("change", function() {
    $(this).parent().next().find("label").text("TESTTTT");
});

Alternatively, find a label which has a for with the same id (perhaps more performant than reverse traversal) :

$("input:checkbox").on("change", function() {
    $("label[for='" + $(this).attr('id') + "']").text("TESTTTT");
});

Or, to be more succinct just this.id:

$("input:checkbox").on("change", function() {
    $("label[for='" + this.id + "']").text("TESTTTT");
});

Can I update a JSF component from a JSF backing bean method?

The RequestContext is deprecated from Primefaces 6.2. From this version use the following:

if (componentID != null && PrimeFaces.current().isAjaxRequest()) {
    PrimeFaces.current().ajax().update(componentID);
}

And to execute javascript from the backbean use this way:

PrimeFaces.current().executeScript(jsCommand);

Reference:

Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

What worked for me was downgrading from EF 6.1.3 to EF 6.1.1.

In Visual Studios 2012+ head over to:

Tools - Nuget Package Manager - Package Manager Console`

Then enter:

Install-Package EntityFramework.SqlServerCompact -Version 6.1.1

I did not have to uninstall EF 6.1.3 first because the command above already does that.

In addition, I don't know if it did something, but I also installed SQL Server CE in my project.

Here's the link to the solution I found:

http://www.itorian.com/2014/11/no-entity-framework-provider-found-for.html

Asynchronously wait for Task<T> to complete with timeout

A few variants of Andrew Arnott's answer:

  1. If you want to wait for an existing task and find out whether it completed or timed out, but don't want to cancel it if the timeout occurs:

    public static async Task<bool> TimedOutAsync(this Task task, int timeoutMilliseconds)
    {
        if (timeoutMilliseconds < 0 || (timeoutMilliseconds > 0 && timeoutMilliseconds < 100)) { throw new ArgumentOutOfRangeException(); }
    
        if (timeoutMilliseconds == 0) {
            return !task.IsCompleted; // timed out if not completed
        }
        var cts = new CancellationTokenSource();
        if (await Task.WhenAny( task, Task.Delay(timeoutMilliseconds, cts.Token)) == task) {
            cts.Cancel(); // task completed, get rid of timer
            await task; // test for exceptions or task cancellation
            return false; // did not timeout
        } else {
            return true; // did timeout
        }
    }
    
  2. If you want to start a work task and cancel the work if the timeout occurs:

    public static async Task<T> CancelAfterAsync<T>( this Func<CancellationToken,Task<T>> actionAsync, int timeoutMilliseconds)
    {
        if (timeoutMilliseconds < 0 || (timeoutMilliseconds > 0 && timeoutMilliseconds < 100)) { throw new ArgumentOutOfRangeException(); }
    
        var taskCts = new CancellationTokenSource();
        var timerCts = new CancellationTokenSource();
        Task<T> task = actionAsync(taskCts.Token);
        if (await Task.WhenAny(task, Task.Delay(timeoutMilliseconds, timerCts.Token)) == task) {
            timerCts.Cancel(); // task completed, get rid of timer
        } else {
            taskCts.Cancel(); // timer completed, get rid of task
        }
        return await task; // test for exceptions or task cancellation
    }
    
  3. If you have a task already created that you want to cancel if a timeout occurs:

    public static async Task<T> CancelAfterAsync<T>(this Task<T> task, int timeoutMilliseconds, CancellationTokenSource taskCts)
    {
        if (timeoutMilliseconds < 0 || (timeoutMilliseconds > 0 && timeoutMilliseconds < 100)) { throw new ArgumentOutOfRangeException(); }
    
        var timerCts = new CancellationTokenSource();
        if (await Task.WhenAny(task, Task.Delay(timeoutMilliseconds, timerCts.Token)) == task) {
            timerCts.Cancel(); // task completed, get rid of timer
        } else {
            taskCts.Cancel(); // timer completed, get rid of task
        }
        return await task; // test for exceptions or task cancellation
    }
    

Another comment, these versions will cancel the timer if the timeout does not occur, so multiple calls will not cause timers to pile up.

sjb

ldconfig error: is not a symbolic link

You need to include the path of the libraries inside /etc/ld.so.conf, and rerun ldconfig to upate the list

Other possibility is to include in the env variable LD_LIBRARY_PATH the path to your library, and rerun the executable.

check the symbolic links if they point to a valid library ...

You can add the path directly in /etc/ld.so.conf, without include...

run ldconfig -p to see whether your library is well included in the cache.

How to get current domain name in ASP.NET

HttpContext.Current.Request.Url.Host is returning the correct values. If you run it on www.somedomainname.com it will give you www.somedomainname.com. If you want to get the 5858 as well you need to use

HttpContext.Current.Request.Url.Port 

Function of Project > Clean in Eclipse

Its function depends on the builders that you have in your project (they can choose to interpret clean command however they like) and whether you have auto-build turned on. If auto-build is on, invoking clean is equivalent of a clean build. First artifacts are removed, then a full build is invoked. If auto-build is off, clean will remove the artifacts and stop. You can then invoke build manually later.

How to check if another instance of my shell script is running

Definitely works.

if [[ `pgrep -f $0` != "$$" ]]; then
        echo "Exiting ! Exist"
        exit
fi

How to detect lowercase letters in Python?

If you don't want to use the libraries and want simple answer then the code is given below:

  def swap_alpha(test_string):
      new_string = ""
      for i in test_string:
          if i.upper() in test_string:
              new_string += i.lower()

          elif i.lower():
                new_string += i.upper()

          else:
              return "invalid "

      return new_string


user_string = input("enter the string:")
updated = swap_alpha(user_string)
print(updated)

How to get commit history for just one branch?

The git merge-base command can be used to find a common ancestor. So if my_experiment has not been merged into master yet and my_experiment was created from master you could:

git log --oneline `git merge-base my_experiment master`..my_experiment

How does MySQL process ORDER BY and LIMIT in a query?

It will order first, then get the first 20. A database will also process anything in the WHERE clause before ORDER BY.

Find the least number of coins required that can make any change from 1 to 99 cents

You can very quickly find an upper bound.

Say, you take three quarters. Then you would only have to fill in the 'gaps' 1-24, 26-49, 51-74, 76-99 with other coins.

Trivially, that would work with 2 dimes, 1 nickel, and 4 pennies.

So, 3 + 4 + 2 + 1 should be an upper bound for your number of coins, Whenever your brute-force algorithm goes above thta, you can instantly stop searching any deeper.

The rest of the search should perform fast enough for any purpose with dynamic programming.

(edit: fixed answer as per Gabe's observation)

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

Don't use jQuery, just use javascript for correct result:

This includes scrollbar width/height:

_x000D_
_x000D_
var windowWidth = window.innerWidth;_x000D_
var windowHeight = window.innerHeight;_x000D_
_x000D_
alert('viewport width is: '+ windowWidth + ' and viewport height is:' + windowHeight);
_x000D_
_x000D_
_x000D_

This excludes scrollbar width/height:

_x000D_
_x000D_
var widthWithoutScrollbar = document.body.clientWidth;_x000D_
var heightWithoutScrollbar = document.body.clientHeight;_x000D_
_x000D_
alert('viewport width is: '+ widthWithoutScrollbar + ' and viewport height is:' + heightWithoutScrollbar);
_x000D_
_x000D_
_x000D_

Want to upgrade project from Angular v5 to Angular v6

As Vinay Kumar pointed out that it will not update global installed Angular CLI. To update it globally just use following commands:

npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli@latest

Note if you want to update existing project you have to modify existing project, you should change package.json inside your project.

There are no breaking changes in Angular itself but they are in RxJS, so don't forget to use rxjs-compat library to work with legacy code.

  npm install --save rxjs-compat  

I wrote a good article about installation/updating Angular CLI http://bmnteam.com/angular-cli-installation/

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

C# Get a control's position on a form

This is what i've done works like a charm

            private static int _x=0, _y=0;
        private static Point _point;
        public static Point LocationInForm(Control c)
        {
            if (c.Parent == null) 
            {
                _x += c.Location.X;
                _y += c.Location.Y;
                _point = new Point(_x, _y);
                _x = 0; _y = 0;
                return _point;
            }
            else if ((c.Parent is System.Windows.Forms.Form))
            {
                _point = new Point(_x, _y);
                _x = 0; _y = 0;
                return _point;
            }
            else 
            {
                _x += c.Location.X;
                _y += c.Location.Y;
                LocationInForm(c.Parent);
            }
            return new Point(1,1);
        }

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

Byte swapping with ye olde 3-step-xor trick around a pivot in a template function gives a flexible, quick O(ln2) solution that does not require a library, the style here also rejects 1 byte types:

template<typename T>void swap(T &t){
    for(uint8_t pivot = 0; pivot < sizeof(t)/2; pivot ++){
        *((uint8_t *)&t + pivot) ^= *((uint8_t *)&t+sizeof(t)-1- pivot);
        *((uint8_t *)&t+sizeof(t)-1- pivot) ^= *((uint8_t *)&t + pivot);
        *((uint8_t *)&t + pivot) ^= *((uint8_t *)&t+sizeof(t)-1- pivot);
    }
}

Difference between Console.Read() and Console.ReadLine()?

Console.Read()

  • It only accepts a single character from user input and returns its ASCII Code.
  • The data type should be int. because it returns an integer value as ASCII.
  • ex -> int value = Console.Read();

Console.ReadLine()

  • It read all the characters from user input. (and finish when press enter).
  • It returns a String so data type should be String.
  • ex -> string value = Console.ReadLine();

Console.ReadKey()

  • It read that which key is pressed by the user and returns its name. it does not require to press enter key before entering.
  • It is a Struct Data type which is ConsoleKeyInfo.
  • ex -> ConsoleKeyInfo key = Console.ReadKey();

How do I remove version tracking from a project cloned from git?

I am working with a Linux environment. I removed all Git files and folders in a recursive way:

rm -rf .git

rm -rf .gitkeep

How to give credentials in a batch script that copies files to a network location?

Try using the net use command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.

net use \\<network-location>\<some-share> password /USER:username

Don't leave a trailing \ at the end of the

Get generic type of java.util.List

For finding generic type of one field:

((Class)((ParameterizedType)field.getGenericType()).getActualTypeArguments()[0]).getSimpleName()

Fragments onResume from back stack

The following section at Android Developers describes a communication mechanism Creating event callbacks to the activity. To quote a line from it:

A good way to do that is to define a callback interface inside the fragment and require that the host activity implement it. When the activity receives a callback through the interface, it can share the information with other fragments in the layout as necessary.

Edit: The fragment has an onStart(...) which is invoked when the fragment is visible to the user. Similarly an onResume(...) when visible and actively running. These are tied to their activity counterparts. In short: use onResume()

Empty ArrayList equals null

No, this will not work. The best you will be able to do is to iterate through all values and check them yourself:

boolean empty = true;
for (Object item : arrayList) {
    if (item != null) {
        empty = false;
        break;
    }
}

Use latest version of Internet Explorer in the webbrowser control

Rather than changing the RegKey, I was able to put a line in the header of my HTML:

<html>
    <head>
        <!-- Use lastest version of Internet Explorer -->
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />

        <!-- Insert other header tags here -->
    </head>
    ...
</html>

See Web Browser Control & Specifying the IE Version.

Rails - passing parameters in link_to

Try this

link_to "+ Service", my_services_new_path(:account_id => acct.id)

it will pass the account_id as you want.

For more details on link_to use this http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

How to generate java classes from WSDL file

You can use the WSDL2JAVA Codegen (or) You can simply use the 'Web Service/WebServiceClient' Wizard available in the Eclipse IDE. Open the IDE and press 'Ctrl+N', selectfor 'Web Service/WebServiceClient', specify the wsdl URL, ouput folder and select finish.

It creates the complete source files that you would need.

this is error ORA-12154: TNS:could not resolve the connect identifier specified?

The database must have a name (example DB1), try this one:

OracleConnection con = new OracleConnection("data source=DB1;user id=fastecit;password=fastecit"); 

In case the TNS is not defined you can also try this one:

OracleConnection con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=DB1)));
User Id=fastecit;Password=fastecit"); 

concat yesterdays date with a specific time

where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS') 

should work.

Getting the client IP address: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, what else could be useful?

I've ported Grant Burton's PHP code to an ASP.Net static method callable against the HttpRequestBase. It will optionally skip through any private IP ranges.

public static class ClientIP
{
    // based on http://www.grantburton.com/2008/11/30/fix-for-incorrect-ip-addresses-in-wordpress-comments/
    public static string ClientIPFromRequest(this HttpRequestBase request, bool skipPrivate)
    {
        foreach (var item in s_HeaderItems)
        {
            var ipString = request.Headers[item.Key];

        if (String.IsNullOrEmpty(ipString))
            continue;

        if (item.Split)
        {
            foreach (var ip in ipString.Split(','))
                if (ValidIP(ip, skipPrivate))
                    return ip;
        }
        else
        {
            if (ValidIP(ipString, skipPrivate))
                return ipString;
        }
    }

    return request.UserHostAddress;
}

private static bool ValidIP(string ip, bool skipPrivate)
{
    IPAddress ipAddr;

    ip = ip == null ? String.Empty : ip.Trim();

    if (0 == ip.Length
        || false == IPAddress.TryParse(ip, out ipAddr)
        || (ipAddr.AddressFamily != AddressFamily.InterNetwork
            && ipAddr.AddressFamily != AddressFamily.InterNetworkV6))
        return false;

    if (skipPrivate && ipAddr.AddressFamily == AddressFamily.InterNetwork)
    {
        var addr = IpRange.AddrToUInt64(ipAddr);
        foreach (var range in s_PrivateRanges)
        {
            if (range.Encompasses(addr))
                return false;
        }
    }

    return true;
}

/// <summary>
/// Provides a simple class that understands how to parse and
/// compare IP addresses (IPV4) ranges.
/// </summary>
private sealed class IpRange
{
    private readonly UInt64 _start;
    private readonly UInt64 _end;

    public IpRange(string startStr, string endStr)
    {
        _start = ParseToUInt64(startStr);
        _end = ParseToUInt64(endStr);
    }

    public static UInt64 AddrToUInt64(IPAddress ip)
    {
        var ipBytes = ip.GetAddressBytes();
        UInt64 value = 0;

        foreach (var abyte in ipBytes)
        {
            value <<= 8;    // shift
            value += abyte;
        }

        return value;
    }

    public static UInt64 ParseToUInt64(string ipStr)
    {
        var ip = IPAddress.Parse(ipStr);
        return AddrToUInt64(ip);
    }

    public bool Encompasses(UInt64 addrValue)
    {
        return _start <= addrValue && addrValue <= _end;
    }

    public bool Encompasses(IPAddress addr)
    {
        var value = AddrToUInt64(addr);
        return Encompasses(value);
    }
};

private static readonly IpRange[] s_PrivateRanges =
    new IpRange[] { 
            new IpRange("0.0.0.0","2.255.255.255"),
            new IpRange("10.0.0.0","10.255.255.255"),
            new IpRange("127.0.0.0","127.255.255.255"),
            new IpRange("169.254.0.0","169.254.255.255"),
            new IpRange("172.16.0.0","172.31.255.255"),
            new IpRange("192.0.2.0","192.0.2.255"),
            new IpRange("192.168.0.0","192.168.255.255"),
            new IpRange("255.255.255.0","255.255.255.255")
    };


/// <summary>
/// Describes a header item (key) and if it is expected to be 
/// a comma-delimited string
/// </summary>
private sealed class HeaderItem
{
    public readonly string Key;
    public readonly bool Split;

    public HeaderItem(string key, bool split)
    {
        Key = key;
        Split = split;
    }
}

// order is in trust/use order top to bottom
private static readonly HeaderItem[] s_HeaderItems =
    new HeaderItem[] { 
            new HeaderItem("HTTP_CLIENT_IP",false),
            new HeaderItem("HTTP_X_FORWARDED_FOR",true),
            new HeaderItem("HTTP_X_FORWARDED",false),
            new HeaderItem("HTTP_X_CLUSTER_CLIENT_IP",false),
            new HeaderItem("HTTP_FORWARDED_FOR",false),
            new HeaderItem("HTTP_FORWARDED",false),
            new HeaderItem("HTTP_VIA",false),
            new HeaderItem("REMOTE_ADDR",false)
    };
}

Best way to show a loading/progress indicator?

ProgressDialog has become deprecated since API Level 26 https://developer.android.com/reference/android/app/ProgressDialog.html

I include a ProgressBar in my layout

   <ProgressBar
        android:layout_weight="1"
        android:id="@+id/progressBar_cyclic"
        android:visibility="gone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="40dp"
        android:minWidth="40dp" />

and change its visibility to .GONE | .VISIBLE depending on the use case.

    progressBar_cyclic.visibility = View.VISIBLE

Int to Char in C#

int i = 65;
char c = Convert.ToChar(i);

Including an anchor tag in an ASP.NET MVC Html.ActionLink

Here is the real life example

@Html.Grid(Model).Columns(columns =>
    {
           columns.Add()
                   .Encoded(false)
                   .Sanitized(false)
                   .SetWidth(10)
                   .Titled(string.Empty)
                   .RenderValueAs(x => @Html.ActionLink("Edit", "UserDetails", "Membership", null, null, "discount", new { @id = @x.Id }, new { @target = "_blank" }));

  }).WithPaging(200).EmptyText("There Are No Items To Display")

And the target page has TABS

<ul id="myTab" class="nav nav-tabs" role="tablist">

        <li class="active"><a href="#discount" role="tab" data-toggle="tab">Discount</a></li>
    </ul>

Can't start Eclipse - Java was started but returned exit code=13

I had the same issue after I upgraded my JDK from 1.7 to 1.8. I'm using Eclipse 4.4 (Luna). The error is gone after I degrade JDK to 1.7.

Docker - a way to give access to a host USB or serial device?

If you would like to dynamically access USB devices which can be plugged in while the docker container is already running, for example access a just attached usb webcam at /dev/video0, you can add a cgroup rule when starting the container. This option does not need a --privileged container and only allows access to specific types of hardware.

Step 1

Check the device major number of the type of device you would like to add. You can look it up in the linux kernel documentation. Or you can check it for your device. For example to check the device major number for a webcam connected to /dev/video0, you can do a ls -la /dev/video0. This results in something like:

crw-rw----+ 1 root video 81, 0 Jul  6 10:22 /dev/video0

Where the first number (81) is the device major number. Some common device major numbers:

  • 81: usb webcams
  • 188: usb to serial converters

Step 2

Add rules when you start the docker container:

  • Add a --device-cgroup-rule='c major_number:* rmw' rule for every type of device you want access to
  • Add access to udev information so docker containers can get more info on your usb devices with -v /run/udev:/run/udev:ro
  • Map the /dev volume to your docker container with -v /dev:/dev

Wrap up

So to add all usb webcams and serial2usb devices to your docker container, do:

docker run -it -v /dev:/dev --device-cgroup-rule='c 188:* rmw' --device-cgroup-rule='c 81:* rmw' ubuntu bash

How to Ignore "Duplicate Key" error in T-SQL (SQL Server)

INSERT INTO KeyedTable(KeyField, Otherfield)
SELECT n.* FROM 
    (SELECT 'PossibleDupeLiteral' AS KeyField, 'OtherfieldValue' AS Otherfield
     UNION ALL
     SELECT 'PossibleDupeLiteral', 'OtherfieldValue2'
    )
LEFT JOIN KeyedTable k
    ON k.KeyField=n.KeyField
WHERE k.KeyField IS NULL

This tells the Server to look for the same data (hopefully the same speedy way it does to check for duplicate keys) and insert nothing if it finds it.

I like the IGNORE_DUP_KEY solution too, but then anyone who relies on errors to catch problems will be mystified when the server silently ignores their dupe-key errors.

The reason I choose this over Philip Kelley's solution is that you can provide several rows of data and only have the missing ones actually get in:

Clear git local cache

When you think your git is messed up, you can use this command to do everything up-to-date.

git rm -r --cached .
git add .
git commit -am 'git cache cleared'
git push

Also to revert back last commit use this :

git reset HEAD^ --hard

Fix footer to bottom of page

A very simple example that shows how to fix the footer at the bottom in your application's layout.

_x000D_
_x000D_
/* Styles go here */_x000D_
html{ height: 100%;}_x000D_
body{ min-height: 100%; background: #fff;}_x000D_
.page-layout{ border: none; width: 100%; height: 100vh; }_x000D_
.page-layout td{ vertical-align: top; }_x000D_
.page-layout .header{ background: #aaa; }_x000D_
.page-layout .main-content{ height: 100%; background: #f1f1f1; text-align: center; padding-top: 50px; }_x000D_
.page-layout .main-content .container{ text-align: center; padding-top: 50px; }_x000D_
.page-layout .footer{ background: #333; color: #fff; } 
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
  <head>_x000D_
    <link data-require="bootstrap@*" data-semver="4.0.5" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />_x000D_
    <link rel="stylesheet" href="style.css" />_x000D_
    <script src="script.js"></script>_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <table class="page-layout">_x000D_
      <tr>_x000D_
        <td class="header">_x000D_
          <div>_x000D_
            This is the site header._x000D_
          </div>_x000D_
        </td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td class="main-content">_x000D_
          <div>_x000D_
            <h1>Fix footer always to the bottom</h1>_x000D_
            <div>_x000D_
              This is how you can simply fix the footer to the bottom._x000D_
            </div>_x000D_
            <div>_x000D_
              The footer will always stick to the bottom until the main-content doesn't grow till footer._x000D_
            </div>_x000D_
            <div>_x000D_
              Even if the content grows, the footer will start to move down naturally as like the normal behavior of page._x000D_
            </div>_x000D_
          </div>_x000D_
        </td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td class="footer">_x000D_
          <div>_x000D_
            This is the site footer._x000D_
          </div>_x000D_
        </td>_x000D_
      </tr>_x000D_
    </table>_x000D_
  </body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Random integer in VB.NET

Microsoft Example Rnd Function

https://msdn.microsoft.com/en-us/library/f7s023d2%28v=vs.90%29.aspx

1- Initialize the random-number generator.

Randomize()

2 - Generate random value between 1 and 6.

Dim value As Integer = CInt(Int((6 * Rnd()) + 1))

Creating a BLOB from a Base64 string in JavaScript

Optimized (but less readable) implementation:

function base64toBlob(base64Data, contentType) {
    contentType = contentType || '';
    var sliceSize = 1024;
    var byteCharacters = atob(base64Data);
    var bytesLength = byteCharacters.length;
    var slicesCount = Math.ceil(bytesLength / sliceSize);
    var byteArrays = new Array(slicesCount);

    for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);

        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}

What does "hard coded" mean?

The antonym of Hard-Coding is Soft-Coding. For a better understanding of Hard Coding, I will introduce both terms.

  • Hard-coding: feature is coded to the system not allowing for configuration;
  • Parametric: feature is configurable via table driven, or properties files with limited parametric values ;
  • Soft-coding: feature uses “engines” that derive results based on any number of parametric values (e.g. business rules in BRE); rules are coded but exist as parameters in system, written in script form

Examples:

// firstName has a hard-coded value of "hello world"
string firstName = "hello world";

// firstName has a non-hard-coded provided as input
Console.WriteLine("first name :");
string firstName = Console.ReadLine();

A hard-coded constant[1]:

float areaOfCircle(int radius)
{
    float area = 0;
    area = 3.14*radius*radius;  //  3.14 is a hard-coded value
    return area;
}

Additionally, hard-coding and soft-coding could be considered to be anti-patterns[2]. Thus, one should strive for balance between hard and soft-coding.

  1. Hard CodingHard coding” is a well-known antipattern against which most web development books warns us right in the preface. Hard coding is the unfortunate practice in which we store configuration or input data, such as a file path or a remote host name, in the source code rather than obtaining it from a configuration file, a database, a user input, or another external source.

    The main problem with hard code is that it only works properly in a certain environment, and at any time the conditions change, we need to modify the source code, usually in multiple separate places.

  2. Soft Coding
    If we try very hard to avoid the pitfall of hard coding, we can easily run into another antipattern called “soft coding”, which is its exact opposite.

    In soft coding, we put things that should be in the source code into external sources, for example we store business logic in the database. The most common reason why we do so, is the fear that business rules will change in the future, therefore we will need to rewrite the code.

    In extreme cases, a soft coded program can become so abstract and convoluted that it is almost impossible to comprehend it (especially for new team members), and extremely hard to maintain and debug.

Sources and Citations:

1: Quora: What does hard-coded something mean in computer programming context?
2: Hongkiat: The 10 Coding Antipatterns You Must Avoid

Further Reading:

Software Engineering SE: Is it ever a good idea to hardcode values into our applications?
Wikipedia: Hardcoding
Wikipedia: Soft-coding

How to plot a histogram using Matplotlib in Python with a list of data?

This is an old question but none of the previous answers has addressed the real issue, i.e. that fact that the problem is with the question itself.

First, if the probabilities have been already calculated, i.e. the histogram aggregated data is available in a normalized way then the probabilities should add up to 1. They obviously do not and that means that something is wrong here, either with terminology or with the data or in the way the question is asked.

Second, the fact that the labels are provided (and not intervals) would normally mean that the probabilities are of categorical response variable - and a use of a bar plot for plotting the histogram is best (or some hacking of the pyplot's hist method), Shayan Shafiq's answer provides the code.

However, see issue 1, those probabilities are not correct and using bar plot in this case as "histogram" would be wrong because it does not tell the story of univariate distribution, for some reason (perhaps the classes are overlapping and observations are counted multiple times?) and such plot should not be called a histogram in this case.

Histogram is by definition a graphical representation of the distribution of univariate variable (see Histogram | NIST/SEMATECH e-Handbook of Statistical Methods & Histogram | Wikipedia) and is created by drawing bars of sizes representing counts or frequencies of observations in selected classes of the variable of interest. If the variable is measured on a continuous scale those classes are bins (intervals). Important part of histogram creation procedure is making a choice of how to group (or keep without grouping) the categories of responses for a categorical variable, or how to split the domain of possible values into intervals (where to put the bin boundaries) for continuous type variable. All observations should be represented, and each one only once in the plot. That means that the sum of the bar sizes should be equal to the total count of observation (or their areas in case of the variable widths, which is a less common approach). Or, if the histogram is normalised then all probabilities must add up to 1.

If the data itself is a list of "probabilities" as a response, i.e. the observations are probability values (of something) for each object of study then the best answer is simply plt.hist(probability) with maybe binning option, and use of x-labels already available is suspicious.

Then bar plot should not be used as histogram but rather simply

import matplotlib.pyplot as plt
probability = [0.3602150537634409, 0.42028985507246375, 
  0.373117033603708, 0.36813186813186816, 0.32517482517482516, 
  0.4175257731958763, 0.41025641025641024, 0.39408866995073893, 
  0.4143222506393862, 0.34, 0.391025641025641, 0.3130841121495327, 
  0.35398230088495575]
plt.hist(probability)
plt.show()

with the results

enter image description here

matplotlib in such case arrives by default with the following histogram values

(array([1., 1., 1., 1., 1., 2., 0., 2., 0., 4.]),
 array([0.31308411, 0.32380469, 0.33452526, 0.34524584, 0.35596641,
        0.36668698, 0.37740756, 0.38812813, 0.39884871, 0.40956928,
        0.42028986]),
 <a list of 10 Patch objects>)

the result is a tuple of arrays, the first array contains observation counts, i.e. what will be shown against the y-axis of the plot (they add up to 13, total number of observations) and the second array are the interval boundaries for x-axis.

One can check they they are equally spaced,

x = plt.hist(probability)[1]
for left, right in zip(x[:-1], x[1:]):
  print(left, right, right-left)

enter image description here

Or, for example for 3 bins (my judgment call for 13 observations) one would get this histogram

plt.hist(probability, bins=3)

enter image description here

with the plot data "behind the bars" being

enter image description here

The author of the question needs to clarify what is the meaning of the "probability" list of values - is the "probability" just a name of the response variable (then why are there x-labels ready for the histogram, it makes no sense), or are the list values the probabilities calculated from the data (then the fact they do not add up to 1 makes no sense).

What is TypeScript and why would I use it in place of JavaScript?

Ecma script 5 (ES5) which all browser support and precompiled. ES6/ES2015 and ES/2016 came this year with lots of changes so to pop up these changes there is something in between which should take cares about so TypeScript.

• TypeScript is Types -> Means we have to define datatype of each property and methods. If you know C# then Typescript is easy to understand.

• Big advantage of TypeScript is we identify Type related issues early before going to production. This allows unit tests to fail if there is any type mismatch.

Pandas read in table without headers

Make sure you specify pass header=None and add usecols=[3,6] for the 4th and 7th columns.

Using BETWEEN in CASE SQL statement

Take out the MONTHS from your case, and remove the brackets... like this:

CASE 
    WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
    ELSE 'NOTHING'
END AS 'MONTHS'

You can think of this as being equivalent to:

CASE TRUE
    WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
    ELSE 'NOTHING'
END AS 'MONTHS'

Node.js - get raw request body using Express

This solution worked for me:

var rawBodySaver = function (req, res, buf, encoding) {
  if (buf && buf.length) {
    req.rawBody = buf.toString(encoding || 'utf8');
  }
}

app.use(bodyParser.json({ verify: rawBodySaver }));
app.use(bodyParser.urlencoded({ verify: rawBodySaver, extended: true }));
app.use(bodyParser.raw({ verify: rawBodySaver, type: '*/*' }));

When I use solution with req.on('data', function(chunk) { }); it not working on chunked request body.

How to ignore a particular directory or file for tslint?

Starting from tslint v5.8.0 you can set an exclude property under your linterOptions key in your tslint.json file:

{
  "extends": "tslint:latest",
  "linterOptions": {
      "exclude": [
          "bin",
          "**/__test__",
          "lib/*generated.js"
      ]
  }
}

More information on this here.

How does `scp` differ from `rsync`?

One major feature of rsync over scp (beside the delta algorithm and encryption if used w/ ssh) is that it automatically verifies if the transferred file has been transferred correctly. Scp will not do that, which occasionally might result in corruption when transferring larger files. So in general rsync is a copy with guarantee.

Centos manpages mention this the end of the --checksum option description:

Note that rsync always verifies that each transferred file was correctly reconstructed on the receiving side by checking a whole-file checksum that is generated as the file is transferred, but that automatic after-the-transfer verification has nothing to do with this option’s before-the-transfer “Does this file need to be updated?” check.

Javascript dynamic array of strings

var junk=new Array();
junk.push('This is a string.');

Et cetera.

SQL Server 2008 Insert with WHILE LOOP

First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.

But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.

For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used

CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN 
    INSERT hospitals ([Hospital ID], Email, Description) 
    VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid))); 
    SET @hid = @hid + 1;
END

And result would be

ID   Hospital ID Email            Description          
---- ----------- ---------------- ---------------------
1    16          [email protected]  Sample Description16 
2    17          [email protected]  Sample Description17 
...                                                    
84   99          [email protected]  Sample Description99 

How do I write stderr to a file while using "tee" with a pipe?

In my case, a script was running command while redirecting both stdout and stderr to a file, something like:

cmd > log 2>&1

I needed to update it such that when there is a failure, take some actions based on the error messages. I could of course remove the dup 2>&1 and capture the stderr from the script, but then the error messages won't go into the log file for reference. While the accepted answer from @lhunath is supposed to do the same, it redirects stdout and stderr to different files, which is not what I want, but it helped me to come up with the exact solution that I need:

(cmd 2> >(tee /dev/stderr)) > log

With the above, log will have a copy of both stdout and stderr and I can capture stderr from my script without having to worry about stdout.

Initialize a string in C to empty string

string[0] = "";
"warning: assignment makes integer from pointer without a cast

Ok, let's dive into the expression ...

0 an int: represents the number of chars (assuming string is (or decayed into) a char*) to advance from the beginning of the object string

string[0]: the char object located at the beginning of the object string

"": string literal: an object of type char[1]

=: assignment operator: tries to assign a value of type char[1] to an object of type char. char[1] (decayed to char*) and char are not assignment compatible, but the compiler trusts you (the programmer) and goes ahead with the assignment anyway by casting the type char* (what char[1] decayed to) to an int --- and you get the warning as a bonus. You have a really nice compiler :-)

Select columns based on string match - dplyr::select

Within the dplyr world, try:

select(iris,contains("Sepal"))

See the Selection section in ?select for numerous other helpers like starts_with, ends_with, etc.

What is the LDF file in SQL Server?

The LDF is the transaction log. It keeps a record of everything done to the database for rollback purposes.

You do not want to delete, but you can shrink it with the dbcc shrinkfile command. You can also right-click on the database in SQL Server Management Studio and go to Tasks > Shrink.

Cordova - Error code 1 for command | Command failed for

Delete platforms/android folder and try to rebuild. That helped me a lot.

(Visual Studio Tools for Apache Cordova)

How to make/get a multi size .ico file?

The excellent (free trial) IcoFX allows you to create and edit icons, including multiple sizes up to 256x256, PNG compression, and transparency. I highly recommend it over most of the alternates.

Get your copy here: http://icofx.ro/ . It supports Windows XP onwards.


Windows automatically chooses the proper icon from the file, depending on where it is to be displayed. For more information on icon design and the sizes/bit depths you should include, see these references:

Defining a percentage width for a LinearLayout?

Use new percentage support library

compile 'com.android.support:percent:24.0.0'

See below example

<android.support.percent.PercentRelativeLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
     <ImageView
         app:layout_widthPercent="50%"
         app:layout_heightPercent="50%"
         app:layout_marginTopPercent="25%"
         app:layout_marginLeftPercent="25%"/>
 </android.support.percent.PercentRelativeLayout>

For More Info Tutorial1 Tutorial2 Tutorial3

Is there an equivalent method to C's scanf in Java?

Java always takes arguments as a string type...(String args[]) so you need to convert in your desired type.

  • Use Integer.parseInt() to convert your string into Interger.
  • To print any string you can use System.out.println()

Example :

  int a;
  a = Integer.parseInt(args[0]);

and for Standard Input you can use codes like

  StdIn.readInt();
  StdIn.readString();

Removing NA in dplyr pipe

I don't think desc takes an na.rm argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NAs, use na.omit (base) or tidyr::drop_na:

outcome.df %>%
  na.omit() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

library(tidyr)
outcome.df %>%
  drop_na() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

If you only want to remove NAs from the HeartAttackDeath column, filter with is.na, or use tidyr::drop_na:

outcome.df %>%
  filter(!is.na(HeartAttackDeath)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

outcome.df %>%
  drop_na(HeartAttackDeath) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

As pointed out at the dupe, complete.cases can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:

outcome.df %>%
  filter(complete.cases(.)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

"com.jcraft.jsch.JSchException: Auth fail" with working passwords

If username/password contains any special characters then inside the camel configuration use RAW for Configuring the values like

  • RAW(se+re?t&23) where se+re?t&23 is actual password

  • RAW({abc.ftp.password}) where {abc.ftp.password} values comes from a spring property file.

By using RAW, solved my issue.

http://camel.apache.org/how-do-i-configure-endpoints.html

When to use If-else if-else over switch statements and vice versa

If you are switching on the value of a single variable then I'd use a switch every time, it's what the construct was made for.

Otherwise, stick with multiple if-else statements.

What are -moz- and -webkit-?

What are -moz- and -webkit-?

CSS properties starting with -webkit-, -moz-, -ms- or -o- are called vendor prefixes.


Why do different browsers add different prefixes for the same effect?

A good explanation of vendor prefixes comes from Peter-Paul Koch of QuirksMode:

Originally, the point of vendor prefixes was to allow browser makers to start supporting experimental CSS declarations.

Let's say a W3C working group is discussing a grid declaration (which, incidentally, wouldn't be such a bad idea). Let's furthermore say that some people create a draft specification, but others disagree with some of the details. As we know, this process may take ages.

Let's furthermore say that Microsoft as an experiment decides to implement the proposed grid. At this point in time, Microsoft cannot be certain that the specification will not change. Therefore, instead of adding the grid to its CSS, it adds -ms-grid.

The vendor prefix kind of says "this is the Microsoft interpretation of an ongoing proposal." Thus, if the final definition of the grid is different, Microsoft can add a new CSS property grid without breaking pages that depend on -ms-grid.


UPDATE AS OF THE YEAR 2016

As this post 3 years old, it's important to mention that now most vendors do understand that these prefixes are just creating un-necessary duplicate code and that the situation where you need to specify 3 different CSS rules to get one effect working in all browser is an unwanted one.

As mentioned in this glossary about Mozilla's view on Vendor Prefix on May 3, 2016,

Browser vendors are now trying to get rid of vendor prefix for experimental features. They noticed that Web developers were using them on production Web sites, polluting the global space and making it more difficult for underdogs to perform well.

For example, just a few years ago, to set a rounded corner on a box you had to write:

-moz-border-radius: 10px 5px;
-webkit-border-top-left-radius: 10px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-right-radius: 10px;
-webkit-border-bottom-left-radius: 5px;
border-radius: 10px 5px;

But now that browsers have come to fully support this feature, you really only need the standardized version:

border-radius: 10px 5px;

Finding the right rules for all browsers

As still there's no standard for common CSS rules that work on all browsers, you can use tools like caniuse.com to check support of a rule across all major browsers.

You can also use pleeease.io/play. Pleeease is a Node.js application that easily processes your CSS. It simplifies the use of preprocessors and combines them with best postprocessors. It helps create clean stylesheets, support older browsers and offers better maintainability.

Input:

a {
  column-count: 3;
  column-gap: 10px;
  column-fill: auto;
}

Output:

a {
  -webkit-column-count: 3;
     -moz-column-count: 3;
          column-count: 3;
  -webkit-column-gap: 10px;
     -moz-column-gap: 10px;
          column-gap: 10px;
  -webkit-column-fill: auto;
     -moz-column-fill: auto;
          column-fill: auto;
}

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

I think the Vim documentation should've explained the meaning behind the naming of these commands. Just telling you what they do doesn't help you remember the names.

map is the "root" of all recursive mapping commands. The root form applies to "normal", "visual+select", and "operator-pending" modes. (I'm using the term "root" as in linguistics.)

noremap is the "root" of all non-recursive mapping commands. The root form applies to the same modes as map. (Think of the nore prefix to mean "non-recursive".)

(Note that there are also the ! modes like map! that apply to insert & command-line.)

See below for what "recursive" means in this context.

Prepending a mode letter like n modify the modes the mapping works in. It can choose a subset of the list of applicable modes (e.g. only "visual"), or choose other modes that map wouldn't apply to (e.g. "insert").

Use help map-modes will show you a few tables that explain how to control which modes the mapping applies to.

Mode letters:

  • n: normal only
  • v: visual and select
  • o: operator-pending
  • x: visual only
  • s: select only
  • i: insert
  • c: command-line
  • l: insert, command-line, regexp-search (and others. Collectively called "Lang-Arg" pseudo-mode)

"Recursive" means that the mapping is expanded to a result, then the result is expanded to another result, and so on.

The expansion stops when one of these is true:

  1. the result is no longer mapped to anything else.
  2. a non-recursive mapping has been applied (i.e. the "noremap" [or one of its ilk] is the final expansion).

At that point, Vim's default "meaning" of the final result is applied/executed.

"Non-recursive" means the mapping is only expanded once, and that result is applied/executed.

Example:

 nmap K H
 nnoremap H G
 nnoremap G gg

The above causes K to expand to H, then H to expand to G and stop. It stops because of the nnoremap, which expands and stops immediately. The meaning of G will be executed (i.e. "jump to last line"). At most one non-recursive mapping will ever be applied in an expansion chain (it would be the last expansion to happen).

The mapping of G to gg only applies if you press G, but not if you press K. This mapping doesn't affect pressing K regardless of whether G was mapped recursively or not, since it's line 2 that causes the expansion of K to stop, so line 3 wouldn't be used.

How to create an Excel File with Nodejs?

Use exceljs library for creating and writing into existing excel sheets.

You can check this tutorial for detailed explanation.

link

Create MSI or setup project with Visual Studio 2012

Have you tried the "Publish" method? You just right click on the project file in the solution explorer and select "Publish" from the pop-up menu. This creates an installer in a few very simple steps.

You can do more configuration of the installer from the Publish tab in the project properties window.

NB: This method only works for WPF & Windows Forms apps.

How to hide image broken Icon using only CSS/HTML?

Since 2005, Mozilla browsers such as Firefox have supported the non-standard :-moz-broken CSS pseudo-class that can accomplish exactly this request:

_x000D_
_x000D_
td {_x000D_
  min-width:64px; /* for display purposes so you can see the empty cell */_x000D_
}_x000D_
_x000D_
img[alt]:-moz-broken {_x000D_
  display:none;_x000D_
}
_x000D_
<table border="1"><tr><td>_x000D_
  <img src="error">_x000D_
</td><td>_x000D_
  <img src="broken" alt="A broken image">_x000D_
</td><td>_x000D_
  <img src="https://images-na.ssl-images-amazon.com/images/I/218eLEn0fuL.png"_x000D_
       alt="A bird" style="width: 120px">_x000D_
</td></tr></table>
_x000D_
_x000D_
_x000D_

img[alt]::before also works in Firefox 64 (though once upon a time it was img[alt]::after so this is not reliable). I can't get either of those to work in Chrome 71.

VBScript to send email without running Outlook

You can send email without Outlook in VBScript using the CDO.Message object. You will need to know the address of your SMTP server to use this:

Set MyEmail=CreateObject("CDO.Message")

MyEmail.Subject="Subject"
MyEmail.From="[email protected]"
MyEmail.To="[email protected]"
MyEmail.TextBody="Testing one two three."

MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2

'SMTP Server
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"

'SMTP Port
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25 

MyEmail.Configuration.Fields.Update
MyEmail.Send

set MyEmail=nothing

If your SMTP server requires a username and password then paste these lines in above the MyEmail.Configuration.Fields.Update line:

'SMTP Auth (For Windows Auth set this to 2)
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'Username
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="username" 
'Password
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="password"

More information on using CDO to send email with VBScript can be found on the link below: http://www.paulsadowski.com/wsh/cdo.htm

Split Spark Dataframe string column into multiple columns

Here's a solution to the general case that doesn't involve needing to know the length of the array ahead of time, using collect, or using udfs. Unfortunately this only works for spark version 2.1 and above, because it requires the posexplode function.

Suppose you had the following DataFrame:

df = spark.createDataFrame(
    [
        [1, 'A, B, C, D'], 
        [2, 'E, F, G'], 
        [3, 'H, I'], 
        [4, 'J']
    ]
    , ["num", "letters"]
)
df.show()
#+---+----------+
#|num|   letters|
#+---+----------+
#|  1|A, B, C, D|
#|  2|   E, F, G|
#|  3|      H, I|
#|  4|         J|
#+---+----------+

Split the letters column and then use posexplode to explode the resultant array along with the position in the array. Next use pyspark.sql.functions.expr to grab the element at index pos in this array.

import pyspark.sql.functions as f

df.select(
        "num",
        f.split("letters", ", ").alias("letters"),
        f.posexplode(f.split("letters", ", ")).alias("pos", "val")
    )\
    .show()
#+---+------------+---+---+
#|num|     letters|pos|val|
#+---+------------+---+---+
#|  1|[A, B, C, D]|  0|  A|
#|  1|[A, B, C, D]|  1|  B|
#|  1|[A, B, C, D]|  2|  C|
#|  1|[A, B, C, D]|  3|  D|
#|  2|   [E, F, G]|  0|  E|
#|  2|   [E, F, G]|  1|  F|
#|  2|   [E, F, G]|  2|  G|
#|  3|      [H, I]|  0|  H|
#|  3|      [H, I]|  1|  I|
#|  4|         [J]|  0|  J|
#+---+------------+---+---+

Now we create two new columns from this result. First one is the name of our new column, which will be a concatenation of letter and the index in the array. The second column will be the value at the corresponding index in the array. We get the latter by exploiting the functionality of pyspark.sql.functions.expr which allows us use column values as parameters.

df.select(
        "num",
        f.split("letters", ", ").alias("letters"),
        f.posexplode(f.split("letters", ", ")).alias("pos", "val")
    )\
    .drop("val")\
    .select(
        "num",
        f.concat(f.lit("letter"),f.col("pos").cast("string")).alias("name"),
        f.expr("letters[pos]").alias("val")
    )\
    .show()
#+---+-------+---+
#|num|   name|val|
#+---+-------+---+
#|  1|letter0|  A|
#|  1|letter1|  B|
#|  1|letter2|  C|
#|  1|letter3|  D|
#|  2|letter0|  E|
#|  2|letter1|  F|
#|  2|letter2|  G|
#|  3|letter0|  H|
#|  3|letter1|  I|
#|  4|letter0|  J|
#+---+-------+---+

Now we can just groupBy the num and pivot the DataFrame. Putting that all together, we get:

df.select(
        "num",
        f.split("letters", ", ").alias("letters"),
        f.posexplode(f.split("letters", ", ")).alias("pos", "val")
    )\
    .drop("val")\
    .select(
        "num",
        f.concat(f.lit("letter"),f.col("pos").cast("string")).alias("name"),
        f.expr("letters[pos]").alias("val")
    )\
    .groupBy("num").pivot("name").agg(f.first("val"))\
    .show()
#+---+-------+-------+-------+-------+
#|num|letter0|letter1|letter2|letter3|
#+---+-------+-------+-------+-------+
#|  1|      A|      B|      C|      D|
#|  3|      H|      I|   null|   null|
#|  2|      E|      F|      G|   null|
#|  4|      J|   null|   null|   null|
#+---+-------+-------+-------+-------+