Programs & Examples On #Pcx

PCX is an images file format that stands for Personal Computer eXchange. It uses run length encoding to achieve lossless compression.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For more performance: A simple change is observing that after n = 3n+1, n will be even, so you can divide by 2 immediately. And n won't be 1, so you don't need to test for it. So you could save a few if statements and write:

while (n % 2 == 0) n /= 2;
if (n > 1) for (;;) {
    n = (3*n + 1) / 2;
    if (n % 2 == 0) {
        do n /= 2; while (n % 2 == 0);
        if (n == 1) break;
    }
}

Here's a big win: If you look at the lowest 8 bits of n, all the steps until you divided by 2 eight times are completely determined by those eight bits. For example, if the last eight bits are 0x01, that is in binary your number is ???? 0000 0001 then the next steps are:

3n+1 -> ???? 0000 0100
/ 2  -> ???? ?000 0010
/ 2  -> ???? ??00 0001
3n+1 -> ???? ??00 0100
/ 2  -> ???? ???0 0010
/ 2  -> ???? ???? 0001
3n+1 -> ???? ???? 0100
/ 2  -> ???? ???? ?010
/ 2  -> ???? ???? ??01
3n+1 -> ???? ???? ??00
/ 2  -> ???? ???? ???0
/ 2  -> ???? ???? ????

So all these steps can be predicted, and 256k + 1 is replaced with 81k + 1. Something similar will happen for all combinations. So you can make a loop with a big switch statement:

k = n / 256;
m = n % 256;

switch (m) {
    case 0: n = 1 * k + 0; break;
    case 1: n = 81 * k + 1; break; 
    case 2: n = 81 * k + 1; break; 
    ...
    case 155: n = 729 * k + 425; break;
    ...
}

Run the loop until n = 128, because at that point n could become 1 with fewer than eight divisions by 2, and doing eight or more steps at a time would make you miss the point where you reach 1 for the first time. Then continue the "normal" loop - or have a table prepared that tells you how many more steps are need to reach 1.

PS. I strongly suspect Peter Cordes' suggestion would make it even faster. There will be no conditional branches at all except one, and that one will be predicted correctly except when the loop actually ends. So the code would be something like

static const unsigned int multipliers [256] = { ... }
static const unsigned int adders [256] = { ... }

while (n > 128) {
    size_t lastBits = n % 256;
    n = (n >> 8) * multipliers [lastBits] + adders [lastBits];
}

In practice, you would measure whether processing the last 9, 10, 11, 12 bits of n at a time would be faster. For each bit, the number of entries in the table would double, and I excect a slowdown when the tables don't fit into L1 cache anymore.

PPS. If you need the number of operations: In each iteration we do exactly eight divisions by two, and a variable number of (3n + 1) operations, so an obvious method to count the operations would be another array. But we can actually calculate the number of steps (based on number of iterations of the loop).

We could redefine the problem slightly: Replace n with (3n + 1) / 2 if odd, and replace n with n / 2 if even. Then every iteration will do exactly 8 steps, but you could consider that cheating :-) So assume there were r operations n <- 3n+1 and s operations n <- n/2. The result will be quite exactly n' = n * 3^r / 2^s, because n <- 3n+1 means n <- 3n * (1 + 1/3n). Taking the logarithm we find r = (s + log2 (n' / n)) / log2 (3).

If we do the loop until n = 1,000,000 and have a precomputed table how many iterations are needed from any start point n = 1,000,000 then calculating r as above, rounded to the nearest integer, will give the right result unless s is truly large.

configure: error: C compiler cannot create executables

If anyone is coming here because RVM / Ruby is creating issues (Middleman/Grunt) I've solved my issue.

PS. The answer by steroscott fixed my issue a while back...this time around not the case.

In my case rvm is trying to use a downloaded gcc via homebrew. I ran a brew uninstall of gcc (gcc46 for me) and reran the code for the ruby installation (old project old ruby v)

$ brew uninstall gcc46

$ rvm install 1.9.3

during that process of checking for requirements it automatically fetched a newer gcc for me and boom, all is working now. Oh a big note, the gcc install from the rvm command can take around 10-15 minutes without throwing out any text, it's not frozen :) Good luck

How do I decode a base64 encoded string?

The m000493 method seems to perform some kind of XOR encryption. This means that the same method can be used for both encrypting and decrypting the text. All you have to do is reverse m0001cd:

string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));

string result = m000493(p0, "_p0lizei.");
//    result == "gaia^unplugged^Ta..."

with return m0001cd(builder3.ToString()); changed to return builder3.ToString();.

Python base64 data decode

i used chardet to detect possible encoding of this data ( if its text ), but get {'confidence': 0.0, 'encoding': None}. Then i tried to use pickle.load and get nothing again. I tried to save this as file , test many different formats and failed here too. Maybe you tell us what type have this 16512 bytes of mysterious data?

Delegates in swift?

DELEGATES IN SWIFT 2

I am explaining with example of Delegate with two viewControllers.In this case, SecondVC Object is sending data back to first View Controller.

Class with Protocol Declaration

protocol  getDataDelegate  {
    func getDataFromAnotherVC(temp: String)
}


import UIKit
class SecondVC: UIViewController {

    var delegateCustom : getDataDelegate?
    override func viewDidLoad() {
        super.viewDidLoad()
     }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBAction func backToMainVC(sender: AnyObject) {
      //calling method defined in first View Controller with Object  
      self.delegateCustom?.getDataFromAnotherVC(temp: "I am sending data from second controller to first view controller.Its my first delegate example. I am done with custom delegates.")
        self.navigationController?.popViewControllerAnimated(true)
    }
    
}

In First ViewController Protocol conforming is done here:

class ViewController: UIViewController, getDataDelegate

Protocol method definition in First View Controller(ViewController)

func getDataFromAnotherVC(temp : String)
{
  // dataString from SecondVC
   lblForData.text = dataString
}

During push the SecondVC from First View Controller (ViewController)

let objectPush = SecondVC()
objectPush.delegateCustom = self
self.navigationController.pushViewController(objectPush, animated: true)

enabling cross-origin resource sharing on IIS7

I can't post comments so I have to put this in a separate answer, but it's related to the accepted answer by Shah.

I initially followed Shahs answer (thank you!) by re configuring the OPTIONSVerbHandler in IIS, but my settings were restored when I redeployed my application.

I ended up removing the OPTIONSVerbHandler in my Web.config instead.

<handlers>
    <remove name="OPTIONSVerbHandler"/>
</handlers>

remove inner shadow of text input

All browsers, including Safari (+ mobile):

input[type=text] {   
    /* Remove */
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    
    /* Optional */
    border: solid;
    box-shadow: none;
    /*etc.*/
}

CSS transition fade in

I believe you could addClass to the element. But either way you'd have to use Jquery or reg JS

div {
  opacity:0;
  transition:opacity 1s linear;*
}
div.SomeClass {
  opacity:1;
}

What is the "hasClass" function with plain JavaScript?

if (document.body.className.split(/\s+/).indexOf("thatClass") !== -1) {
    // has "thatClass"
}

JavaScript code to stop form submission

E.g if you have submit button on form ,inorder to stop its propogation simply write event.preventDefault(); in the function which is called upon clicking submit button or enter button.

UnicodeDecodeError when reading CSV file in Pandas with Python

I am using Jupyter-notebook. And in my case, it was showing the file in the wrong format. The 'encoding' option was not working. So I save the csv in utf-8 format, and it works.

How do I force a DIV block to extend to the bottom of a page even if it has no content?

Try playing around with the following css rule:

#content {
    min-height: 600px;
    height: auto !important;
    height: 600px;
}

Change the height to suit your page. height is mentioned twice for cross browser compatibility.

how can I display tooltip or item information on mouse over?

Use the title attribute while alt is important for SEO stuff.

apache and httpd running but I can't see my website

There are several possibilities.

  • firewall, iptables configuration
  • apache listen address / port

More information is needed about your configuration. What distro are you using? Can you connect via 127.0.0.1?

If the issue is with the firewall/iptables, you can add the following lines to /etc/sysconfig/iptables:

-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT

(Second line is only needed for https)

Make sure this is above any lines that would globally restrict access, like the following:

-A INPUT -j REJECT --reject-with icmp-host-prohibited

Tested on CentOS 6.3

And finally

service iptables restart

How do I display local image in markdown?

To add an image in markdown file the .md file and the image should be in the same directory. As in my case my .md file was in doc folder so i also moved the image into the same folder. After that write the following syntax in .md file

![alt text](filename)

like ![Car Image](car.png)

This has worked for me.

Where can I find the .apk file on my device, when I download any app and install?

You can use a file browser with an backup function, for example the ES File Explorer Long tap a item and select create backup

Opening database file from within SQLite command-line shell

I wonder why no one was able to get what the question actually asked. It stated What is the command within the SQLite shell tool to specify a database file?

A sqlite db is on my hard disk E:\ABCD\efg\mydb.db. How do I access it with sqlite3 command line interface? .open E:\ABCD\efg\mydb.db does not work. This is what question asked.

I found the best way to do the work is

  • copy-paste all your db files in 1 directory (say E:\ABCD\efg\mydbs)
  • switch to that directory in your command line
  • now open sqlite3 and then .open mydb.db

This way you can do the join operation on different tables belonging to different databases as well.

Laravel Soft Delete posts

In Laravel 5.5 Soft Deleted works ( for me ).

Data Base

deleted_at Field, default NULL value

Model

use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model {
    use SoftDeletes;
}

Controller

public function destroy($id)
{
    User::find($id)->delete();
}

How to use pip on windows behind an authenticating proxy

You may also run into problems with certificates from your proxy. There are plenty of answers here on how to retrieve your proxy's certificate.

On a Windows host, to allow pip to clear your proxy, you may want to set an environment variable such as:

PIP_CERT=C:\path\to\certificate\file\in\pem\form\myproxycert.pem

You can also use the --cert argument to PIP with the same result.

Performance differences between ArrayList and LinkedList

ArrayList

  • ArrayList is best choice if our frequent operation is retrieval operation.
  • ArrayList is worst choice if our operation is insertion and deletion in the middle because internally several shift operations are performed.
  • In ArrayList elements will be stored in consecutive memory locations hence retrieval operation will become easy.

LinkedList:-

  • LinkedList is best choice if our frequent operation is insertion and deletion in the middle.
  • LinkedList is worst choice is our frequent operation is retrieval operation.
  • In LinkedList the elements won't be stored in consecutive memory location and hence retrieval operation will be complex.

Now coming to your questions:-

1) ArrayList saves data according to indexes and it implements RandomAccess interface which is a marker interface that provides the capability of a Random retrieval to ArrayList but LinkedList doesn't implements RandomAccess Interface that's why ArrayList is faster than LinkedList.

2) The underlying data structure for LinkedList is doubly linked list so insertion and deletion in the middle is very easy in LinkedList as it doesn't have to shift each and every element for each and every deletion and insertion operations just like ArrayList(which is not recommended if our operation is insertion and deletion in the middle because internally several shift operations are performed).
Source

How to get HttpClient returning status code and response body?

You can avoid the BasicResponseHandler, but use the HttpResponse itself to get both status and response as a String.

HttpResponse response = httpClient.execute(get);

// Getting the status code.
int statusCode = response.getStatusLine().getStatusCode();

// Getting the response body.
String responseBody = EntityUtils.toString(response.getEntity());

Use of *args and **kwargs

One place where the use of *args and **kwargs is quite useful is for subclassing.

class Foo(object):
    def __init__(self, value1, value2):
        # do something with the values
        print value1, value2

class MyFoo(Foo):
    def __init__(self, *args, **kwargs):
        # do something else, don't care about the args
        print 'myfoo'
        super(MyFoo, self).__init__(*args, **kwargs)

This way you can extend the behaviour of the Foo class, without having to know too much about Foo. This can be quite convenient if you are programming to an API which might change. MyFoo just passes all arguments to the Foo class.

The zip() function in Python 3

Unlike in Python 2, the zip function in Python 3 returns an iterator. Iterators can only be exhausted (by something like making a list out of them) once. The purpose of this is to save memory by only generating the elements of the iterator as you need them, rather than putting it all into memory at once. If you want to reuse your zipped object, just create a list out of it as you do in your second example, and then duplicate the list by something like

 test2 = list(zip(lis1,lis2))
 zipped_list = test2[:]
 zipped_list_2 = list(test2)

How to remove provisioning profiles from Xcode

For XCode 9.3, the following steps worked for me.

  1. Go to Applications > Utilities > Keychain Access
  2. Under the login option on the left panel, find Apple Worldwide Developer Relations Certification Authority. Double click to get the options under it.
  3. Under the Trust option, change the When using this certificate option to Always trust .
  4. Exit the keychain access window, quit Xcode and restart Xcode. Rebuild the application. It should work now.

Exit codes in Python

Operating system commands have exit codes. Look for Linux exit codes to see some material on this. The shell uses the exit codes to decide if the program worked, had problems, or failed. There are some efforts to create standard (or at least commonly-used) exit codes. See this Advanced Shell Script posting.

How to use pagination on HTML tables?

Pure js. Can apply it to multiple tables at once. Aborts if only one page is required. I used anushree as my starting point.

Sorry to the asker, obviously this is not a simplePagignation.js solution. However, it's the top google result when you type "javascript table paging", and it's a reasonable solution to many who may be considering a library but unsure whether to go that route or not.

Use like this:

addPagerToTables('#someTable', 8);

Requires no css, though it may be wise to initially hide table tBody rows in css anyway to prevent the effect of rows showing then quicky being hidden (not happening with me right now, but it's something I've seen before).

The code:

function addPagerToTables(tables, rowsPerPage = 10) {

    tables = 
        typeof tables == "string"
      ? document.querySelectorAll(tables)
      : tables;

    for (let table of tables) 
        addPagerToTable(table, rowsPerPage);

}

function addPagerToTable(table, rowsPerPage = 10) {

    let tBodyRows = table.querySelectorAll('tBody tr');
    let numPages = Math.ceil(tBodyRows.length/rowsPerPage);

    let colCount = 
    [].slice.call(
        table.querySelector('tr').cells
    )
    .reduce((a,b) => a + parseInt(b.colSpan), 0);

    table
    .createTFoot()
    .insertRow()
    .innerHTML = `<td colspan=${colCount}><div class="nav"></div></td>`;

    if(numPages == 1)
        return;

    for(i = 0;i < numPages;i++) {

        let pageNum = i + 1;

        table.querySelector('.nav')
        .insertAdjacentHTML(
            'beforeend',
            `<a href="#" rel="${i}">${pageNum}</a> `        
        );

    }

    changeToPage(table, 1, rowsPerPage);

    for (let navA of table.querySelectorAll('.nav a'))
        navA.addEventListener(
            'click', 
            e => changeToPage(
                table, 
                parseInt(e.target.innerHTML), 
                rowsPerPage
            )
        );

}

function changeToPage(table, page, rowsPerPage) {

    let startItem = (page - 1) * rowsPerPage;
    let endItem = startItem + rowsPerPage;
    let navAs = table.querySelectorAll('.nav a');
    let tBodyRows = table.querySelectorAll('tBody tr');

    for (let nix = 0; nix < navAs.length; nix++) {

        if (nix == page - 1)
            navAs[nix].classList.add('active');
        else 
            navAs[nix].classList.remove('active');

        for (let trix = 0; trix < tBodyRows.length; trix++) 
            tBodyRows[trix].style.display = 
                (trix >= startItem && trix < endItem)
                ? 'table-row'
                : 'none';  

    }

}

Android: How can I validate EditText input?

If you want nice validation popups and images when an error occurs you can use the setError method of the EditText class as I describe here

Screenshot of the use of setError taken from Donn Felker, the author of the linked post

How do I access call log for android?

use this method from everywhere with a context

private static String getCallDetails(Context context) {
    StringBuffer stringBuffer = new StringBuffer();
    Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,
            null, null, null, CallLog.Calls.DATE + " DESC");
    int number = cursor.getColumnIndex(CallLog.Calls.NUMBER);
    int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
    int date = cursor.getColumnIndex(CallLog.Calls.DATE);
    int duration = cursor.getColumnIndex(CallLog.Calls.DURATION);       
    while (cursor.moveToNext()) {
        String phNumber = cursor.getString(number);
        String callType = cursor.getString(type);
        String callDate = cursor.getString(date);
        Date callDayTime = new Date(Long.valueOf(callDate));
        String callDuration = cursor.getString(duration);
        String dir = null;
        int dircode = Integer.parseInt(callType);
        switch (dircode) {
        case CallLog.Calls.OUTGOING_TYPE:
            dir = "OUTGOING";
            break;
        case CallLog.Calls.INCOMING_TYPE:
            dir = "INCOMING";
            break;

        case CallLog.Calls.MISSED_TYPE:
            dir = "MISSED";
            break;
        }
        stringBuffer.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
                + dir + " \nCall Date:--- " + callDayTime
                + " \nCall duration in sec :--- " + callDuration);
        stringBuffer.append("\n----------------------------------");
    }
    cursor.close();
    return stringBuffer.toString();
}

How do I remove a comma off the end of a string?

I had a pesky "invisible" space at the end of my string and had to do this

 $update_sql=rtrim(trim($update_sql),',');

But a solution above is better

 $update_sql=rtrim($update_sql,', ');

jquery find closest previous sibling with class

Try

$('li.current_sub').prev('.par_cat').[do stuff];

SELECT DISTINCT on one column

I know it was asked over 6 years ago, but knowledge is still knowledge. This is different solution than all above, as I had to run it under SQL Server 2000:

DECLARE @TestData TABLE([ID] int, [SKU] char(6), [Product] varchar(15))
INSERT INTO @TestData values (1 ,'FOO-23', 'Orange')
INSERT INTO @TestData values (2 ,'BAR-23', 'Orange')
INSERT INTO @TestData values (3 ,'FOO-24', 'Apple')
INSERT INTO @TestData values (4 ,'FOO-25', 'Orange')

SELECT DISTINCT  [ID] = ( SELECT TOP 1 [ID]  FROM @TestData Y WHERE Y.[Product] = X.[Product])
                ,[SKU]= ( SELECT TOP 1 [SKU] FROM @TestData Y WHERE Y.[Product] = X.[Product])
                ,[PRODUCT] 
            FROM @TestData X  

How to set the 'selected option' of a select dropdown list with jquery

The match between .val('Bruce jones') and value="Bruce Jones" is case-sensitive. It looks like you're capitalizing Jones in one but not the other. Either track down where the difference comes from, use id's instead of the name, or call .toLowerCase() on both.

IOPub data rate exceeded in Jupyter notebook (when viewing image)

Removing print statements can also fix the problem.

Apart from loading images, this error also happens when your code is printing continuously at a high rate, which is causing the error "IOPub data rate exceeded". E.g. if you have a print statement in a for loop somewhere that is being called over 1000 times.

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

Session 'app' error while installing APK

Try to this way :

1) In Instance Run is Enable then desable it. 2) Save it and Rebuild the project. 3) Check devices is online or USB debugging On your device. 4) Then Run It App On your devices.

Note :

If you use mobile device is MI (Xiaomi) Then Check : => setting>Additional setting> Developer options> Install via USB (ON it) => setting>Additional setting> Developer options> USB debugging (ON it) => setting>Additional setting> Developer options> Verify apps over USB (ON/Off it)

Passing a variable to a powershell script via command line

Make this in your test.ps1, at the first line

param(
[string]$a
)

Write-Host $a

Then you can call it with

./Test.ps1 "Here is your text"

Found here (English)

Disable automatic sorting on the first column when using jQuery DataTables

If any of other solution doesn't fix it, try to override the styles to hide the sort togglers:

.sorting_asc:after, .sorting_desc:after {
  content: "";
}

Resolve host name to an ip address

This is hard to answer without more detail about the network architecture. Some things to investigate are:

  • Is it possible that client and/or server is behind a NAT device, a firewall, or similar?
  • Is any of the IP addresses involved a "local" address, like 192.168.x.y or 10.x.y.z?
  • What are the host names, are they "real" DNS:able names or something more local and/or Windows-specific?
  • How does the client look up the server? There must be a place in code or config data that holds the host name, simply try using the IP there instead if you want to avoid the lookup.

How do you discover model attributes in Rails?

To describe model I use following snippet

Model.columns.collect { |c| "#{c.name} (#{c.type})" }

Again this is if you are looking pretty print to describe you ActiveRecord without you going trough migrations or hopping that developer before you was nice enough to comment in attributes.

ReactJS: "Uncaught SyntaxError: Unexpected token <"

I have the same issue with you and I have change something in my server

you might try this

const root = require("path").join(__dirname, "./build");
app.use(express.static(root));
app.get("*", (req, res) => {
  res.sendFile("index.html", { root });
});

How to construct a relative path in Java from two absolute paths (or URLs)?

I'm assuming you have fromPath (an absolute path for a folder), and toPath (an absolute path for a folder/file), and your're looking for a path that with represent the file/folder in toPath as a relative path from fromPath (your current working directory is fromPath) then something like this should work:

public static String getRelativePath(String fromPath, String toPath) {

  // This weirdness is because a separator of '/' messes with String.split()
  String regexCharacter = File.separator;
  if (File.separatorChar == '\\') {
    regexCharacter = "\\\\";
  }

  String[] fromSplit = fromPath.split(regexCharacter);
  String[] toSplit = toPath.split(regexCharacter);

  // Find the common path
  int common = 0;
  while (fromSplit[common].equals(toSplit[common])) {
    common++;
  }

  StringBuffer result = new StringBuffer(".");

  // Work your way up the FROM path to common ground
  for (int i = common; i < fromSplit.length; i++) {
    result.append(File.separatorChar).append("..");
  }

  // Work your way down the TO path
  for (int i = common; i < toSplit.length; i++) {
    result.append(File.separatorChar).append(toSplit[i]);
  }

  return result.toString();
}

How to append new data onto a new line

If you want a newline, you have to write one explicitly. The usual way is like this:

hs.write(name + "\n")

This uses a backslash escape, \n, which Python converts to a newline character in string literals. It just concatenates your string, name, and that newline character into a bigger string, which gets written to the file.

It's also possible to use a multi-line string literal instead, which looks like this:

"""
"""

Or, you may want to use string formatting instead of concatenation:

hs.write("{}\n".format(name))

All of this is explained in the Input and Output chapter in the tutorial.

How to set column widths to a jQuery datatable?

Configuration Options:

$(document).ready(function () {

  $("#companiesTable").dataTable({
    "sPaginationType": "full_numbers",
    "bJQueryUI": true,
    "bAutoWidth": false, // Disable the auto width calculation 
    "aoColumns": [
      { "sWidth": "30%" }, // 1st column width 
      { "sWidth": "30%" }, // 2nd column width 
      { "sWidth": "40%" } // 3rd column width and so on 
    ]
  });
});

Specify the css for the table:

table.display {
  margin: 0 auto;
  width: 100%;
  clear: both;
  border-collapse: collapse;
  table-layout: fixed;         // add this 
  word-wrap:break-word;        // add this 
}

HTML:

<table id="companiesTable" class="display"> 
  <thead>
    <tr>
      <th>Company name</th>
      <th>Address</th>
      <th>Town</th>
    </tr>
  </thead>
  <tbody>

    <% for(Company c: DataRepository.GetCompanies()){ %>
      <tr>  
        <td><%=c.getName()%></td>
        <td><%=c.getAddress()%></td>
        <td><%=c.getTown()%></td>
      </tr>
    <% } %>

  </tbody>
</table>

It works for me!

All ASP.NET Web API controllers return 404

I'm a bit stumped, not sure if this was due to an HTTP output caching issue.

Anyways, "all of a sudden it started working properly". :/ So, the example above worked without me adding or changing anything.

Guess the code just had to sit and cook overnight... :)

Thanks for helping, guys!

select2 - hiding the search box

Version 4.0.3

Try not to mix user interface requirements with your JavaScript code.

You can hide the search box in the markup with the attribute:

data-minimum-results-for-search="Infinity"

Markup

<select class="select2" data-minimum-results-for-search="Infinity"></select>

Example

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".select2").select2();_x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>_x000D_
_x000D_
<label>without search box</label>_x000D_
<select class="select2" data-width="100%" data-minimum-results-for-search="Infinity">_x000D_
  <option>one</option>_x000D_
  <option>two</option>_x000D_
</select>_x000D_
_x000D_
<label>with search box</label>_x000D_
<select class="select2" data-width="100%">_x000D_
  <option>one</option>_x000D_
  <option>two</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Recover sa password

best answer written by Dmitri Korotkevitch:

Speaking of the installation, SQL Server 2008 allows you to set authentication mode (Windows or SQL Server) during the installation process. You will be forced to choose the strong password for sa user in the case if you choose sql server authentication mode during setup.

If you install SQL Server with Windows Authentication mode and want to change it, you need to do 2 different things:

  1. Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode

  2. Go to security/logins, open SA login properties

a. Uncheck "Enforce password policy" and "Enforce password expiration" check box there if you decide to use weak password

b. Assign password to SA user

c. Open "Status" tab and enable login.

I don't need to mention that every action from above would violate security best practices that recommend to use windows authentication mode, have sa login disabled and use strong passwords especially for sa login.

close fancy box from function from within open 'fancybox'

It is no use putting the .fn, it will reffers to the prototype.
What you need to do is $.fancybox.close();

The thing is that you are maybe experiencing another error from js.
There are any errors on screen?
Is your fancybox and jquery the latest releases? jquery is currently in 1.4.1 and fb in 1.3 something

Experiment putting a link inside the fancybox and put that function in it.

You probably had read that, but in any case, http://fancybox.net/api

One thing that you probably might need to do is isolate each part in order to realize what it is.

Batch file to run a command in cmd within a directory

Chain arbitrary commands using & like this:

command1 & command2 & command3 & ...

Thus, in your particular case, put this line in a batch file on your desktop:

START cmd.exe /k "cd C:\activiti-5.9\setup & ant demo.start"

You can also use && to chain commands, albeit this will perform error checking and the execution chain will break if one of the commands fails. The behaviour is detailed here.

Edit: Intrigued by @James K's comment "You CAN chain the commands, but they will have no effect", I tested some more and to my surprise discovered, that the program I was starting in my original test - firefox.exe - while not existing in a directory in the PATH environment variable, is actually executable anywhere on my system (which really made me wonder - see bottom of answer for explanation). So in fact executing...

START cmd.exe /k "cd C:\progra~1\mozill~1 && firefox"

...didn't prove the solution was working. So I chose another program (nLite) after making sure that it was not executable anywhere on my system:

START cmd.exe /k "cd C:\progra~1\nlite && nlite"

And that works just as my original answer already suggested. A Windows version is not given in the question, but I'm using Windows XP, btw.


If anybody is interested why firefox.exe, while not being in PATH, is executable anywhere on my system - and very probably on yours as well - this is due to a registry key where applications can be registered to be available everywhere. See this SU answer for details.

how to set the default value to the drop down list control?

Assuming that the DropDownList control in the other table also contains DepartmentName and DepartmentID:

lstDepartment.ClearSelection();

foreach (var item in lstDepartment.Items) 
{
  if (item.Value == otherDropDownList.SelectedValue)
  {
    item.Selected = true;
  }
}

How to add button in ActionBar(Android)?

An activity populates the ActionBar in its onCreateOptionsMenu() method.

Instead of using setcustomview(), just override onCreateOptionsMenu like this:

@Override    
public boolean onCreateOptionsMenu(Menu menu) {
  MenuInflater inflater = getMenuInflater();
  inflater.inflate(R.menu.mainmenu, menu);
  return true;
}

If an actions in the ActionBar is selected, the onOptionsItemSelected() method is called. It receives the selected action as parameter. Based on this information you code can decide what to do for example:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
    case R.id.menuitem1:
      Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show();
      break;
    case R.id.menuitem2:
      Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT).show();
      break;
  }
  return true;
}

Is there a way to delete all the data from a topic or delete the topic before every run?

  1. Stop ZooKeeper and Kafka
  2. In server.properties, change log.retention.hours value. You can comment log.retention.hours and add log.retention.ms=1000. It would keep the record on Kafka Topic for only one second.
  3. Start zookeeper and kafka.
  4. Check on consumer console. When I opened the console for the first time, record was there. But when I opened the console again, the record was removed.
  5. Later on, you can set the value of log.retention.hours to your desired figure.

How do I connect to this localhost from another computer on the same network?

This is a side note if one still can't access localhost from another devices after following through the step above. This might be due to the apache ports.conf has been configured to serve locally (127.0.0.1) and not to outside.

check the following, (for ubuntu apache2)

  $ cat /etc/apache2/ports.conf

if the following is set,

NameVirtualHost *:80  
Listen 127.0.0.1:80  

then change it back to default value

NameVirtualHost *:80  
Listen 80  

How to randomly pick an element from an array

You can use the Random generator to generate a random index and return the element at that index:

//initialization
Random generator = new Random();
int randomIndex = generator.nextInt(myArray.length);
return myArray[randomIndex];

Check if passed argument is file or directory in Bash

Using the "file" command may be useful for this:

#!/bin/bash
check_file(){

if [ -z "${1}" ] ;then
 echo "Please input something"
 return;
fi

f="${1}"
result="$(file $f)"
if [[ $result == *"cannot open"* ]] ;then
        echo "NO FILE FOUND ($result) ";
elif [[ $result == *"directory"* ]] ;then
        echo "DIRECTORY FOUND ($result) ";
else
        echo "FILE FOUND ($result) ";
fi

}

check_file "${1}"

Output examples :

$ ./f.bash login
DIRECTORY FOUND (login: directory) 
$ ./f.bash ldasdas
NO FILE FOUND (ldasdas: cannot open `ldasdas' (No such file or  directory)) 
$ ./f.bash evil.php 
FILE FOUND (evil.php: PHP script, ASCII text) 

FYI: the answers above work but you can use -s to help in weird situations by checking for a valid file first:

#!/bin/bash

check_file(){
    local file="${1}"
    [[ -s "${file}" ]] || { echo "is not valid"; return; } 
    [[ -d "${file}" ]] && { echo "is a directory"; return; }
    [[ -f "${file}" ]] && { echo "is a file"; return; }
}

check_file ${1}

Parse XLSX with Node and create json

Improved Version of "Josh Marinacci" answer , it will read beyond Z column (i.e. AA1).

var XLSX = require('xlsx');
var workbook = XLSX.readFile('test.xlsx');
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function(y) {
    var worksheet = workbook.Sheets[y];
    var headers = {};
    var data = [];
    for(z in worksheet) {
        if(z[0] === '!') continue;
        //parse out the column, row, and value
        var tt = 0;
        for (var i = 0; i < z.length; i++) {
            if (!isNaN(z[i])) {
                tt = i;
                break;
            }
        };
        var col = z.substring(0,tt);
        var row = parseInt(z.substring(tt));
        var value = worksheet[z].v;

        //store header names
        if(row == 1 && value) {
            headers[col] = value;
            continue;
        }

        if(!data[row]) data[row]={};
        data[row][headers[col]] = value;
    }
    //drop those first two rows which are empty
    data.shift();
    data.shift();
    console.log(data);
});

What's the difference between window.location and document.location in JavaScript?

The canonical way to get the current location object is window.location (see this MSDN page from 1996 and the W3C draft from 2006).

Compare this to document.location, which originally only returned the current URL as a string (see this page on MSDN). Probably to avoid confusion, document.location was replaced with document.URL (see here on MSDN), which is also part of DOM Level 1.

As far as I know, all modern browsers map document.location to window.location, but I still prefer window.location as that's what I've used since I wrote my first DHTML.

Can you recommend a free light-weight MySQL GUI for Linux?

Why not try MySQL GUI Tools? It's light, and does its job well.

How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

Additional to the main answer I needed to remove all npm instances found in:

rm -rf /usr/local/share/man/man1/npm*

C#: Waiting for all threads to complete

I was tying to figure out how to do this but i could not get any answers from google. I know this is an old thread but here was my solution:

Use the following class:

class ThreadWaiter
    {
        private int _numThreads = 0;
        private int _spinTime;

        public ThreadWaiter(int SpinTime)
        {
            this._spinTime = SpinTime;
        }

        public void AddThreads(int numThreads)
        {
            _numThreads += numThreads;
        }

        public void RemoveThread()
        {
            if (_numThreads > 0)
            {
                _numThreads--;
            }
        }

        public void Wait()
        {
            while (_numThreads != 0)
            {
                System.Threading.Thread.Sleep(_spinTime);
            }
        }
    }
  1. Call Addthreads(int numThreads) before executing a thread(s).
  2. Call RemoveThread() after each one has completed.
  3. Use Wait() at the point that you want to wait for all the threads to complete before continuing

Matrix Transpose in Python

If your rows are not equal you can also use map:

>>> uneven = [['a','b','c'],['d','e'],['g','h','i']]
>>> map(None,*uneven)
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', None, 'i')]

Edit: In Python 3 the functionality of map changed, itertools.zip_longest can be used instead:
Source: What’s New In Python 3.0

>>> import itertools
>>> uneven = [['a','b','c'],['d','e'],['g','h','i']]
>>> list(itertools.zip_longest(*uneven))
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', None, 'i')]

cordova Android requirements failed: "Could not find an installed version of Gradle"

Run in terminal:

$ sudo apt-get update
$ sudo apt-get install gradle

This works for me in Ubuntu 18.04

Bundler: Command not found

My problem was that I did:

sudo gem install bundler

So I had installed as root rather than as myself. So I uninstalled as root, then installed as myself:

sudo gem uninstall bundler
gem install bundler
rbenv rehash

(last command for if you are using rbenv)

And it worked. The "correct" path was in .bashrc (or other shell profile), at least according to

$PATH
=> zsh: /Users/myself/.rbenv/shims:/Users/myself/.rbenv/bin: ... etc

but it was expecting it to be installed for myself - not for root. In my case, its rightful installation place is in ~/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/bundler

When should I use a struct rather than a class in C#?

I was just dealing with Windows Communication Foundation [WCF] Named Pipe and I did notice that it does make sense to use Structs in order to ensure that exchange of data is of value type instead of reference type.

How do I deal with "signed/unsigned mismatch" warnings (C4018)?

It's all in your things.size() type. It isn't int, but size_t (it exists in C++, not in C) which equals to some "usual" unsigned type, i.e. unsigned int for x86_32.

Operator "less" (<) cannot be applied to two operands of different sign. There's just no such opcodes, and standard doesn't specify, whether compiler can make implicit sign conversion. So it just treats signed number as unsigned and emits that warning.

It would be correct to write it like

for (size_t i = 0; i < things.size(); ++i) { /**/ }

or even faster

for (size_t i = 0, ilen = things.size(); i < ilen; ++i) { /**/ }

Indexing vectors and arrays with +:

This is another way to specify the range of the bit-vector.

x +: N, The start position of the vector is given by x and you count up from x by N.

There is also

x -: N, in this case the start position is x and you count down from x by N.

N is a constant and x is an expression that can contain iterators.

It has a couple of benefits -

  1. It makes the code more readable.

  2. You can specify an iterator when referencing bit-slices without getting a "cannot have a non-constant value" error.

Left function in c#

It sounds like you're asking about a function

string Left(string s, int left)

that will return the leftmost left characters of the string s. In that case you can just use String.Substring. You can write this as an extension method:

public static class StringExtensions
{
    public static string Left(this string value, int maxLength)
    {
        if (string.IsNullOrEmpty(value)) return value;
        maxLength = Math.Abs(maxLength);

        return ( value.Length <= maxLength 
               ? value 
               : value.Substring(0, maxLength)
               );
    }
}

and use it like so:

string left = s.Left(number);

For your specific example:

string s = fac.GetCachedValue("Auto Print Clinical Warnings").ToLower() + " ";
string left = s.Substring(0, 1);

Doctrine and LIKE query

This is not possible with the magic find methods. Try using the query builder:

$result = $em->getRepository("Orders")->createQueryBuilder('o')
   ->where('o.OrderEmail = :email')
   ->andWhere('o.Product LIKE :product')
   ->setParameter('email', '[email protected]')
   ->setParameter('product', 'My Products%')
   ->getQuery()
   ->getResult();

Show just the current branch in Git

From what I can tell, there is no way to natively show just the current branch in Git, so I have been using:

git branch | grep '*'

JavaFX FXML controller - constructor vs initialize method

In a few words: The constructor is called first, then any @FXML annotated fields are populated, then initialize() is called.

This means the constructor does not have access to @FXML fields referring to components defined in the .fxml file, while initialize() does have access to them.

Quoting from the Introduction to FXML:

[...] the controller can define an initialize() method, which will be called once on an implementing controller when the contents of its associated document have been completely loaded [...] This allows the implementing class to perform any necessary post-processing on the content.

ReferenceError: document is not defined (in plain JavaScript)

Try adding the script element just before the /body tag like that

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="css/quiz.css" />
</head>
<body>

    <div id="divid">Next</div>
    <script type="text/javascript" src="js/quiz.js"></script>
</body>
</html>

How do I debug Node.js applications?

There is the new open-source Nodeclipse project (as a Eclipse plugin or Enide Studio):

Nodeclipse became #1 in Eclipse Top 10 NEW Plugins for 2013. It uses a modified V8 debugger (from Google Chrome Developer Tools for Java).

Nodeclipse is free open-source software released at the start of every month.

WPF User Control Parent

How about this:

DependencyObject parent = ExVisualTreeHelper.FindVisualParent<UserControl>(this);

public static class ExVisualTreeHelper
{
    /// <summary>
    /// Finds the visual parent.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="sender">The sender.</param>
    /// <returns></returns>
    public static T FindVisualParent<T>(DependencyObject sender) where T : DependencyObject
    {
        if (sender == null)
        {
            return (null);
        }
        else if (VisualTreeHelper.GetParent(sender) is T)
        {
            return (VisualTreeHelper.GetParent(sender) as T);
        }
        else
        {
            DependencyObject parent = VisualTreeHelper.GetParent(sender);
            return (FindVisualParent<T>(parent));
        }
    } 
}

How do you check in python whether a string contains only numbers?

you can use str.isdigit() method or str.isnumeric() method

SQL Query for Logins

Have a look in the syslogins or sysusers tables in the master schema. Not sure if this still still around in more recent MSSQL versions though. In MSSQL 2005 there are views called sys.syslogins and sys.sysusers.

Postgres DB Size Command

Yes, there is a command to find the size of a database in Postgres. It's the following:

SELECT pg_database.datname as "database_name", pg_size_pretty(pg_database_size(pg_database.datname)) AS size_in_mb FROM pg_database ORDER by size_in_mb DESC;

Summarizing multiple columns with dplyr?

We can summarize by using summarize_at, summarize_all and summarize_if on dplyr 0.7.4. We can set the multiple columns and functions by using vars and funs argument as below code. The left-hand side of funs formula is assigned to suffix of summarized vars. In the dplyr 0.7.4, summarise_each(and mutate_each) is already deprecated, so we cannot use these functions.

options(scipen = 100, dplyr.width = Inf, dplyr.print_max = Inf)

library(dplyr)
packageVersion("dplyr")
# [1] ‘0.7.4’

set.seed(123)
df <- data_frame(
  a = sample(1:5, 10, replace=T), 
  b = sample(1:5, 10, replace=T), 
  c = sample(1:5, 10, replace=T), 
  d = sample(1:5, 10, replace=T), 
  grp = as.character(sample(1:3, 10, replace=T)) # For convenience, specify character type
)

df %>% group_by(grp) %>% 
  summarise_each(.vars = letters[1:4],
                 .funs = c(mean="mean"))
# `summarise_each()` is deprecated.
# Use `summarise_all()`, `summarise_at()` or `summarise_if()` instead.
# To map `funs` over a selection of variables, use `summarise_at()`
# Error: Strings must match column names. Unknown columns: mean

You should change to the following code. The following codes all have the same result.

# summarise_at
df %>% group_by(grp) %>% 
  summarise_at(.vars = letters[1:4],
               .funs = c(mean="mean"))

df %>% group_by(grp) %>% 
  summarise_at(.vars = names(.)[1:4],
               .funs = c(mean="mean"))

df %>% group_by(grp) %>% 
  summarise_at(.vars = vars(a,b,c,d),
               .funs = c(mean="mean"))

# summarise_all
df %>% group_by(grp) %>% 
  summarise_all(.funs = c(mean="mean"))

# summarise_if
df %>% group_by(grp) %>% 
  summarise_if(.predicate = function(x) is.numeric(x),
               .funs = funs(mean="mean"))
# A tibble: 3 x 5
# grp a_mean b_mean c_mean d_mean
# <chr>  <dbl>  <dbl>  <dbl>  <dbl>
# 1     1   2.80   3.00    3.6   3.00
# 2     2   4.25   2.75    4.0   3.75
# 3     3   3.00   5.00    1.0   2.00

You can also have multiple functions.

df %>% group_by(grp) %>% 
  summarise_at(.vars = letters[1:2],
               .funs = c(Mean="mean", Sd="sd"))
# A tibble: 3 x 5
# grp a_Mean b_Mean      a_Sd     b_Sd
# <chr>  <dbl>  <dbl>     <dbl>    <dbl>
# 1     1   2.80   3.00 1.4832397 1.870829
# 2     2   4.25   2.75 0.9574271 1.258306
# 3     3   3.00   5.00        NA       NA

Detect all Firefox versions in JS

This will detect any version of Firefox:

var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;

more specifically:

if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1){
     // Do Firefox-related activities
}

You may want to consider using feature-detection ala Modernizr, or a related tool, to accomplish what you need.

Is it possible to cast a Stream in Java 8?

Along the lines of ggovan's answer, I do this as follows:

/**
 * Provides various high-order functions.
 */
public final class F {
    /**
     * When the returned {@code Function} is passed as an argument to
     * {@link Stream#flatMap}, the result is a stream of instances of
     * {@code cls}.
     */
    public static <E> Function<Object, Stream<E>> instancesOf(Class<E> cls) {
        return o -> cls.isInstance(o)
                ? Stream.of(cls.cast(o))
                : Stream.empty();
    }
}

Using this helper function:

Stream.of(objects).flatMap(F.instancesOf(Client.class))
        .map(Client::getId)
        .forEach(System.out::println);

CSS, Images, JS not loading in IIS

I had a similar error, my console looked like this:

error

My problem was that I was running my site in a sub folder since the company was using one top domain and no sub domains. Like this:

host.com/app1

host.com/app2

My code looked like this for including scripts which worked fine on localhost but not in app1 or app2:

<link rel="stylesheet" type="text/css" href="/Content/css/font-awesome.min.css" />

Added a tilde sign ~ to src and then everything worked:

<link rel="stylesheet" type="text/css" href="~/Content/css/font-awesome.min.css" />

Explanation of ~ vs /:

  • / - Site root
  • ~/ - Root directory of the application

/ will return the root of the site (http://host.com/),

~/ will return the root of the application (http://host.com/app1/).

Make code in LaTeX look *nice*

The listings package is quite nice and very flexible (e.g. different sizes for comments and code).

Laravel assets url

Besides put all your assets in the public folder, you can use the HTML::image() Method, and only needs an argument which is the path to the image, relative on the public folder, as well:

{{ HTML::image('imgs/picture.jpg') }}

Which generates the follow HTML code:

<img src="http://localhost:8000/imgs/picture.jpg">

The link to other elements of HTML::image() Method: http://laravel-recipes.com/recipes/185/generating-an-html-image-element

How to write to a file without overwriting current contents?

Instead of "w" use "a" (append) mode with open function:

with open("games.txt", "a") as text_file:

Can I add a custom attribute to an HTML tag?

_x000D_
_x000D_
var demo = document.getElementById("demo")_x000D_
console.log(demo.dataset.myvar)_x000D_
// or_x000D_
alert(demo.dataset.myvar)_x000D_
//this will show in console the value of myvar
_x000D_
<div id="demo" data-myvar="foo">anything</div>
_x000D_
_x000D_
_x000D_

How to get a certain element in a list, given the position?

Not very efficient, but if you must use a list, you can deference the iterator

*myList.begin()+N

How do I debug a stand-alone VBScript script?

This is for future readers. I found that the simplest method for me was to use Visual Studio -> Tools -> External Tools. More details in this answer.

Easier to use and good debugging tools.

DB2 Timestamp select statement

@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000

If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:

...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'

or

...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06' 
   AND usagetime < '2012-09-03 08:03:07'

HTML entity for the middle dot

Do you mean bulletpoints? • • •

&bull;

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

TLDR:

  1. Rebooting both application and DB servers is the quickest fix where data volume, network settings and code haven't changed. We always do so as a rule
  2. May be indicator of failing hard-drive that needs replacement - check system notifications

I have often encountered this error for various reasons and have had various solutions, including:

  1. refactoring my code to use SqlBulkCopy
  2. increasing Timeout values, as stated in various answers or checking for underlying causes (may not be data related)
  3. Connection Timeout (Default 15s) - How long it takes to wait for a connection to be established with the SQL server before terminating - TCP/PORT related - can go through a troubleshooting checklist (very handy MSDN article)
  4. Command Timeout (Default 30s) - How long it takes to wait for the execution of a query - Query execution/network traffic related - also has a troubleshooting process (another very handy MSDN article)
  5. Rebooting of the server(s) - both application & DB Server (if separate) - where code and data haven't changed, environment must have changed - First thing you must do. Typically caused by patches (operating system, .Net Framework or SQL Server patches or updates). Particularly if timeout exception appears as below (even if we do not use Azure):
    • System.Data.Entity.Core.EntityException: An exception has been raised that is likely due to a transient failure. If you are connecting to a SQL Azure database consider using SqlAzureExecutionStrategy. ---> System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.Data.SqlClient.SqlException: A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The semaphore timeout period has expired.) ---> System.ComponentModel.Win32Exception: The semaphore timeout period has expired

Clear all fields in a form upon going back with browser back button

This is what worked for me.

$(window).bind("pageshow", function() {
    $("#id").val('');
    $("#another_id").val('');
});

I initially had this in the $(document).ready section of my jquery, which also worked. However, I heard that not all browsers fire $(document).ready on hitting back button, so I took it out. I don't know the pros and cons of this approach, but I have tested on multiple browsers and on multiple devices, and no issues with this solution were found.

Stop UIWebView from "bouncing" vertically?

(Xcode 5 iOS 7 SDK example) Here is a Universal App example using the scrollview setBounces function. It is an open source project / example located here: Link to SimpleWebView (Project Zip and Source Code Example)

How to append data to a json file?

You can simply import the data from the source file, read it, and save what you want to append to a variable. Then open the destination file, assign the list data inside to a new variable (presumably this will all be valid JSON), then use the 'append' function on this list variable and append the first variable to it. Viola, you have appended to the JSON list. Now just overwrite your destination file with the newly appended list (as JSON).

The 'a' mode in your 'open' function will not work here because it will just tack everything on to the end of the file, which will make it non-valid JSON format.

mongod command not recognized when trying to connect to a mongodb server

Apart from having a Path variable, the directory C:\data\db is mandatory.

Create this and the error shall be solved.

How to use onClick with divs in React.js

Your box doesn't have a size. If you set the width and height, it works just fine:

_x000D_
_x000D_
var Box = React.createClass({_x000D_
    getInitialState: function() {_x000D_
        return {_x000D_
            color: 'black'_x000D_
        };_x000D_
    },_x000D_
_x000D_
    changeColor: function() {_x000D_
        var newColor = this.state.color == 'white' ? 'black' : 'white';_x000D_
        this.setState({_x000D_
            color: newColor_x000D_
        });_x000D_
    },_x000D_
_x000D_
    render: function() {_x000D_
        return (_x000D_
            <div>_x000D_
                <div_x000D_
                    style = {{_x000D_
                        background: this.state.color,_x000D_
                        width: 100,_x000D_
                        height: 100_x000D_
                    }}_x000D_
                    onClick = {this.changeColor}_x000D_
                >_x000D_
                </div>_x000D_
            </div>_x000D_
        );_x000D_
    }_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
  <Box />,_x000D_
  document.getElementById('box')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<div id='box'></div>
_x000D_
_x000D_
_x000D_

Get value of c# dynamic property via string

In .Net core 3.1 you can try like this

d?.value2 , d?.value3

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

Your ComboBox is trying to bind to bind to GridItem[x].CompanyItems, which doesn't exist.

Your RelativeBinding is close, however it needs to bind to DataContext.CompanyItems because Window.CompanyItems does not exist

Is it possible to save HTML page as PDF using JavaScript or jquery?

_x000D_
_x000D_
$('#cmd2').click(function() {_x000D_
   var options = {_x000D_
  //'width': 800,_x000D_
   };_x000D_
   var pdf = new jsPDF('p', 'pt', 'a4');_x000D_
   pdf.addHTML($("#content2"), -1, 220, options, function() {_x000D_
     pdf.save('admit_card.pdf');_x000D_
   });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>_x000D_
_x000D_
<div id="content2" style="background: #fff;border-bottom: 1px solid #ffffff;">_x000D_
                     <div class="tokenDet" style="padding: 15px;border: 1px solid #000;width: 80%;margin: 0 auto;position: relative;overflow: hidden;">_x000D_
                         <div class="title" style="text-align: center;border-bottom: 1px solid #000;margin-bottom: 15px;">_x000D_
                             <h2>Entrance Exam Hall Ticket</h2>_x000D_
                            </div>_x000D_
                            <div class="parentdiv" style="display: inline-block;width: 100%;position: relative;">_x000D_
                             <div class="innerdiv" style="width: 80%;float: left;">_x000D_
                              <div class="restDet">_x000D_
                                        <div class="div">_x000D_
                                            <div class="label" style="width: 30%;float: left;">_x000D_
                                                <strong>Name</strong>_x000D_
                                            </div>_x000D_
                                            <div class="data" style="width: 70%;display: inline-block;">_x000D_
                                                <span>Santanu Patra</span>_x000D_
                                            </div>_x000D_
                                            <div class="label" style="width: 30%;float: left;">_x000D_
                                                <strong>D.O.B.</strong>_x000D_
                                            </div>_x000D_
                                            <div class="data" style="width: 70%;display: inline-block;">_x000D_
                                                <span>17th April, 1995</span>_x000D_
                                            </div>_x000D_
                                            <div class="label" style="width: 30%;float: left;">_x000D_
                                                <strong>Address</strong>_x000D_
                                            </div>_x000D_
                                            <div class="data" style="width: 70%;display: inline-block;">_x000D_
                                                <span>P.S. Srijan Corporate Park, Saltlake, Sector 5, Kolkata-91</span>_x000D_
                                            </div>_x000D_
                                            <div class="label" style="width: 30%;float: left;">_x000D_
                                                <strong>Contact Number</strong>_x000D_
                                            </div>_x000D_
                                            <div class="data" style="width: 70%;display: inline-block;">_x000D_
                                                <span>9874563210</span>_x000D_
                                            </div>_x000D_
                                            <div class="label" style="width: 30%;float: left;">_x000D_
                                                <strong>Email Id</strong>_x000D_
                                            </div>_x000D_
                                            <div class="data" style="width: 70%;display: inline-block;">_x000D_
                                                <span>[email protected]</span>_x000D_
                                            </div>_x000D_
                                            <div class="label" style="width: 30%;float: left;">_x000D_
                                                <strong>Parent(s) Name</strong>_x000D_
                                            </div>_x000D_
                                            <div class="data" style="width: 70%;display: inline-block;">_x000D_
                                                <span>S. Patra</span><br /><span>7896541230</span>_x000D_
                                            </div>_x000D_
                                            <div class="label" style="width: 30%;float: left;">_x000D_
                                                <strong>Exam Center</strong>_x000D_
                                            </div>_x000D_
                                            <div class="data" style="width: 70%;display: inline-block;">_x000D_
                                                <span>Institute of Engineering & Management</span>_x000D_
                                            </div>_x000D_
                                            <div class="label" style="width: 30%;float: left;">_x000D_
                                                <strong>Hall Number</strong>_x000D_
                                            </div>_x000D_
                                            <div class="data" style="width: 70%;display: inline-block;">_x000D_
                                                <span>COM-32</span>_x000D_
                                            </div>_x000D_
                                        </div>_x000D_
                                    </div>_x000D_
                             </div>_x000D_
                                <div class="sideDiv" style="width: 20%;float: left;">_x000D_
                                 <div class="atts" style="float: left;width: 100%;">_x000D_
                                     <div class="photo" style="width: 115px;height: 150px;float: right;">_x000D_
                                         <img src="images/candidateImg.gif" style="width: 100%;"/>_x000D_
                                        </div>_x000D_
                                        <div class="sign" style="position: absolute;bottom: 0;right: 0;border-top: 1px dashed #000;left: 80%;text-align: right;">_x000D_
                                         <small>Self Attested</small>_x000D_
                                        </div>_x000D_
                                    </div>_x000D_
                                </div>_x000D_
                            </div>_x000D_
                        </div>_x000D_
                    </div>_x000D_
                    <button class="btn btn-info" id="cmd2">Download Token</button>
_x000D_
_x000D_
_x000D_

Find object in list that has attribute equal to some value (that meets any condition)

Old question but I use this quite frequently (for version 3.8). It's a bit of syntactic salt, but it has the advantage over the top answer in that you could retrieve a list of results (if there are multiple) by simply removing the [0] and it still defaults to None if nothing is found. For any other condition, simply change the x.value==value to what ever you're looking for.

_[0] if (_:=[x for x in test_list if x.value==value]) else None

How to change active class while click to another link in bootstrap use jquery?

<script type="text/javascript">
$(document).ready(function(){
    $('.nav li').click(function(){
        $(this).addClass('active');
        $(this).siblings().removeClass('active');

    });

});

Align two inline-blocks left and right on same line

If you're already using JavaScript to center stuff when the screen is too small (as per your comment for your header), why not just undo floats/margins with JavaScript while you're at it and use floats and margins normally.

You could even use CSS media queries to reduce the amount JavaScript you're using.

Eclipse: Frustration with Java 1.7 (unbound library)

Most of the time after the installation of Eclipse eclipse.ini is changed. If you change the jdk in eclipse.ini then eclipse will use this jdk by default.

Let's say you install a new version of Eclipse and you have forgotten to change the eclipse.ini related to the jdk. Then Eclipse finds a jdk for you. Let's say it is java 1.6 that was automatically discovered (you did nothing).

If you use maven (M2E) and you reference a 1.7 jdk then you will see the frustrating message. But normally it is not displayed because you configure the correct jdk in eclipse.ini.

That was my case. I made reference into the pom to a jdk that was not configured into Eclipse.

In the screenshot you can see that 1.7 is configured and seen by Eclipse. In this case, you should make reference into the pom to a jre that is compatible with 1.7! If not -> frustrating message!

jdk 1.7 configured in eclipse.ini and retrieved in installed jre

How can I export tables to Excel from a webpage

Far and away, the cleanest, easiest export from tables to Excel is Jquery DataTables Table Tools plugin. You get a grid that sorts, filters, orders, and pages your data, and with just a few extra lines of code and two small files included, you get export to Excel, PDF, CSV, to clipboard and to the printer.

This is all the code that's required:

  $(document).ready( function () {
    $('#example').dataTable( {
        "sDom": 'T<"clear">lfrtip',
        "oTableTools": {
            "sSwfPath": "/swf/copy_cvs_xls_pdf.swf"
        }
    } );
} );

So, quick to deploy, no browser limitations, no server-side language required, and most of all very EASY to understand. It's a win-win. The one thing it does have limits on, though, is strict formatting of columns.

If formatting and colors are absolute dealbreakers, the only 100% reliable, cross browser method I've found is to use a server-side language to process proper Excel files from your code. My solution of choice is PHPExcel It is the only one I've found so far that positively handles export with formatting to a MODERN version of Excel from any browser when you give it nothing but HTML. Let me clarify though, it's definitely not as easy as the first solution, and also is a bit of a resource hog. However, on the plus side it also can output direct to PDF as well. And, once you get it configured, it just works, every time.

UPDATE - September 15, 2016: TableTools has been discontinued in favor of a new plugin called "buttons" These tools perform the same functions as the old TableTools extension, but are FAR easier to install and they make use of HTML5 downloads for modern browsers, with the capability to fallback to the original Flash download for browsers that don't support the HTML5 standard. As you can see from the many comments since I posted this response in 2011, the main weakness of TableTools has been addressed. I still can't recommend DataTables enough for handling large amounts of data simply, both for the developer and the user.

How to list all properties of a PowerShell object

Try this:

Get-WmiObject -Class "Win32_computersystem" | Format-List *
Get-WmiObject -Class "Win32_computersystem" | Format-List -Property *

For certain objects, PowerShell provides a set of formatting instructions that can affect either the table or list formats. These are usually meant to limit the display of reams of properties down to just the essential properties. However there are times when you really want to see everything. In those cases Format-List * will show all the properties. Note that in the case where you're trying to view a PowerShell error record, you need to use "Format-List * -Force" to truly see all the error information, for example,

$error[0] | Format-List * -force

Note that the wildcard can be used like a traditional wilcard this:

Get-WmiObject -Class "Win32_computersystem" | Format-List M*

Optional query string parameters in ASP.NET Web API

Default values cannot be supplied for parameters that are not declared 'optional'

 Function GetFindBooks(id As Integer, ByVal pid As Integer, Optional sort As String = "DESC", Optional limit As Integer = 99)

In your WebApiConfig

 config.Routes.MapHttpRoute( _
          name:="books", _
          routeTemplate:="api/{controller}/{action}/{id}/{pid}/{sort}/{limit}", _
          defaults:=New With {.id = RouteParameter.Optional, .pid = RouteParameter.Optional, .sort = UrlParameter.Optional, .limit = UrlParameter.Optional} _
      )

Has Facebook sharer.php changed to no longer accept detailed parameters?

I review your url in use:

https://www.facebook.com/sharer/sharer.php?s=100&p[title]=EXAMPLE&p[summary]=EXAMPLE&p[url]=EXAMPLE&p[images][0]=EXAMPLE

and see this differences:

  1. The sharer URL not is same.
  2. The strings are in different order. ( Do not know if this affects ).

I use this URL string:

http://www.facebook.com/sharer.php?s=100&p[url]=http://www.example.com/&p[images][0]=/images/image.jpg&p[title]=Title&p[summary]=Summary

In the "title" and "summary" section, I use the php function urlencode(); like this:

<?php echo urlencode($detail->title); ?>

And working fine for me.

Show/hide 'div' using JavaScript

Set your HTML as

<div id="body" hidden="">
 <h1>Numbers</h1>
 </div>
 <div id="body1" hidden="hidden">
 Body 1
 </div>

And now set the javascript as

function changeDiv()
  {
  document.getElementById('body').hidden = "hidden"; // hide body div tag
  document.getElementById('body1').hidden = ""; // show body1 div tag
  document.getElementById('body1').innerHTML = "If you can see this, JavaScript function worked"; 
  // display text if JavaScript worked
   }

How to display Oracle schema size with SQL query?

You probably want

SELECT sum(bytes)
  FROM dba_segments
 WHERE owner = <<owner of schema>>

If you are logged in as the schema owner, you can also

SELECT SUM(bytes)
  FROM user_segments

That will give you the space allocated to the objects owned by the user in whatever tablespaces they are in. There may be empty space allocated to the tables that is counted as allocated by these queries.

How to create a file in Android?

I used the following code to create a temporary file for writing bytes. And its working fine.

File file = new File(Environment.getExternalStorageDirectory() + "/" + File.separator + "test.txt");
file.createNewFile();
byte[] data1={1,1,0,0};
//write the bytes in file
if(file.exists())
{
     OutputStream fo = new FileOutputStream(file);              
     fo.write(data1);
     fo.close();
     System.out.println("file created: "+file);
}               

//deleting the file             
file.delete();
System.out.println("file deleted");

Compare two dates in Java

public long compareDates(Date exp, Date today){

        long b = (exp.getTime()-86400000)/86400000;
        long c = (today.getTime()-86400000)/86400000;
        return b-c;
    }

This works for GregorianDates. 86400000 are the amount of milliseconds in a day, this will return the number of days between the two dates.

Add and remove attribute with jquery

First you to add a class then remove id

<script type="text/javascript">
$(document).ready(function(){   
 $("#page_navigation1").addClass("page_navigation");        

 $("#add").click(function(){
        $(".page_navigation").attr("id","page_navigation1");
    });     
    $("#remove").click(function(){
        $(".page_navigation").removeAttr("id");
    });     
  });
</script>

top -c command in linux to filter processes listed based on processname

After looking for so many answers on StackOverflow, I haven't seen an answer to fit my needs.

That is, to make top command to keep refreshing with given keyword, and we don't have to CTRL+C / top again and again when new processes spawn.

Thus I make a new one...

Here goes the no-restart-needed version.

__keyword=name_of_process; (while :; do __arg=$(pgrep -d',' -f $__keyword); if [ -z "$__arg" ]; then top -u 65536 -n 1; else top -c -n 1 -p $__arg; fi; sleep 1; done;)

Modify the __keyword and it should works. (Ubuntu 2.6.38 tested)

2.14.2015 added: The system workload part is missing with the code above. For people who cares about the "load average" part:

__keyword=name_of_process; (while :; do __arg=$(pgrep -d',' -f $__keyword); if [ -z "$__arg" ]; then top -u 65536 -n 1; else top -c -n 1 -p $__arg; fi; uptime; sleep 1; done;)

How do you disable browser Autocomplete on web form field / input tag?

It doesn't seem to be possible to achieve this without using a combination client side and server side code.

In order to make sure that the user must fill in the form every time without autocomplete I use the following techniques:

  1. Generate the form field names on the server and use hidden input fields to store those names, so that when submitted to the server the server side code can use the generated names to access the field values. This is to stop the user from having the option to auto populate the fields.

  2. Place three instances of each form field on the form and hide the first and last fields of each set using css and then disable them after page load using javascript. This is to prevent the browser from filling in the fields automatically.

Here is a fiddle that demonstrates the javascript, css and html as described in #2 https://jsfiddle.net/xnbxbpv4/

javascript:

$(document).ready(function() {
    $(".disable-input").attr("disabled", "disabled");
});

css:

.disable-input {
  display: none;
}

html:

<form>
<input type="email" name="username" placeholder="username" class="disable-input">
<input type="email" name="username" placeholder="username">
<input type="email" name="username" placeholder="username" class="disable-input">
<br>
<input type="password" name="password" placeholder="password" class="disable-input">
<input type="password" name="password" placeholder="password">
<input type="password" name="password" placeholder="password" class="disable-input">
<br>
<input type="submit" value="submit">
</form>

Here is a rough example of what the server code using asp.net with razor would be to facilitate #1

model:

public class FormModel
{
    public string Username { get; set; }
    public string Password { get; set; }
}

controller:

public class FormController : Controller
{
    public ActionResult Form()
    {
        var m = new FormModel();

        m.Username = "F" + Guid.NewGuid().ToString();
        m.Password = "F" + Guid.NewGuid().ToString();

        return View(m);
    }

    public ActionResult Form(FormModel m)
    {
        var u = Request.Form[m.Username];
        var p = Request.Form[m.Password];

        // todo: do something with the form values

        ...

        return View(m);
    }
}

view:

@model FormModel

@using (Html.BeginForm("Form", "Form"))
{
    @Html.HiddenFor(m => m.UserName)
    @Html.HiddenFor(m => m.Password)

    <input type="email" name="@Model.Username" placeholder="username" class="disable-input">
    <input type="email" name="@Model.Username" placeholder="username">
    <input type="email" name="@Model.Username" placeholder="username" class="disable-input">
    <br>
    <input type="password" name="@Model.Password" placeholder="password" class="disable-input">
    <input type="password" name="@Model.Password" placeholder="password">
    <input type="password" name="@Model.Password" placeholder="password" class="disable-input">
    <br>
    <input type="submit" value="submit">
}

Object of class DateTime could not be converted to string

Use this: $newDate = $dateInDB->format('Y-m-d');

PHP Date Format to Month Name and Year

if you want same string output then try below else use without double quotes for proper output

$str = '20130814';
  echo date('"F Y"', strtotime($str));

//output  : "August 2013" 

NSDictionary - Need to check whether dictionary contains key-value pair or not

With literal syntax you can check as follows

static const NSString* kKeyToCheck = @"yourKey"
if (xyz[kKeyToCheck])
  NSLog(@"Key: %@, has Value: %@", kKeyToCheck, xyz[kKeyToCheck]);
else
 NSLog(@"Key pair do not exits for key: %@", kKeyToCheck); 

Determine if Android app is being used for the first time

for kotlin

    fun checkFirstRun() {

    var prefs_name = "MyPrefsFile"
    var pref_version_code_key = "version_code"
    var doesnt_exist: Int = -1;

    // Get current version code
    var currentVersionCode = BuildConfig.VERSION_CODE

    // Get saved version code
    var prefs: SharedPreferences = getSharedPreferences(prefs_name, MODE_PRIVATE)
    var savedVersionCode: Int = prefs.getInt(pref_version_code_key, doesnt_exist)

    // Check for first run or upgrade
    if (currentVersionCode == savedVersionCode) {

        // This is just a normal run
        return;

    } else if (savedVersionCode == doesnt_exist) {

        // TODO This is a new install (or the user cleared the shared preferences)


    } else if (currentVersionCode > savedVersionCode) {

        // TODO This is an upgrade
    }

    // Update the shared preferences with the current version code
    prefs.edit().putInt(pref_version_code_key, currentVersionCode).apply();

}

One-liner if statements, how to convert this if-else-statement

All you'd need in your case is:

return expression;

The reason why is that the expression itself evaluates to a boolean value of true or false, so it's redundant to have an if block (or even a ?: operator).

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

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

Like....

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

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

so if you need want use this code )

import { useRoutes } from "./routes";

import { BrowserRouter as Router } from "react-router-dom";

export const App = () => {

const routes = useRoutes(true);

  return (

    <Router>

      <div className="container">{routes}</div>

    </Router>

  );

};

// ./routes.js 

import { Switch, Route, Redirect } from "react-router-dom";

export const useRoutes = (isAuthenticated) => {
  if (isAuthenticated) {
    return (
      <Switch>
        <Route path="/links" exact>
          <LinksPage />
        </Route>
        <Route path="/create" exact>
          <CreatePage />
        </Route>
        <Route path="/detail/:id">
          <DetailPage />
        </Route>
        <Redirect path="/create" />
      </Switch>
    );
  }
  return (
    <Switch>
      <Route path={"/"} exact>
        <AuthPage />
      </Route>
      <Redirect path={"/"} />
    </Switch>
  );
};

How to compress an image via Javascript in the browser?

In short:

  • Read the files using the HTML5 FileReader API with .readAsArrayBuffer
  • Create a Blob with the file data and get its url with window.URL.createObjectURL(blob)
  • Create new Image element and set it's src to the file blob url
  • Send the image to the canvas. The canvas size is set to desired output size
  • Get the scaled-down data back from canvas via canvas.toDataURL("image/jpeg",0.7) (set your own output format and quality)
  • Attach new hidden inputs to the original form and transfer the dataURI images basically as normal text
  • On backend, read the dataURI, decode from Base64, and save it

Source: code.

C++ array initialization

Yes, I believe it should work and it can also be applied to other data types.

For class arrays though, if there are fewer items in the initializer list than elements in the array, the default constructor is used for the remaining elements. If no default constructor is defined for the class, the initializer list must be complete — that is, there must be one initializer for each element in the array.

Docker error cannot delete docker container, conflict: unable to remove repository reference

Remove just the containers associated with a specific image

docker ps -a | grep training/webapp | cut -d ' ' -f 1 | xargs docker rm
  • ps -a: list all containers
  • grep training/webapp : filter out everything but the containers started from the training/webapp image
  • cut -d ' ' -f 1: list only the container ids (first field when delimited by space)
  • xargs docker rm : send the container id list output to the docker rm command to remove the container

Using Tkinter in python to edit the title bar

Easy method:

root = Tk()
root.title('Hello World')

How to edit CSS style of a div using C# in .NET

Add the runat="server" attribute to the tag, then you can reference it from the codebehind.

Could not establish secure channel for SSL/TLS with authority '*'

Yes an Untrusted certificate can cause this. Look at the certificate path for the webservice by opening the websservice in a browser and use the browser tools to look at the certificate path. You may need to install one or more intermediate certificates onto the computer calling the webservice. In the browser you may see "Certificate errors" with an option to "Install Certificate" when you investigate further - this could be the certificate you missing.

My particular problem was a Geotrust Geotrust DV SSL CA intermediate certificate missing following an upgrade to their root server in July 2010 https://knowledge.geotrust.com/support/knowledge-base/index?page=content&id=AR1422

(2020 update deadlink preserved here: https://web.archive.org/web/20140724085537/https://knowledge.geotrust.com/support/knowledge-base/index?page=content&id=AR1422 )

Why does Maven have such a bad rep?

Well I've been wasting 2 days now with maven. Using m2eclipse, I found that the dependencies reported in eclipse are missing from the repositories, just like that. When I tried IAM and wanted to generate a simple blank project for struts 2, I found that v2.0.9 had also been deleted from the repository. When I finally manually added the artifacts and stuff, the project created itself only to find out that whatever I ask IAM to do, it responds with: no maven 2 projects found..... Hey, didn't I just use the Maven 2 project wizard??? Maven has been a pain in my ass since day one. THe idea behind it is very nice. In practical terms however, it lacks discipline from all parties involved. And that makes it virtually worthless. BEcause today your project might build. ANd tomorrow, when some dumbass deleted some pom from some repo, you are screwed. As simple as that. It is NOT usable for professional enterprise develoment! Not at all. Maybe in a year or 5?

How do I install TensorFlow's tensorboard?

If you installed TensorFlow using pip, then the location of TensorBoard can be retrieved by issuing the command which tensorboard on the terminal. You can then edit the TensorBoard file, if necessary.

Error during installing HAXM, VT-X not working

Uninstall any antivirus (Avast, in my case), reboot the system and try install the Intel HAXM again. It works for me.

Meaning of Choreographer messages in Logcat

This usually happens when debugging using the emulator, which is known to be slow anyway.

How to delete a localStorage item when the browser window/tab is closed?

There is a very specific use case in which any suggestion to use sessionStorage instead of localStorage does not really help. The use-case would be something as simple as having something stored while you have at least one tab opened, but invalidate it if you close the last tab remaining. If you need your values to be saved cross-tab and window, sessionStorage does not help you unless you complicate your life with listeners, like I have tried. In the meantime localStorage would be perfect for this, but it does the job 'too well', since your data will be waiting there even after a restart of the browser. I ended up using a custom code and logic that takes advantage of both.

I'd rather explain then give code. First store what you need to in localStorage, then also in localStorage create a counter that will contain the number of tabs that you have opened. This will be increased every time the page loads and decreased every time the page unloads. You can have your pick here of the events to use, I'd suggest 'load' and 'unload'. At the time you unload, you need to do the cleanup tasks that you'd like to when the counter reaches 0, meaning you're closing the last tab. Here comes the tricky part: I haven't found a reliable and generic way to tell the difference between a page reload or navigation inside the page and the closing of the tab. So If the data you store is not something that you can rebuild on load after checking that this is your first tab, then you cannot remove it at every refresh. Instead you need to store a flag in sessionStorage at every load before increasing the tab counter. Before storing this value, you can make a check to see if it already has a value and if it doesn't, this means you're loading into this session for the first time, meaning that you can do the cleanup at load if this value is not set and the counter is 0.

How can I create an object and add attributes to it?

There are a few ways to reach this goal. Basically you need an object which is extendable.

obj.a = type('Test', (object,), {})  
obj.a.b = 'fun'  

obj.b = lambda:None

class Test:
  pass
obj.c = Test()

Android camera intent

I found a pretty simple way to do this. Use a button to open it using an on click listener to start the function openc(), like this:

String fileloc;
private void openc()
{
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File f = null;
    try 
    {
        f = File.createTempFile("temppic",".jpg",getApplicationContext().getCacheDir());
        if (takePictureIntent.resolveActivity(getPackageManager()) != null)
        {               
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,FileProvider.getUriForFile(profile.this, BuildConfig.APPLICATION_ID+".provider",f));
            fileloc = Uri.fromFile(f)+"";
            Log.d("texts", "openc: "+fileloc);
            startActivityForResult(takePictureIntent, 3);
        }
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == 3 && resultCode == RESULT_OK) {
        Log.d("texts", "onActivityResult: "+fileloc);
        // fileloc is the uri of the file so do whatever with it
    }
}

You can do whatever you want with the uri location string. For instance, I send it to an image cropper to crop the image.

Set default option in mat-select

Try this:

<mat-select [(ngModel)]="defaultValue">
export class AppComponent {
  defaultValue = 'domain';
}

How to log a method's execution time exactly in milliseconds?

Here's a Swift 3 solution for bisecting code anywhere to find a long running process.

var increment: Int = 0

var incrementTime = NSDate()

struct Instrumentation {
    var title: String
    var point: Int
    var elapsedTime: Double

    init(_ title: String, _ point: Int, _ elapsedTime: Double) {
        self.title = title
        self.point = point
        self.elapsedTime = elapsedTime
    }
}

var elapsedTimes = [Instrumentation]()

func instrument(_ title: String) {
    increment += 1
    let incrementedTime = -incrementTime.timeIntervalSinceNow
    let newPoint = Instrumentation(title, increment, incrementedTime)
    elapsedTimes.append(newPoint)
    incrementTime = NSDate()
}

Usage: -

instrument("View Did Appear")

print("ELAPSED TIMES \(elapsedTimes)")

Sample output:-

ELAPSED TIMES [MyApp.SomeViewController.Instrumentation(title: "Start View Did Load", point: 1, elapsedTime: 0.040504038333892822), MyApp.SomeViewController.Instrumentation(title: "Finished Adding SubViews", point: 2, elapsedTime: 0.010585010051727295), MyApp.SomeViewController.Instrumentation(title: "View Did Appear", point: 3, elapsedTime: 0.56564098596572876)]

Finding the position of the max element

In the STL, std::max_element provides the iterator (which can be used to get index with std::distance, if you really want it).

int main(int argc, char** argv) {
  int A[4] = {0, 2, 3, 1};
  const int N = sizeof(A) / sizeof(int);

  cout << "Index of max element: "
       << distance(A, max_element(A, A + N))
       << endl;

  return 0;
}

ModuleNotFoundError: What does it mean __main__ is not a package?

Remove the dot and import absolute_import in the beginning of your file

from __future__ import absolute_import

from p_02_paying_debt_off_in_a_year import compute_balance_after

WPF Check box: Check changed handling

I know this is an old question, but how about just binding to Command if using MVVM?

ex:

<CheckBox Content="Case Sensitive" Command="{Binding bSearchCaseSensitive}"/>

For me it triggers on both Check and Uncheck.

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

How can I capture packets in Android?

Option 1 - Android PCAP

Limitation

Android PCAP should work so long as:

Your device runs Android 4.0 or higher (or, in theory, the few devices which run Android 3.2). Earlier versions of Android do not have a USB Host API

Option 2 - TcpDump

Limitation

Phone should be rooted

Option 3 - bitshark (I would prefer this)

Limitation

Phone should be rooted

Reason - the generated PCAP files can be analyzed in WireShark which helps us in doing the analysis.

Other Options without rooting your phone

  1. tPacketCapture

https://play.google.com/store/apps/details?id=jp.co.taosoftware.android.packetcapture&hl=en

Advantages

Using tPacketCapture is very easy, captured packet save into a PCAP file that can be easily analyzed by using a network protocol analyzer application such as Wireshark.

  1. You can route your android mobile traffic to PC and capture the traffic in the desktop using any network sniffing tool.

http://lifehacker.com/5369381/turn-your-windows-7-pc-into-a-wireless-hotspot

Child inside parent with min-height: 100% not inheriting height

The best way to achieve this nowadays is to use display: flex;. However you might run into an issue when trying to support IE11. According to https://caniuse.com using flexbox :

IE 11 does not vertically align items correctly when min-height is used

Internet Explorer compatible solution

The solution is to use display: table; on the parent and display: table-row; on the child both with height: 100%; as a replacement for min-height: 100%;.

Most of the solutions listed here use display: table, table-row and/or table-cell, but they don't replicate the same behaviour as min-height: 100%;, which is:

  • Inherit the computed height of the parent (as opposed to inheriting its height property);
  • Allow the parent's height to exceed its min-height;

While using this solution, the behaviour is the same and the property min-height is not needed which allows to get around the bug.

Explanation

The reason why it works is because, unlike most elements, elements using display: table and table-row will always be as tall as their content. This makes their height property behave similarly to min-height.

Solution in action

_x000D_
_x000D_
html, body {_x000D_
  height: 100px;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
#containment {_x000D_
  display: table;_x000D_
  height: 100%;_x000D_
  background: pink;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#containment-shadow-left {_x000D_
  display: table-row;_x000D_
  height: 100%;_x000D_
  background: aqua;_x000D_
}_x000D_
_x000D_
#content {_x000D_
  padding: 15px;_x000D_
}_x000D_
_x000D_
#demo {_x000D_
  display: none;_x000D_
  background-color: red;_x000D_
  height: 200px;_x000D_
}_x000D_
_x000D_
#demo-checkbox:checked ~ #demo {_x000D_
  display: block;_x000D_
}
_x000D_
<div id="containment">_x000D_
  <div id="containment-shadow-left">_x000D_
    <div id="content">_x000D_
      <input id="demo-checkbox" type="checkbox">_x000D_
      <label for="demo-checkbox">Click here for overflow demo</label>_x000D_
      <div id="demo">This is taller than #containment</div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

When does Git refresh the list of remote branches?

Use git fetch to fetch all latest created branches.

git: undo all working dir changes including new files

If you want to discard all changes, you can use any of the valid options in an alias in .gitconfig. For instance:

[alias]
    discard = "!f() { git add . && git stash && git stash drop stash@{0}; }; f"

Usage: git discard

Delete worksheet in Excel using VBA

Worksheets("Sheet1").Delete
Worksheets("Sheet2").Delete

Child element click event trigger the parent click event

The stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.

You can use the method event.isPropagationStopped() to know whether this method was ever called (on that event object).

Syntax:

Here is the simple syntax to use this method:

event.stopPropagation() 

Example:

$("div").click(function(event) {
    alert("This is : " + $(this).prop('id'));

    // Comment the following to see the difference
    event.stopPropagation();
});?

How to use Switch in SQL Server

    select 
       @selectoneCount = case @Temp
       when 1 then (@selectoneCount+1)
       when 2 then (@selectoneCount+1)
       end

   select  @selectoneCount 

C# Example of AES256 encryption using System.Security.Cryptography.Aes

Maybe this example listed here can help you out. Statement from the author

about 24 lines of code to encrypt, 23 to decrypt

Due to the fact that the link in the original posting is dead - here the needed code parts (c&p without any change to the original source)

  /*
  Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
  
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.*/
   
  #region Usings
  using System;
  using System.IO;
  using System.Security.Cryptography;
  using System.Text;
  #endregion
   
  namespace Utilities.Encryption
  {
      /// <summary>
      /// Utility class that handles encryption
      /// </summary>
      public static class AESEncryption
      {
          #region Static Functions
   
          /// <summary>
          /// Encrypts a string
          /// </summary>
          /// <param name="PlainText">Text to be encrypted</param>
          /// <param name="Password">Password to encrypt with</param>
          /// <param name="Salt">Salt to encrypt with</param>
          /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
          /// <param name="PasswordIterations">Number of iterations to do</param>
          /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
          /// <param name="KeySize">Can be 128, 192, or 256</param>
          /// <returns>An encrypted string</returns>
          public static string Encrypt(string PlainText, string Password,
              string Salt = "Kosher", string HashAlgorithm = "SHA1",
              int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
              int KeySize = 256)
          {
              if (string.IsNullOrEmpty(PlainText))
                  return "";
              byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
              byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
              byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
              PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
              byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
              RijndaelManaged SymmetricKey = new RijndaelManaged();
              SymmetricKey.Mode = CipherMode.CBC;
              byte[] CipherTextBytes = null;
              using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
              {
                  using (MemoryStream MemStream = new MemoryStream())
                  {
                      using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                      {
                          CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                          CryptoStream.FlushFinalBlock();
                          CipherTextBytes = MemStream.ToArray();
                          MemStream.Close();
                          CryptoStream.Close();
                      }
                  }
              }
              SymmetricKey.Clear();
              return Convert.ToBase64String(CipherTextBytes);
          }
   
          /// <summary>
          /// Decrypts a string
          /// </summary>
          /// <param name="CipherText">Text to be decrypted</param>
          /// <param name="Password">Password to decrypt with</param>
          /// <param name="Salt">Salt to decrypt with</param>
          /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
          /// <param name="PasswordIterations">Number of iterations to do</param>
          /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
          /// <param name="KeySize">Can be 128, 192, or 256</param>
          /// <returns>A decrypted string</returns>
          public static string Decrypt(string CipherText, string Password,
              string Salt = "Kosher", string HashAlgorithm = "SHA1",
              int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
              int KeySize = 256)
          {
              if (string.IsNullOrEmpty(CipherText))
                  return "";
              byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
              byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
              byte[] CipherTextBytes = Convert.FromBase64String(CipherText);
              PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
              byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
              RijndaelManaged SymmetricKey = new RijndaelManaged();
              SymmetricKey.Mode = CipherMode.CBC;
              byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
              int ByteCount = 0;
              using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
              {
                  using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
                  {
                      using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                      {
   
                          ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                          MemStream.Close();
                          CryptoStream.Close();
                      }
                  }
              }
              SymmetricKey.Clear();
              return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
          }
   
          #endregion
      }
  }

How to add app icon within phonegap projects?

I'm running phonegap 3.1.0-0.15.0, since iOS7 changed the resolution to 120x120px I just added a file with those dimensions to the project then changed the info.plist file.

  1. Add a 120x120 file to the project, by right clicking the project file in Xcode and selecting, "Add files to "[Your Project Name]"...
  2. Go to the info.plist file in Xcode "Resources/[Your Project Name]-info.plist"
  3. Under "Icon files (iOS 5)/Primary Icon/Icon files" change "Item 2" to whatever the filename your file had (I called mine "icon-120.png which I placed in the Project folder along side all the other icons, though this shouldn't matter)

More info can be found here: http://www.digifloor.com/missing-recommended-icon-file-error-ios-app-13

To fix the splash screen in iOS i just pasted in new files with the same dimensions and same filenames, overwriting the old ones. Just remember to go to Product>Clean in the menu bar in Xcode (shortcut Shift+Command+K) and it should work fine! :)

How to check if memcache or memcached is installed for PHP?

The best approach in this case is to use extension_loaded() or function_exists() they are equally as fast.

You can see evidence here:

https://github.com/dragoonis/ppi-framework/blob/master/Cache/Memcached.php#L140

Bear in mind that some PHP extensions such as APC have php.ini settings that can disable them even though the extension may be loaded. Here is an example of how to check against that also:

https://github.com/dragoonis/ppi-framework/blob/master/Cache/Apc.php#L79

Hope this helps.

Iterating over JSON object in C#

You can use the JsonTextReader to read the JSON and iterate over the tokens:

using (var reader = new JsonTextReader(new StringReader(jsonText)))
{
    while (reader.Read())
    {
        Console.WriteLine("{0} - {1} - {2}", 
                          reader.TokenType, reader.ValueType, reader.Value);
    }
}

How to disable EditText in Android

Set inputType attribute to none in your layout.xml file under EditText

C# - Insert a variable number of spaces into a string? (Formatting an output file)

Just for kicks, here's the functions I wrote to do it before I had the .PadRight bit:

    public string insertSpacesAtEnd(string input, int longest)
    {
        string output = input;
        string spaces = "";
        int inputLength = input.Length;
        int numToInsert = longest - inputLength;

        for (int i = 0; i < numToInsert; i++)
        {
            spaces += " ";
        }

        output += spaces;

        return output;
    }

    public int findLongest(List<Results> theList)
    {
        int longest = 0;

        for (int i = 0; i < theList.Count; i++)
        {
            if (longest < theList[i].title.Length)
                longest = theList[i].title.Length;
        }
        return longest;
    }

    ////Usage////
    for (int i = 0; i < storageList.Count; i++)
    {
        output += insertSpacesAtEnd(storageList[i].title, longest + 5) +   storageList[i].rank.Trim() + "     " + storageList[i].term.Trim() + "         " + storageList[i].name + "\r\n";
    }

Bootstrap Modal Backdrop Remaining

I got the same problem, the solution is add the property data-dismiss="modal" to the button you are going to click.

VBA: How to delete filtered rows in Excel?

As an alternative to using UsedRange or providing an explicit range address, the AutoFilter.Range property can also specify the affected range.

ActiveSheet.AutoFilter.Range.Offset(1,0).Rows.SpecialCells(xlCellTypeVisible).Delete(xlShiftUp)

As used here, Offset causes the first row after the AutoFilter range to also be deleted. In order to avoid that, I would try using .Resize() after .Offset().

How to create a simple checkbox in iOS?

Yeah, no checkbox for you in iOS (-:

Here, this is what I did to create a checkbox:

UIButton *checkbox;
BOOL checkBoxSelected;
checkbox = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
// 20x20 is the size of the checkbox that you want
// create 2 images sizes 20x20 , one empty square and
// another of the same square with the checkmark in it
// Create 2 UIImages with these new images, then:

[checkbox setBackgroundImage:[UIImage imageNamed:@"notselectedcheckbox.png"]
                    forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted=YES;
[checkbox addTarget:(nullable id) action:(nonnull SEL) forControlEvents:(UIControlEvents)];
[self.view addSubview:checkbox];

Now in the target method do the following:

-(void)checkboxSelected:(id)sender
{
    checkBoxSelected = !checkBoxSelected; /* Toggle */
    [checkbox setSelected:checkBoxSelected];
}

That's it!

How do I add a library path in cmake?

The simplest way of doing this would be to add

include_directories(${CMAKE_SOURCE_DIR}/inc)
link_directories(${CMAKE_SOURCE_DIR}/lib)

add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # libbar.so is found in ${CMAKE_SOURCE_DIR}/lib

The modern CMake version that doesn't add the -I and -L flags to every compiler invocation would be to use imported libraries:

add_library(bar SHARED IMPORTED) # or STATIC instead of SHARED
set_target_properties(bar PROPERTIES
  IMPORTED_LOCATION "${CMAKE_SOURCE_DIR}/lib/libbar.so"
  INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_SOURCE_DIR}/include/libbar"
)

set(FOO_SRCS "foo.cpp")
add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # also adds the required include path

If setting the INTERFACE_INCLUDE_DIRECTORIES doesn't add the path, older versions of CMake also allow you to use target_include_directories(bar PUBLIC /path/to/include). However, this no longer works with CMake 3.6 or newer.

How to change link color (Bootstrap)

If you are using Bootstrap 4, you can simple use a color utility class (e.g. text-success, text-danger, etc... ).

You can also create your own classes (e.g. text-my-own-color)

Both options are shown in the example below, run the code snippet to see a live demo.

_x000D_
_x000D_
.text-my-own-color {
  color: #663300 !important; // Define your own color in your CSS
}
.text-my-own-color:hover, .text-my-own-color:active {
  color: #664D33 !important; // Define your own color's darkening/lightening in your CSS
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="navbar-collapse">
  <ul class="nav pull-right">

    <!-- Bootstrap's color utility class -->
    <li class="active"><a class="text-success" href="#">? ???</a></li>

    <!-- Bootstrap's color utility class -->
    <li><a class="text-danger" href="#">??? ??? ????????</a></li>

    <!-- Bootstrap's color utility class -->
    <li><a class="text-warning" href="#">????</a></li>

    <!-- Custom color utility class -->
    <li><a class="text-my-own-color" href="#">????????</a></li>

  </ul>
</div>
_x000D_
_x000D_
_x000D_

SQL Case Expression Syntax?

Oracle syntax from the 11g Documentation:

CASE { simple_case_expression | searched_case_expression }
     [ else_clause ]
     END

simple_case_expression

expr { WHEN comparison_expr THEN return_expr }...

searched_case_expression

{ WHEN condition THEN return_expr }...

else_clause

ELSE else_expr

Convert a list to a data frame

Sometimes your data may be a list of lists of vectors of the same length.

lolov = list(list(c(1,2,3),c(4,5,6)), list(c(7,8,9),c(10,11,12),c(13,14,15)) )

(The inner vectors could also be lists, but I'm simplifying to make this easier to read).

Then you can make the following modification. Remember that you can unlist one level at a time:

lov = unlist(lolov, recursive = FALSE )
> lov
[[1]]
[1] 1 2 3

[[2]]
[1] 4 5 6

[[3]]
[1] 7 8 9

[[4]]
[1] 10 11 12

[[5]]
[1] 13 14 15

Now use your favorite method mentioned in the other answers:

library(plyr)
>ldply(lov)
  V1 V2 V3
1  1  2  3
2  4  5  6
3  7  8  9
4 10 11 12
5 13 14 15

How is the default max Java heap size determined?

For Java SE 5: According to Garbage Collector Ergonomics [Oracle]:

initial heap size:

Larger of 1/64th of the machine's physical memory on the machine or some reasonable minimum. Before J2SE 5.0, the default initial heap size was a reasonable minimum, which varies by platform. You can override this default using the -Xms command-line option.

maximum heap size:

Smaller of 1/4th of the physical memory or 1GB. Before J2SE 5.0, the default maximum heap size was 64MB. You can override this default using the -Xmx command-line option.

UPDATE:

As pointed out by Tom Anderson in his comment, the above is for server-class machines. From Ergonomics in the 5.0 JavaTM Virtual Machine:

In the J2SE platform version 5.0 a class of machine referred to as a server-class machine has been defined as a machine with

  • 2 or more physical processors
  • 2 or more Gbytes of physical memory

with the exception of 32 bit platforms running a version of the Windows operating system. On all other platforms the default values are the same as the default values for version 1.4.2.

In the J2SE platform version 1.4.2 by default the following selections were made

  • initial heap size of 4 Mbyte
  • maximum heap size of 64 Mbyte

Difference between break and continue in PHP?

break exits the loop you are in, continue starts with the next cycle of the loop immediatly.

Example:

$i = 10;
while (--$i)
{
    if ($i == 8)
    {
        continue;
    }
    if ($i == 5)
    {
        break;
    }
    echo $i . "\n";
}

will output:

9
7
6

Django datetime issues (default=datetime.now())

The datetime.now() is evaluated when the class is created, not when new record is being added to the database.

To achieve what you want define this field as:

date = models.DateTimeField(auto_now_add=True)

This way the date field will be set to current date for each new record.

How do I use Node.js Crypto to create a HMAC-SHA1 hash?

Documentation for crypto: http://nodejs.org/api/crypto.html

const crypto = require('crypto')

const text = 'I love cupcakes'
const key = 'abcdeg'

crypto.createHmac('sha1', key)
  .update(text)
  .digest('hex')

Check element CSS display with JavaScript

As sdleihssirhc says below, if the element's display is being inherited or being specified by a CSS rule, you'll need to get its computed style:

return window.getComputedStyle(element, null).display;

Elements have a style property that will tell you what you want, if the style was declared inline or with JavaScript:

console.log(document.getElementById('someIDThatExists').style.display);

will give you a string value.

make bootstrap twitter dialog modal draggable

You can use the code below if you dont want to use jQuery UI or any third party pluggin. It's only plain jQuery.

This answer works well with Bootstrap v3.x . For version 4.x see @User comment below

_x000D_
_x000D_
$(".modal").modal("show");_x000D_
_x000D_
$(".modal-header").on("mousedown", function(mousedownEvt) {_x000D_
    var $draggable = $(this);_x000D_
    var x = mousedownEvt.pageX - $draggable.offset().left,_x000D_
        y = mousedownEvt.pageY - $draggable.offset().top;_x000D_
    $("body").on("mousemove.draggable", function(mousemoveEvt) {_x000D_
        $draggable.closest(".modal-dialog").offset({_x000D_
            "left": mousemoveEvt.pageX - x,_x000D_
            "top": mousemoveEvt.pageY - y_x000D_
        });_x000D_
    });_x000D_
    $("body").one("mouseup", function() {_x000D_
        $("body").off("mousemove.draggable");_x000D_
    });_x000D_
    $draggable.closest(".modal").one("bs.modal.hide", function() {_x000D_
        $("body").off("mousemove.draggable");_x000D_
    });_x000D_
});
_x000D_
.modal-header {_x000D_
    cursor: move;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="modal fade" tabindex="-1" role="dialog">_x000D_
  <div class="modal-dialog" role="document">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>_x000D_
        <h4 class="modal-title">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        <p>One fine body&hellip;</p>_x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        <button type="button" class="btn btn-primary">Save changes</button>_x000D_
      </div>_x000D_
    </div><!-- /.modal-content -->_x000D_
  </div><!-- /.modal-dialog -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

Multiple WHERE Clauses with LINQ extension methods

If you working with in-memory data (read "collections of POCO") you may also stack your expressions together using PredicateBuilder like so:

// initial "false" condition just to start "OR" clause with
var predicate = PredicateBuilder.False<YourDataClass>();

if (condition1)
{
    predicate = predicate.Or(d => d.SomeStringProperty == "Tom");
}

if (condition2)
{
    predicate = predicate.Or(d => d.SomeStringProperty == "Alex");
}

if (condition3)
{
    predicate = predicate.And(d => d.SomeIntProperty >= 4);
}

return originalCollection.Where<YourDataClass>(predicate.Compile());

The full source of mentioned PredicateBuilder is bellow (but you could also check the original page with a few more examples):

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;

public static class PredicateBuilder
{
  public static Expression<Func<T, bool>> True<T> ()  { return f => true;  }
  public static Expression<Func<T, bool>> False<T> () { return f => false; }

  public static Expression<Func<T, bool>> Or<T> (this Expression<Func<T, bool>> expr1,
                                                      Expression<Func<T, bool>> expr2)
  {
    var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
    return Expression.Lambda<Func<T, bool>>
          (Expression.OrElse (expr1.Body, invokedExpr), expr1.Parameters);
  }

  public static Expression<Func<T, bool>> And<T> (this Expression<Func<T, bool>> expr1,
                                                       Expression<Func<T, bool>> expr2)
  {
    var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
    return Expression.Lambda<Func<T, bool>>
          (Expression.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);
  }
}

Note: I've tested this approach with Portable Class Library project and have to use .Compile() to make it work:

Where(predicate .Compile() );

Could not find com.google.android.gms:play-services:3.1.59 3.2.25 4.0.30 4.1.32 4.2.40 4.2.42 4.3.23 4.4.52 5.0.77 5.0.89 5.2.08 6.1.11 6.1.71 6.5.87

I've been strugglin with this problem for hours till found this post. Just like @ligi said, some people have two SDK folders (Android Studio, which is bundled and Eclipse). The problem is that it doesn't matter if you downloaded the Google Play Services library on both SDK folders, your ANDROID_HOME enviroment variable must be pointing to the SDK folder used by the Android Studio.

SDK Folder A  (Used on Eclipse)
SDK Folder B  (Used on AS)

ANDROID_HOME=<path to SDK Folder B>

After change the path of this variable the error was gone.

What does "fatal: bad revision" mean?

git revert doesn't take a filename parameter. Do you want git checkout?

How to run a .jar in mac?

Make Executable your jar and after that double click on it on Mac OS then it works successfully.

sudo chmod +x filename.jar

Try this, I hope this works.

Illegal string offset Warning PHP

It works to me:

Testing Code of mine:

$var2['data'] = array ('a'=>'21','b'=>'32','c'=>'55','d'=>'66','e'=>'77');
foreach($var2 as $result)
{  
    $test = $result['c'];
}
print_r($test);

Output: 55

Check it guys. Thanks

Using getopts to process long and short command line options

Here's an example that actually uses getopt with long options:

aflag=no
bflag=no
cargument=none

# options may be followed by one colon to indicate they have a required argument
if ! options=$(getopt -o abc: -l along,blong,clong: -- "$@")
then
    # something went wrong, getopt will put out an error message for us
    exit 1
fi

set -- $options

while [ $# -gt 0 ]
do
    case $1 in
    -a|--along) aflag="yes" ;;
    -b|--blong) bflag="yes" ;;
    # for options with required arguments, an additional shift is required
    -c|--clong) cargument="$2" ; shift;;
    (--) shift; break;;
    (-*) echo "$0: error - unrecognized option $1" 1>&2; exit 1;;
    (*) break;;
    esac
    shift
done

How do I make a Mac Terminal pop-up/alert? Applescript?

Use this command to trigger the notification center notification from the terminal.

osascript -e 'display notification "Lorem ipsum dolor sit amet" with title "Title"'

Android check permission for LocationManager

If you simply want to check for permissions (rather than request for permissions), I wrote a simple extension like so:

fun BaseActivity.checkPermission(permissionName: String): Boolean {
        return if (Build.VERSION.SDK_INT >= 23) {
            val granted =
                ContextCompat.checkSelfPermission(this, permissionName)
            granted == PackageManager.PERMISSION_GRANTED
        } else {
            val granted =
                PermissionChecker.checkSelfPermission(this, permissionName)
            granted == PermissionChecker.PERMISSION_GRANTED
        }
    }

Now, if I want to check for a permission I can simply pass in a permission like so:

checkPermission(Manifest.permission.READ_CONTACTS)

How to install wget in macOS?

You need to do

./configure --with-ssl=openssl --with-libssl-prefix=/usr/local/ssl

Instead of this

./configure --with-ssl=openssl

Get current clipboard content?

You can use

window.clipboardData.getData('Text')

to get the content of user's clipboard in IE. However, in other browser you may need to use flash to get the content, since there is no standard interface to access the clipboard. May be you can have try this plugin Zero Clipboard

Why is &#65279; appearing in my HTML?

The character in question &#65279 is the Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF). It may be that you copied it into your code via a copy/paste without realizing it. The fact that it's not visible makes it hard to tell if you're using an editor that displays actual unicode characters.

One option is to open the file in a very basic text editor that doesn't understand unicode, or one that understands it but has the ability to display any non-ascii characters using their actual codes.

Once you locate it, you can delete the small block of text around it and retype that text manually.

How to open new browser window on button click event?

Or write to the response stream:

Response.Write("<script>");
Response.Write("window.open('page.html','_blank')");
Response.Write("</script>");

Encrypt and decrypt a string in C#?

A good algorithm to securely hash data is BCrypt:

Besides incorporating a salt to protect against rainbow table attacks, bcrypt is an adaptive function: over time, the iteration count can be increased to make it slower, so it remains resistant to brute-force search attacks even with increasing computation power.

There's a nice .NET implementation of BCrypt that is available also as a NuGet package.

Easy way to make a confirmation dialog in Angular?

Here's a slghtly different take using javascript's native confirm functionality and a custom Angular directive. It's super flexible and pretty lightweight:

Usage:

<button (hrsAreYouSure) (then)="confirm(arg1)" (else)="cancel(arg2)">
  This will execute confirm if user presses Ok on the confirmation dialog, or cancel if they
  hit Cancel
</button>

Directive:

import {Directive, ElementRef, EventEmitter, Inject, OnInit, Output} from '@angular/core';

@Directive({
  selector: '[hrsAreYouSure]'
})

export class AreYouSureDirective implements OnInit {

  @Output() then = new EventEmitter<boolean>();
  @Output() else = new EventEmitter<boolean>();

  constructor(@Inject(ElementRef) private element: ElementRef) { }

  ngOnInit(): void {
    const directive = this;
    this.element.nativeElement.onclick = function() {
      const result = confirm('Are you sure?');
      if (result) {
        directive.then.emit(true);
      } else {
        directive.else.emit(true);
      }
    };
  }
}

Android: How to handle right to left swipe gestures

This issue still exists. An OnTouchListener with an OnSwipeTouchListener solves it in a simple way:

myView.setOnTouchListener(
    new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            if(!swipe.onTouch(v, event)) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    // your code here

                    return true;
                } else if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    // your code here

                    return true;
                }
            }
            return false;
        }

    }
);

where swipe refers to a class which records whether swipe methods have been invoked, then forwards events to the delegate OnSwipeTouchListener.

private class DirtyOnSwipeTouchListener extends OnSwipeTouchListener {
    private boolean dirty = false;
    private OnSwipeTouchListener delegate;

    public DirtyOnSwipeTouchListener(Context ctx, OnSwipeTouchListener delegate) {
        super(ctx);

        this.delegate = delegate;
    }

    private void reset() {
        dirty = false;
    }

    public void onSwipeTop() {
        dirty = true;
        delegate.onSwipeTop();
    }

    public void onSwipeRight() {
        dirty = true;
        delegate.onSwipeRight();
    }

    public void onSwipeLeft() {
        dirty = true;
        delegate.onSwipeLeft();
    }

    public void onSwipeBottom() {
        dirty = true;
        delegate.onSwipeBottom();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        try {
            super.onTouch(v, event);

            return dirty;
        } finally {
            dirty = false;
        }

    }
};

Can I access constants in settings.py from templates in Django?

If we were to compare context vs. template tags on a single variable, then knowing the more efficient option could be benificial. However, you might be better off to dip into the settings only from templates that need that variable. In that case it doesn't make sense to pass the variable into all templates. But if you are sending the variable into a common template such as the base.html template, Then it would not matter as the base.html template is rendered on every request, so you can use either methods.

If you decide to go with the template tags option, then use the following code as it allows you to pass a default value in, just in case the variable in-question was undefined.

Example: get_from_settings my_variable as my_context_value

Example: get_from_settings my_variable my_default as my_context_value

class SettingsAttrNode(Node):
    def __init__(self, variable, default, as_value):
        self.variable = getattr(settings, variable, default)
        self.cxtname = as_value

    def render(self, context):
        context[self.cxtname] = self.variable
        return ''


def get_from_setting(parser, token):
    as_value = variable = default = ''
    bits = token.contents.split()
    if len(bits) == 4 and bits[2] == 'as':
        variable = bits[1]
        as_value = bits[3]
    elif len(bits) == 5 and bits[3] == 'as':
        variable     = bits[1]
        default  = bits[2]
        as_value = bits[4]
    else:
        raise TemplateSyntaxError, "usage: get_from_settings variable default as value " \
                "OR: get_from_settings variable as value"

    return SettingsAttrNode(variable=variable, default=default, as_value=as_value)

get_from_setting = register.tag(get_from_setting)

Rownum in postgresql

If you have a unique key, you may use COUNT(*) OVER ( ORDER BY unique_key ) as ROWNUM

SELECT t.*, count(*) OVER (ORDER BY k ) ROWNUM 
FROM yourtable t;

| k |     n | rownum |
|---|-------|--------|
| a | TEST1 |      1 |
| b | TEST2 |      2 |
| c | TEST2 |      3 |
| d | TEST4 |      4 |

DEMO

OpenCV with Network Cameras

rtsp protocol did not work for me. mjpeg worked first try. I assume it is built into my camera (Dlink DCS 900).

Syntax found here: http://answers.opencv.org/question/133/how-do-i-access-an-ip-camera/

I did not need to compile OpenCV with ffmpg support.

Javascript - How to show escape characters in a string?

If your goal is to have

str = "Hello\nWorld";

and output what it contains in string literal form, you can use JSON.stringify:

console.log(JSON.stringify(str)); // ""Hello\nWorld""

_x000D_
_x000D_
const str = "Hello\nWorld";_x000D_
const json = JSON.stringify(str);_x000D_
console.log(json); // ""Hello\nWorld""_x000D_
for (let i = 0; i < json.length; ++i) {_x000D_
    console.log(`${i}: ${json.charAt(i)}`);_x000D_
}
_x000D_
.as-console-wrapper {_x000D_
    max-height: 100% !important;_x000D_
}
_x000D_
_x000D_
_x000D_

console.log adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal (yes, that's somewhat confusing).

JSON.stringify takes what you give it (in this case, a string) and returns a string containing valid JSON for that value. So for the above, it returns an opening quote ("), the word Hello, a backslash (\), the letter n, the word World, and the closing quote ("). The linefeed in the string is escaped in the output as a \ and an n because that's how you encode a linefeed in JSON. Other escape sequences are similarly encoded.

SQL Update with row_number()

If table does not have relation, just copy all in new table with row number and remove old and rename new one with old one.

Select   RowNum = ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) , * INTO cdm.dbo.SALES2018 from 
(
select * from SALE2018) as SalesSource

Flask-SQLalchemy update a row's information

Models.py define the serializers

def default(o):
   if isinstance(o, (date, datetime)):
      return o.isoformat()

class User(db.Model):
   __tablename__='user'
   id = db.Column(db.Integer, primary_key=True, autoincrement=True)
   .......
   ####

    def serializers(self):
       dict_val={"id":self.id,"created_by":self.created_by,"created_at":self.created_at,"updated_by":self.updated_by,"updated_at":self.updated_at}
       return json.loads(json.dumps(dict_val,default=default))

In RestApi, We can update the record dynamically by passing the json data into update query:

class UpdateUserDetails(Resource):
   @auth_token_required
   def post(self):
      json_data = request.get_json()
      user_id = current_user.id
      try:
         instance = User.query.filter(User.id==user_id)
         data=instance.update(dict(json_data))
         db.session.commit()
         updateddata=instance.first()
         msg={"msg":"User details updated successfully","data":updateddata.serializers()}
         code=200
      except Exception as e:
         print(e)
         msg = {"msg": "Failed to update the userdetails! please contact your administartor."}
         code=500
      return msg

Can someone explain mappedBy in JPA and Hibernate?

You started with ManyToOne mapping , then you put OneToMany mapping as well for BiDirectional way. Then at OneToMany side (usually your parent table/class), you have to mention "mappedBy" (mapping is done by and in child table/class), so hibernate will not create EXTRA mapping table in DB (like TableName = parent_child).

How to disable scientific notation?

You can effectively remove scientific notation in printing with this code:

options(scipen=999)

Darken background image on hover

Similar, but again a little bit different.

Make the image 100% opacity so it is clear. And then on img hover reduce it to the opacity you want. In this example, I have also added easing for a nice transition.

img {
    -webkit-filter: brightness(100%);
}

img:hover {
    -webkit-filter: brightness(70%);
    -webkit-transition: all 1s ease;
    -moz-transition: all 1s ease;
    -o-transition: all 1s ease;
    -ms-transition: all 1s ease;
    transition: all 1s ease;
}

That will do it, Hope that helps.

Thank you Robert Byers for your jsfiddle

Does a finally block always get executed in Java?

Adding to @vibhash's answer as no other answer explains what happens in the case of a mutable object like the one below.

public static void main(String[] args) {
    System.out.println(test().toString());
}

public static StringBuffer test() {
    StringBuffer s = new StringBuffer();
    try {
        s.append("sb");
        return s;
    } finally {
        s.append("updated ");
    }
}

Will output

sbupdated 

What is the copy-and-swap idiom?

There are some good answers already. I'll focus mainly on what I think they lack - an explanation of the "cons" with the copy-and-swap idiom....

What is the copy-and-swap idiom?

A way of implementing the assignment operator in terms of a swap function:

X& operator=(X rhs)
{
    swap(rhs);
    return *this;
}

The fundamental idea is that:

  • the most error-prone part of assigning to an object is ensuring any resources the new state needs are acquired (e.g. memory, descriptors)

  • that acquisition can be attempted before modifying the current state of the object (i.e. *this) if a copy of the new value is made, which is why rhs is accepted by value (i.e. copied) rather than by reference

  • swapping the state of the local copy rhs and *this is usually relatively easy to do without potential failure/exceptions, given the local copy doesn't need any particular state afterwards (just needs state fit for the destructor to run, much as for an object being moved from in >= C++11)

When should it be used? (Which problems does it solve [/create]?)

  • When you want the assigned-to objected unaffected by an assignment that throws an exception, assuming you have or can write a swap with strong exception guarantee, and ideally one that can't fail/throw..†

  • When you want a clean, easy to understand, robust way to define the assignment operator in terms of (simpler) copy constructor, swap and destructor functions.

    • Self-assignment done as a copy-and-swap avoids oft-overlooked edge cases.‡

  • When any performance penalty or momentarily higher resource usage created by having an extra temporary object during the assignment is not important to your application. ?

swap throwing: it's generally possible to reliably swap data members that the objects track by pointer, but non-pointer data members that don't have a throw-free swap, or for which swapping has to be implemented as X tmp = lhs; lhs = rhs; rhs = tmp; and copy-construction or assignment may throw, still have the potential to fail leaving some data members swapped and others not. This potential applies even to C++03 std::string's as James comments on another answer:

@wilhelmtell: In C++03, there is no mention of exceptions potentially thrown by std::string::swap (which is called by std::swap). In C++0x, std::string::swap is noexcept and must not throw exceptions. – James McNellis Dec 22 '10 at 15:24


‡ assignment operator implementation that seems sane when assigning from a distinct object can easily fail for self-assignment. While it might seem unimaginable that client code would even attempt self-assignment, it can happen relatively easily during algo operations on containers, with x = f(x); code where f is (perhaps only for some #ifdef branches) a macro ala #define f(x) x or a function returning a reference to x, or even (likely inefficient but concise) code like x = c1 ? x * 2 : c2 ? x / 2 : x;). For example:

struct X
{
    T* p_;
    size_t size_;
    X& operator=(const X& rhs)
    {
        delete[] p_;  // OUCH!
        p_ = new T[size_ = rhs.size_];
        std::copy(p_, rhs.p_, rhs.p_ + rhs.size_);
    }
    ...
};

On self-assignment, the above code delete's x.p_;, points p_ at a newly allocated heap region, then attempts to read the uninitialised data therein (Undefined Behaviour), if that doesn't do anything too weird, copy attempts a self-assignment to every just-destructed 'T'!


? The copy-and-swap idiom can introduce inefficiencies or limitations due to the use of an extra temporary (when the operator's parameter is copy-constructed):

struct Client
{
    IP_Address ip_address_;
    int socket_;
    X(const X& rhs)
      : ip_address_(rhs.ip_address_), socket_(connect(rhs.ip_address_))
    { }
};

Here, a hand-written Client::operator= might check if *this is already connected to the same server as rhs (perhaps sending a "reset" code if useful), whereas the copy-and-swap approach would invoke the copy-constructor which would likely be written to open a distinct socket connection then close the original one. Not only could that mean a remote network interaction instead of a simple in-process variable copy, it could run afoul of client or server limits on socket resources or connections. (Of course this class has a pretty horrid interface, but that's another matter ;-P).

npm install hangs

Incase its useful to others, the following is what worked for me:

On my machine, although npm proxy was set correctly, npm install waits forever doing something like sill extract. Re-trying npm install waits forever on the same package again and again.

After waiting for a long timeout, npm install printed an error message implying that git was trying to fetch something.

The problem vanished after configuring git proxy using the below command:

git config --global http.proxy https://proxy-server:port

Note the https in the value of http.proxy without which the configuration did not take effect. Proxy server settings (http / https / port) might vary for users; hence its worth spending a bit of time experimenting with npm and git proxy server settings.

Regular cast vs. static_cast vs. dynamic_cast

static_cast

static_cast is used for cases where you basically want to reverse an implicit conversion, with a few restrictions and additions. static_cast performs no runtime checks. This should be used if you know that you refer to an object of a specific type, and thus a check would be unnecessary. Example:

void func(void *data) {
  // Conversion from MyClass* -> void* is implicit
  MyClass *c = static_cast<MyClass*>(data);
  ...
}

int main() {
  MyClass c;
  start_thread(&func, &c)  // func(&c) will be called
      .join();
}

In this example, you know that you passed a MyClass object, and thus there isn't any need for a runtime check to ensure this.

dynamic_cast

dynamic_cast is useful when you don't know what the dynamic type of the object is. It returns a null pointer if the object referred to doesn't contain the type casted to as a base class (when you cast to a reference, a bad_cast exception is thrown in that case).

if (JumpStm *j = dynamic_cast<JumpStm*>(&stm)) {
  ...
} else if (ExprStm *e = dynamic_cast<ExprStm*>(&stm)) {
  ...
}

You cannot use dynamic_cast if you downcast (cast to a derived class) and the argument type is not polymorphic. For example, the following code is not valid, because Base doesn't contain any virtual function:

struct Base { };
struct Derived : Base { };
int main() {
  Derived d; Base *b = &d;
  dynamic_cast<Derived*>(b); // Invalid
}

An "up-cast" (cast to the base class) is always valid with both static_cast and dynamic_cast, and also without any cast, as an "up-cast" is an implicit conversion.

Regular Cast

These casts are also called C-style cast. A C-style cast is basically identical to trying out a range of sequences of C++ casts, and taking the first C++ cast that works, without ever considering dynamic_cast. Needless to say, this is much more powerful as it combines all of const_cast, static_cast and reinterpret_cast, but it's also unsafe, because it does not use dynamic_cast.

In addition, C-style casts not only allow you to do this, but they also allow you to safely cast to a private base-class, while the "equivalent" static_cast sequence would give you a compile-time error for that.

Some people prefer C-style casts because of their brevity. I use them for numeric casts only, and use the appropriate C++ casts when user defined types are involved, as they provide stricter checking.

How to add a class to a given element?

You can use the API querySelector to select your element and then create a function with the element and the new classname as parameters. Using classlist for modern browsers, else for IE8. Then you can call the function after an event.

 //select the dom element
 var addClassVar = document.querySelector('.someclass');

 //define the addclass function
 var addClass = function(el,className){
   if (el.classList){
     el.classList.add(className);
   }
   else {
     el.className += ' ' + className;
  }
};

//call the function
addClass(addClassVar, 'newClass');

What's the difference between a proxy server and a reverse proxy server?

Proxy: It is making the request on behalf of the client. So, the server will return the response to the proxy, and the proxy will forward the response to the client. In fact, the server will never "learn" who the client was (the client's IP address); it will only know the proxy. However, the client definitely knows the server, since it essentially formats the HTTP request destined for the server, but it just hands it to the proxy.

Enter image description here

Reverse Proxy: It is receiving the request on behalf of the server. It forwards the request to the server, receives the response and then returns the response to the client. In this case, the client will never "learn" who was the actual server (the server's IP address) (with some exceptions); it will only know the proxy. The server will or won't know the actual client, depending on the configurations of the reverse proxy.

Enter image description here

Put content in HttpResponseMessage object?

For any T object you can do:

return Request.CreateResponse<T>(HttpStatusCode.OK, Tobject);

How to convert color code into media.brush?

You could use the same mechanism the XAML reading system uses: Type converters

var converter = new System.Windows.Media.BrushConverter();
var brush = (Brush)converter.ConvertFromString("#FFFFFF90");
Fill = brush;

How to customize the background/border colors of a grouped table view cell?

To change the table view border color:

In.h:

#import <QuartzCore/QuartzCore.h>

In .m:

tableView.layer.masksToBounds=YES;
tableView.layer.borderWidth = 1.0f;
tableView.layer.borderColor = [UIColor whiteColor].CGColor;

Complex CSS selector for parent of active child

Future answer with CSS4 selectors

New CSS Specs contain an experimental :has pseudo selector that might be able to do this thing.

li:has(a:active) {
  /* ... */
}

The browser support on this is basically non-existent at this time, but it is in consideration on the official specs.


Answer in 2012 that was wrong in 2012 and is even more wrong in 2018

While it is true that CSS cannot ASCEND, it is incorrect that you cannot grab the parent element of another element. Let me reiterate:

Using your HTML example code, you are able to grab the li without specifying li

ul * a {
    property:value;
}

In this example, the ul is the parent of some element and that element is the parent of anchor. The downside of using this method is that if there is a ul with any child element that contains an anchor, it inherits the styles specified.

You may also use the child selector as well since you'll have to specify the parent element anyway.

ul>li a {
    property:value;
}

In this example, the anchor must be a descendant of an li that MUST be a child of ul, meaning it must be within the tree following the ul declaration. This is going to be a bit more specific and will only grab a list item that contains an anchor AND is a child of ul.

SO, to answer your question by code.

ul.menu > li a.active {
    property:value;
}

This should grab the ul with the class of menu, and the child list item that contains only an anchor with the class of active.

Unity 2d jumping script

The answer above is now obsolete with Unity 5 or newer. Use this instead!

GetComponent<Rigidbody2D>().AddForce(new Vector2(0,10), ForceMode2D.Impulse);

I also want to add that this leaves the jump height super private and only editable in the script, so this is what I did...

    public float playerSpeed;  //allows us to be able to change speed in Unity
public Vector2 jumpHeight;

// Use this for initialization
void Start () {

}
// Update is called once per frame
void Update ()
{
    transform.Translate(playerSpeed * Time.deltaTime, 0f, 0f);  //makes player run

    if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space))  //makes player jump
    {
        GetComponent<Rigidbody2D>().AddForce(jumpHeight, ForceMode2D.Impulse);

This makes it to where you can edit the jump height in Unity itself without having to go back to the script.

Side note - I wanted to comment on the answer above, but I can't because I'm new here. :)

What does %w(array) mean?

I think of %w() as a "word array" - the elements are delimited by spaces and it returns an array of strings.

There are other % literals:

  • %r() is another way to write a regular expression.
  • %q() is another way to write a single-quoted string (and can be multi-line, which is useful)
  • %Q() gives a double-quoted string
  • %x() is a shell command
  • %i() gives an array of symbols (Ruby >= 2.0.0)
  • %s() turns foo into a symbol (:foo)

I don't know any others, but there may be some lurking around in there...