Programs & Examples On #Cfdocument

CFDocument is a tag in the CFML language used to dynamically create PDFs. It translates generated HTML/CSS into postscript and either outputs a PDF to the browser or saves it to a file.

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

XMLHttpRequest is a standard object in the JavaScript Object model.

According to Wikipedia, XMLHttpRequest first appeared in Internet Explorer 5 as an ActiveX object, but has since been made into a standard and has been included for use in JavaScript in the Mozilla family since 1.0, Apple Safari 1.2, Opera 7.60-p1, and IE 7.0.

The open() method on the object takes the HTTP Method as an argument - and is specified as taking any valid HTTP method (see the item number 5 of the link) - including GET, POST, HEAD, PUT and DELETE, as specified by RFC 2616.

As a side note IE 7–8 only permit the following HTTP methods: "GET", "POST", "HEAD", "PUT", "DELETE", "MOVE", "PROPFIND", "PROPPATCH", "MKCOL", "COPY", "LOCK", "UNLOCK", and "OPTIONS".

Create a Dropdown List for MVC3 using Entity Framework (.edmx Model) & Razor Views && Insert A Database Record to Multiple Tables

Well, actually I'll have to say David is right with his solution, but there are some topics disturbing me:

  1. You should never send your model to the view => This is correct
  2. If you create a ViewModel, and include the Model as member in the ViewModel, then you effectively sent your model to the View => this is BAD
  3. Using dictionaries to send the options to the view => this not good style

So how can you create a better coupling?

I would use a tool like AutoMapper or ValueInjecter to map between ViewModel and Model. AutoMapper does seem to have the better syntax and feel to it, but the current version lacks a very severe topic: It is not able to perform the mapping from ViewModel to Model (under certain circumstances like flattening, etc., but this is off topic) So at present I prefer to use ValueInjecter.

So you create a ViewModel with the fields you need in the view. You add the SelectList items you need as lookups. And you add them as SelectLists already. So you can query from a LINQ enabled sourc, select the ID and text field and store it as a selectlist: You gain that you do not have to create a new type (dictionary) as lookup and you just move the new SelectList from the view to the controller.

  // StaffTypes is an IEnumerable<StaffType> from dbContext
  // viewModel is the viewModel initialized to copy content of Model Employee  
  // viewModel.StaffTypes is of type SelectList

  viewModel.StaffTypes =
    new SelectList(
        StaffTypes.OrderBy( item => item.Name )
        "StaffTypeID",
        "Type",
        viewModel.StaffTypeID
    );

In the view you just have to call

@Html.DropDownListFor( model => mode.StaffTypeID, model.StaffTypes )

Back in the post element of your method in the controller you have to take a parameter of the type of your ViewModel. You then check for validation. If the validation fails, you have to remember to re-populate the viewModel.StaffTypes SelectList, because this item will be null on entering the post function. So I tend to have those population things separated into a function. You just call back return new View(viewModel) if anything is wrong. Validation errors found by MVC3 will automatically be shown in the view.

If you have your own validation code you can add validation errors by specifying which field they belong to. Check documentation on ModelState to get info on that.

If the viewModel is valid you have to perform the next step:

If it is a create of a new item, you have to populate a model from the viewModel (best suited is ValueInjecter). Then you can add it to the EF collection of that type and commit changes.

If you have an update, you get the current db item first into a model. Then you can copy the values from the viewModel back to the model (again using ValueInjecter gets you do that very quick). After that you can SaveChanges and are done.

Feel free to ask if anything is unclear.

GROUP BY having MAX date

There's no need to group in that subquery... a where clause would suffice:

SELECT * FROM tblpm n
WHERE date_updated=(SELECT MAX(date_updated)
    FROM tblpm WHERE control_number=n.control_number)

Also, do you have an index on the 'date_updated' column? That would certainly help.

Javascript .querySelector find <div> by innerTEXT

You best see if you have a parent element of the div you are querying. If so get the parent element and perform an element.querySelectorAll("div"). Once you get the nodeList apply a filter on it over the innerText property. Assume that a parent element of the div that we are querying has an id of container. You can normally access container directly from the id but let's do it the proper way.

var conty = document.getElementById("container"),
     divs = conty.querySelectorAll("div"),
    myDiv = [...divs].filter(e => e.innerText == "SomeText");

So that's it.

PHP Get Site URL Protocol - http vs https

Here is how I do it ... it is a shorthand if else version of Rid Iculous's answer ...

$protocol = isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on' || $_SERVER['HTTPS'] === 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ? 'https' : 'http';

Rails DateTime.now without Time

If you want today's date without the time, just use Date.today

jquery change button color onclick

I would just create a separate CSS class:

.ButtonClicked {
    background-color:red;
}

And then add the class on click:

$('#ButtonId').on('click',function(){
    !$(this).hasClass('ButtonClicked') ? addClass('ButtonClicked') : '';
});

This should do what you're looking for, showing by this jsFiddle. If you're curious about the logic with the ? and such, its called ternary (or conditional) operators, and its just a concise way to do the simple if logic to check if the class has already been added.

You can also create the ability to have an "on/off" switch feel by toggling the class:

$('#ButtonId').on('click',function(){
    $(this).toggleClass('ButtonClicked');
});

Shown by this jsFiddle. Just food for thought.

How can I unstage my files again after making a local commit?

For unstaging all the files in your last commit -

git reset HEAD~

Could not install packages due to an EnvironmentError: [Errno 13]

I also had the same problem, I tried many different command lines, this one worked for me:

Try:

    conda install py-xgboost

That's what I got:

Collecting package metadata: done
Solving environment: done

## Package Plan ##

  environment location: /home/simplonco/anaconda3

  added / updated specs:
    - py-xgboost


The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    _py-xgboost-mutex-2.0      |            cpu_0           9 KB
    ca-certificates-2019.1.23  |                0         126 KB
    certifi-2018.11.29         |           py37_0         146 KB
    conda-4.6.2                |           py37_0         1.7 MB
    libxgboost-0.80            |       he6710b0_0         3.7 MB
    mkl-2019.1                 |              144       204.6 MB
    mkl_fft-1.0.10             |   py37ha843d7b_0         169 KB
    mkl_random-1.0.2           |   py37hd81dba3_0         405 KB
    numpy-1.15.4               |   py37h7e9f1db_0          47 KB
    numpy-base-1.15.4          |   py37hde5b4d6_0         4.2 MB
    py-xgboost-0.80            |   py37he6710b0_0         1.7 MB
    scikit-learn-0.20.2        |   py37hd81dba3_0         5.7 MB
    scipy-1.2.0                |   py37h7c811a0_0        17.7 MB
    ------------------------------------------------------------
                                           Total:       240.0 MB

The following NEW packages will be INSTALLED:

  _py-xgboost-mutex  pkgs/main/linux-64::_py-xgboost-mutex-2.0-cpu_0
  libxgboost         pkgs/main/linux-64::libxgboost-0.80-he6710b0_0
  py-xgboost         pkgs/main/linux-64::py-xgboost-0.80-py37he6710b0_0

The following packages will be UPDATED:

  ca-certificates     anaconda::ca-certificates-2018.12.5-0 --> pkgs/main::ca-certificates-2019.1.23-0
  mkl                                            2019.0-118 --> 2019.1-144
  mkl_fft                              1.0.4-py37h4414c95_1 --> 1.0.10-py37ha843d7b_0
  mkl_random                           1.0.1-py37h4414c95_1 --> 1.0.2-py37hd81dba3_0
  numpy                               1.15.1-py37h1d66e8a_0 --> 1.15.4-py37h7e9f1db_0
  numpy-base                          1.15.1-py37h81de0dd_0 --> 1.15.4-py37hde5b4d6_0
  scikit-learn                        0.19.2-py37h4989274_0 --> 0.20.2-py37hd81dba3_0
  scipy                                1.1.0-py37hfa4b5c9_1 --> 1.2.0-py37h7c811a0_0

The following packages will be SUPERSEDED by a higher-priority channel:

  certifi                                          anaconda --> pkgs/main
  conda                                            anaconda --> pkgs/main
  openssl                anaconda::openssl-1.1.1-h7b6447c_0 --> pkgs/main::openssl-1.1.1a-h7b6447c_0


Proceed ([y]/n)? y


Downloading and Extracting Packages
libxgboost-0.80      | 3.7 MB    | ##################################### | 100% 
mkl_random-1.0.2     | 405 KB    | ##################################### | 100% 
certifi-2018.11.29   | 146 KB    | ##################################### | 100% 
ca-certificates-2019 | 126 KB    | ##################################### | 100% 
conda-4.6.2          | 1.7 MB    | ##################################### | 100% 
mkl-2019.1           | 204.6 MB  | ##################################### | 100% 
mkl_fft-1.0.10       | 169 KB    | ##################################### | 100% 
numpy-1.15.4         | 47 KB     | ##################################### | 100% 
scipy-1.2.0          | 17.7 MB   | ##################################### | 100% 
scikit-learn-0.20.2  | 5.7 MB    | ##################################### | 100% 
py-xgboost-0.80      | 1.7 MB    | ##################################### | 100% 
_py-xgboost-mutex-2. | 9 KB      | ##################################### | 100% 
numpy-base-1.15.4    | 4.2 MB    | ##################################### | 100% 
Preparing transaction: done
Verifying transaction: done
Executing transaction: done

Random record from MongoDB

If you have a simple id key, you could store all the id's in an array, and then pick a random id. (Ruby answer):

ids = @coll.find({},fields:{_id:1}).to_a
@coll.find(ids.sample).first

getting the reason why websockets closed with close code 1006

It looks like this is the case when Chrome is not compliant with WebSocket standard. When the server initiates close and sends close frame to a client, Chrome considers this to be an error and reports it to JS side with code 1006 and no reason message. In my tests, Chrome never responds to server-initiated close frames (close code 1000) suggesting that code 1006 probably means that Chrome is reporting its own internal error.

P.S. Firefox v57.00 handles this case properly and successfully delivers server's reason message to JS side.

Twitter Bootstrap Button Text Word Wrap

You can simply add this class.

.btn {
    white-space:normal !important;
    word-wrap: break-word; 
}

Markdown to create pages and table of contents?

I just coded an extension for python-markdown, which uses its parser to retrieve headings, and outputs a TOC as Markdown-formatted unordered list with local links. The file is

... and it should be placed in markdown/extensions/ directory in the markdown installation. Then, all you have to do, is type anchor <a> tags with an id="..." attribute as a reference - so for an input text like this:

$ cat test.md 
Hello
=====

## <a id="sect one"></a>SECTION ONE ##

something here

### <a id='sect two'>eh</a>SECTION TWO ###

something else

#### SECTION THREE

nothing here

### <a id="four"></a>SECTION FOUR

also...

... the extension can be called like this:

$ python -m markdown -x md_toc test.md 
* Hello
    * [SECTION ONE](#sect one)
        * [SECTION TWO](#sect two)
            * SECTION THREE
        * [SECTION FOUR](#four)

... and then you can paste back this toc in your markdown document (or have a shortcut in your text editor, that calls the script on the currently open document, and then inserts the resulting TOC in the same document).

Note that older versions of python-markdown don't have a __main__.py module, and as such, the command line call as above will not work for those versions.

How to update Xcode from command line

I encountered the same issue when I uninstalled the complete version of Xcode to reinstall the CLI version. My fix was:

sudo xcode-select -s /Library/Developer/CommandLineTools

How to make an unaware datetime timezone aware in python

Here is a simple solution to minimize changes to your code:

from datetime import datetime
import pytz

start_utc = datetime.utcnow()
print ("Time (UTC): %s" % start_utc.strftime("%d-%m-%Y %H:%M:%S"))

Time (UTC): 09-01-2021 03:49:03

tz = pytz.timezone('Africa/Cairo')
start_tz = datetime.now().astimezone(tz)
print ("Time (RSA): %s" % start_tz.strftime("%d-%m-%Y %H:%M:%S"))

Time (RSA): 09-01-2021 05:49:03

What is the difference between %g and %f in C?

They are both examples of floating point input/output.

%g and %G are simplifiers of the scientific notation floats %e and %E.

%g will take a number that could be represented as %f (a simple float or double) or %e (scientific notation) and return it as the shorter of the two.

The output of your print statement will depend on the value of sum.

Android Studio - debug keystore

If you use Windows, you will found it follow this: File-->Project Structure-->Facets

chose your Android project and in the "Facet 'Android'" window click TAB "Packaging",you will found what you want

What size do you use for varchar(MAX) in your parameter declaration?

If you do something like this:

    cmd.Parameters.Add("@blah",SqlDbType.VarChar).Value = "some large text";

size will be taken from "some large text".Length

This can be problematic when it's an output parameter, you get back no more characters then you put as input.

How to have image and text side by side

Use following code : jsfiddle.net/KqHEC/

HTML

<div class='container2'>
        <div class="left">
            <img src='http://ecx.images-amazon.com/images/I/21-leKb-zsL._SL500_AA300_.png' class='iconDetails'>
        </div>  
    <div   class="right" >
    <h4>Facebook</h4>
    <div style="font-size:.7em;width:160px;float:left;">fine location, GPS, coarse location</div>
    <div style="float:right;font-size:.7em">0 mins ago</div>
    </div>
</div>

CSS

.iconDetails {
 margin-left:2%;
float:left; 
height:40px;
width:40px; 
} 

.container2 {
    width:270px;
    height:auto;
    padding:1%;
    float:left;
}
h4{margin:0}
.left {float:left;width:45px;}
.right {float:left;margin:0 0 0 5px;width:215px;}

http://jsfiddle.net/KqHEC/1/

How can I remove non-ASCII characters but leave periods and spaces using Python?

You may use the following code to remove non-English letters:

import re
str = "123456790 ABC#%? .(???)"
result = re.sub(r'[^\x00-\x7f]',r'', str)
print(result)

This will return

123456790 ABC#%? .()

.gitignore file for java eclipse project

You need to add your source files with git add or the GUI equivalent so that Git will begin tracking them.

Use git status to see what Git thinks about the files in any given directory.

Stretch image to fit full container width bootstrap

Check if this solves the problem:

<div class="container-fluid no-padding">
  <div class="row">
    <div class="col-md-12">
      <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=1300%C3%97400&w=1300&h=400" alt="placeholder 960" class="img-responsive" />
    </div>
  </div>
</div>

CSS

.no-padding {
  padding-left: 0;
  padding-right: 0;
}

Css class no-padding will override default bootstrap container padding.

Full example here.


@Update If you use bootstrap 4 it could be done even simpler

<div class="container-fluid px-0">
  <div class="row">
    <div class="col-md-12">
      <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=1300%C3%97400&w=1300&h=400" alt="placeholder 960" class="img-responsive" />
    </div>
   </div>
</div>

Updated example here.

Use of REPLACE in SQL Query for newline/ carriage return characters

There are probably embedded tabs (CHAR(9)) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:

DECLARE @var NVARCHAR(255), @i INT;

SET @i = 1;

SELECT @var = AccountType FROM dbo.Account
  WHERE AccountNumber = 200
  AND AccountType LIKE '%Daily%';

CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));

WHILE @i <= LEN(@var)
BEGIN
  INSERT #x 
    SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));

  SET @i = @i + 1;
END

SELECT i,c,a FROM #x ORDER BY i;

You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.

What is a Sticky Broadcast?

sendStickyBroadcast() performs a sendBroadcast(Intent) known as sticky, i.e. the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(Intent). One example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED. When you call registerReceiver() for that action -- even with a null BroadcastReceiver -- you get the Intent that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.

Using Pip to install packages to Anaconda Environment

Uninstall the duplicated python installation. Just keep anaconda and create an env with the desired python version as specified here: https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-python.html. Then your python and pip versions will change as you switch between envs.

Trigger change event <select> using jquery

If you want to do some checks then use this way

 <select size="1" name="links" onchange="functionToTriggerClick(this.value)">
    <option value="">Select a Search Engine</option>        
    <option value="http://www.google.com">Google</option>
    <option value="http://www.yahoo.com">Yahoo</option>
</select>

<script>

   function functionToTriggerClick(link) {

     if(link != ''){
        window.location.href=link;
        }
    }  

</script>

How do I install the ext-curl extension with PHP 7?

If you are using PHP7.1 ( try php -version to find your PHP version)

sudo apt-get install php7.1-curl

then restart apache

sudo service apache2 restart

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

ECMAScript 6 introduced String.prototype.includes:

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

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

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

How do I download a file with Angular2 or greater

 let headers = new Headers({
                'Content-Type': 'application/json',
                'MyApp-Application': 'AppName',
                'Accept': 'application/vnd.ms-excel'
            });
            let options = new RequestOptions({
                headers: headers,
                responseType: ResponseContentType.Blob
            });


this.http.post(this.urlName + '/services/exportNewUpc', localStorageValue, options)
                .subscribe(data => {
                    if (navigator.appVersion.toString().indexOf('.NET') > 0)
                    window.navigator.msSaveBlob(data.blob(), "Export_NewUPC-Items_" + this.selectedcategory + "_" + this.retailname +"_Report_"+this.myDate+".xlsx");

                    else {
                        var a = document.createElement("a");
                        a.href = URL.createObjectURL(data.blob());
                        a.download = "Export_NewUPC-Items_" + this.selectedcategory + "_" + this.retailname +"_Report_"+this.myDate+ ".xlsx";
                        a.click();
                    }
                    this.ui_loader = false;
                    this.selectedexport = 0;
                }, error => {
                    console.log(error.json());
                    this.ui_loader = false;
                    document.getElementById("exceptionerror").click();
                });

Looping through all the properties of object php

Before you run the $object through a foreach loop you have to convert it to an array:

$array = (array) $object;  

 foreach($array as $key=>$val){
      echo "$key: $val";
      echo "<br>";
 }

What does request.getParameter return?

Both if (one.length() > 0) {} and if (!"".equals(one)) {} will check against an empty foo parameter, and an empty parameter is what you'd get if the the form is submitted with no value in the foo text field.

If there's any chance you can use the Expression Language to handle the parameter, you could access it with empty param.foo in an expression.

<c:if test='${not empty param.foo}'>
    This page code gets rendered.
</c:if>

Beginner question: returning a boolean value from a function in Python

Ignoring the refactoring issues, you need to understand functions and return values. You don't need a global at all. Ever. You can do this:

def rps():
    # Code to determine if player wins
    if player_wins:
        return True

    return False

Then, just assign a value to the variable outside this function like so:

player_wins = rps()

It will be assigned the return value (either True or False) of the function you just called.


After the comments, I decided to add that idiomatically, this would be better expressed thus:

 def rps(): 
     # Code to determine if player wins, assigning a boolean value (True or False)
     # to the variable player_wins.

     return player_wins

 pw = rps()

This assigns the boolean value of player_wins (inside the function) to the pw variable outside the function.

How to iterate over the keys and values with ng-repeat in AngularJS?

How about:

<table>
  <tr ng-repeat="(key, value) in data">
    <td> {{key}} </td> <td> {{ value }} </td>
  </tr>
</table>

This method is listed in the docs: https://docs.angularjs.org/api/ng/directive/ngRepeat

JQuery DatePicker ReadOnly

onkeypress = > preventdefault ...

Get local IP address in Node.js

Running programs to parse the results seems a bit iffy. Here's what I use.

require('dns').lookup(require('os').hostname(), function (err, add, fam) {
  console.log('addr: ' + add);
})

This should return your first network interface local IP address.

How to add extension methods to Enums

A Simple workaround.

public static class EnumExtensions
{
    public static int ToInt(this Enum payLoad) {

        return ( int ) ( IConvertible ) payLoad;

    }
}

int num = YourEnum.AItem.ToInt();
Console.WriteLine("num : ", num);

How to dynamically change the color of the selected menu item of a web page?

Set the styles for class active and hover:


Than you need to make the li active, on the server side. So when you are drawing the menu, you should know which page is loaded and set it to:

 <li class="active">Question</li>
 <li>Tags</li>
 <li>Users</li>

But if you are changing the content without reloading, you cannot change set the active li element on the server, you need to use javascript:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<style>
  .menu{width: 300px; height: 25; font-size: 18px;}
  .menu li{list-style: none; float: left; margin-right: 4px; padding: 5px;}
  .menu li:hover, .menu li.active {
        background-color: #f90;
    }
</style>
</head>
<body>

<ul class="menu">
<li>Item 1</li>
<li class="active">Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>

<script type="text/javascript">

var make_button_active = function()
{
  //Get item siblings
  var siblings =($(this).siblings());

  //Remove active class on all buttons
  siblings.each(function (index)
    {
      $(this).removeClass('active');
    }
  )


  //Add the clicked button class
  $(this).addClass('active');
}

//Attach events to menu
$(document).ready(
  function()
  {
    $(".menu li").click(make_button_active);
  }  
)

</script>
</body>

</html>

What is polymorphism, what is it for, and how is it used?

I know this is an older question with a lot of good answers but I'd like to include a one sentence answer:

Treating a derived type as if it were it's base type.

There are plenty of examples above that show this in action, but I feel this is a good concise answer.

How to use CURL via a proxy?

root@APPLICATIOSERVER:/var/www/html# php connectiontest.php
61e23468-949e-4103-8e08-9db09249e8s1 OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to 10.172.123.1:80 root@APPLICATIOSERVER:/var/www/html#

Post declaring the proxy settings in the php script file issue has been fixed.

$proxy = '10.172.123.1:80';
curl_setopt($cSession, CURLOPT_PROXY, $proxy); // PROXY details with port

git: diff between file in local repo and origin

To view the differences going from the remote file to the local file:

git diff remotename/branchname:remote/path/file1.txt local/path/file1.txt

To view the differences in the other direction:

git diff HEAD:local/path/file1.txt remotename/branchname:remote/path/file1.txt

Basically you can diff any two files anywhere using this notation:

git diff ref1:path/to/file1 ref2:path/to/file2

As usual, ref1 and ref2 could be branch names, remotename/branchname, commit SHAs, etc.

Is there an online application that automatically draws tree structures for phrases/sentences?

In short, yes. I assume you're looking to parse English: for that you can use the Link Parser from Carnegie Mellon.

It is important to remember that there are many theories of syntax, that can give completely different-looking phrase structure trees; further, the trees are different for each language, and tools may not exist for those languages.

As a note for the future: if you need a sentence parsed out and tag it as linguistics (and syntax or whatnot, if that's available), someone can probably parse it out for you and guide you through it.

Hibernate dialect for Oracle Database 11g?

Add org.hibernate.dialect.OracleDialect for Oracle11g database. It will resolve this error.

How to manually trigger click event in ReactJS?

You could use the ref prop to acquire a reference to the underlying HTMLInputElement object through a callback, store the reference as a class property, then use that reference to later trigger a click from your event handlers using the HTMLElement.click method.

In your render method:

<input ref={input => this.inputElement = input} ... />

In your event handler:

this.inputElement.click();

Full example:

class MyComponent extends React.Component {
  render() {
    return (
      <div onClick={this.handleClick}>
        <input ref={input => this.inputElement = input} />
      </div>
    );
  }

  handleClick = (e) => {
    this.inputElement.click();
  }
}

Note the ES6 arrow function that provides the correct lexical scope for this in the callback. Also note, that the object you acquire this way is an object akin to what you would acquire using document.getElementById, i.e. the actual DOM-node.

JavaFX FXML controller - constructor vs initialize method

The initialize method is called after all @FXML annotated members have been injected. Suppose you have a table view you want to populate with data:

class MyController { 
    @FXML
    TableView<MyModel> tableView; 

    public MyController() {
        tableView.getItems().addAll(getDataFromSource()); // results in NullPointerException, as tableView is null at this point. 
    }

    @FXML
    public void initialize() {
        tableView.getItems().addAll(getDataFromSource()); // Perfectly Ok here, as FXMLLoader already populated all @FXML annotated members. 
    }
}

Invoke(Delegate)

Delegate are essentially inline Action's or Func<T>. You can declare a delegate outside the scope of a method which you are running or using a lambda expression(=>); because you run the delegate within a method, you run it on the thread which is being run for the current window/application which is the bit in bold.

Lambda example

int AddFiveToNumber(int number)
{
  var d = (int i => i + 5);
  d.Invoke(number);
}

How do I stop Notepad++ from showing autocomplete for all words in the file

Notepad++ provides 2 types of features:

  • Auto-completion that read the open file and provide suggestion of words and/or functions within the file
  • Suggestion with the arguments of functions (specific to the language)

Based on what you write, it seems what you want is auto-completion on function only + suggestion on arguments.

To do that, you just need to change a setting.

  1. Go to Settings > Preferences... > Auto-completion
  2. Check Enable Auto-completion on each input
  3. Select Function completion and not Word completion
  4. Check Function parameter hint on input (if you have this option)

On version 6.5.5 of Notepad++, I have this setting settings

Some documentation about auto-completion is available in Notepad++ Wiki.

Generating Random Number In Each Row In Oracle Query

Something like?

select t.*, round(dbms_random.value() * 8) + 1 from foo t;

Edit: David has pointed out this gives uneven distribution for 1 and 9.

As he points out, the following gives a better distribution:

select t.*, floor(dbms_random.value(1, 10)) from foo t;

Where does MySQL store database files on Windows and what are the names of the files?

in MySQL are
".myd" a database self and
".tmd" a temporal file.
But sometimes I see also ".sql".

It depends on your settings and/or export method.

How to declare std::unique_ptr and what is the use of it?

Unique pointers are guaranteed to destroy the object they manage when they go out of scope. http://en.cppreference.com/w/cpp/memory/unique_ptr

In this case:

unique_ptr<double> uptr2 (pd);

pd will be destroyed when uptr2 goes out of scope. This facilitates memory management by automatic deletion.

The case of unique_ptr<int> uptr (new int(3)); is not different, except that the raw pointer is not assigned to any variable here.

Value does not fall within the expected range

In case of WSS 3.0 recently I experienced same issue. It was because of column that was accessed from code was not present in the wss list.

How to count no of lines in text file and store the value into a variable using batch script?

The :countLines subroutine below accepts two parameters: a variable name; and a filename. The number of lines in the file are counted, the result is stored in the variable, and the result is passed back to the main program.

The code has the following features:

  • Reads files with Windows or Unix line endings.
  • Handles Unicode as well as ANSI/ASCII text files.
  • Copes with extremely long lines.
  • Isn’t fazed by the null character.
  • Raises an error on reading an empty file.
  • Counts beyond the Batch max int limit of (31^2)-1.
@echo off & setLocal enableExtensions disableDelayedExpansion

call :countLines noOfLines "%~1" || (
    >&2 echo(file "%~nx1" is empty & goto end
) %= cond exec =%
echo(file "%~nx1" has %noOfLines% line(s)

:end - exit program with appropriate errorLevel
endLocal & goto :EOF

:countLines result= "%file%"
:: counts the number of lines in a file
setLocal disableDelayedExpansion
(set "lc=0" & call)

for /f "delims=:" %%N in ('
    cmd /d /a /c type "%~2" ^^^& ^<nul set /p "=#" ^| (^
    2^>nul findStr /n "^" ^&^& echo(^) ^| ^
    findStr /blv 1: ^| 2^>nul findStr /lnxc:" "
') do (set "lc=%%N" & call;) %= for /f =%

endlocal & set "%1=%lc%"
exit /b %errorLevel% %= countLines =%

I know it looks hideous, but it covers most edge-cases and is surprisingly fast.

Is it necessary to assign a string to a variable before comparing it to another?

Brian, also worth throwing in here - the others are of course correct that you don't need to declare a string variable. However, next time you want to declare a string you don't need to do the following:

NSString *myString = [[NSString alloc] initWithFormat:@"SomeText"];

Although the above does work, it provides a retained NSString variable which you will then need to explicitly release after you've finished using it.

Next time you want a string variable you can use the "@" symbol in a much more convenient way:

NSString *myString = @"SomeText";

This will be autoreleased when you've finished with it so you'll avoid memory leaks too...

Hope that helps!

Why Visual Studio 2015 can't run exe file (ucrtbased.dll)?

I would like to suggest additional solution to fix this issue. So, I recommend to reinstall/install the latest Windows SDK. In my case it has helped me to fix the issue when using Qt with MSVC compiler to debug a program.

How to handle checkboxes in ASP.NET MVC forms?

<input type = "checkbox" name = "checkbox1" /> <label> Check to say hi.</label>

From the Controller:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Index(FormCollection fc)
    {

         var s = fc["checkbox1"];

         if (s == "on")
         {
             string x = "Hi";
         }
    }

Java Package Does Not Exist Error

I was having this problem, while trying to use a theme packaged as .jar in my app, it was working while debugging the app, but it didn't when building/exporting the app.

I solved it by unzipping the jar, and manually add its contents to my build folder, resulting in this:

project/
   ¦
   +-- build 
   ¦   +-- classes
   ¦       +-- pt
   ¦       ¦   +-- myAppName ... 
   ¦       +-- com
   ¦           +-- themeName ...
   +-- src
   +-- lib

I don't have the error anymore and my app loads with the intended theme.

Group by in LINQ

An alternative way to do this could be select distinct PersonId and group join with persons:

var result = 
    from id in persons.Select(x => x.PersonId).Distinct()
    join p2 in persons on id equals p2.PersonId into gr // apply group join here
    select new 
    {
        PersonId = id,
        Cars = gr.Select(x => x.Car).ToList(),
    };

Or the same with fluent API syntax:

var result = persons.Select(x => x.PersonId).Distinct()
    .GroupJoin(persons, id => id, p => p.PersonId, (id, gr) => new
    {
        PersonId = id,
        Cars = gr.Select(x => x.Car).ToList(),
    });

GroupJoin produces a list of entries in the first list ( list of PersonId in our case), each with a group of joined entries in the second list (list of persons).

How to read a .xlsx file using the pandas Library in iPython?

I usually create a dictionary containing a DataFrame for every sheet:

xl_file = pd.ExcelFile(file_name)

dfs = {sheet_name: xl_file.parse(sheet_name) 
          for sheet_name in xl_file.sheet_names}

Update: In pandas version 0.21.0+ you will get this behavior more cleanly by passing sheet_name=None to read_excel:

dfs = pd.read_excel(file_name, sheet_name=None)

In 0.20 and prior, this was sheetname rather than sheet_name (this is now deprecated in favor of the above):

dfs = pd.read_excel(file_name, sheetname=None)

TSQL CASE with if comparison in SELECT statement

Should be:

SELECT registrationDate, 
       (SELECT CASE
        WHEN COUNT(*)< 2 THEN 'Ama'
        WHEN COUNT(*)< 5 THEN 'SemiAma' 
        WHEN COUNT(*)< 7 THEN 'Good'  
        WHEN COUNT(*)< 9 THEN 'Better' 
        WHEN COUNT(*)< 12 THEN 'Best'
        ELSE 'Outstanding'
        END as a FROM Articles 
        WHERE Articles.userId = Users.userId) as ranking,
        (SELECT COUNT(*) 
        FROM Articles 
        WHERE userId = Users.userId) as articleNumber,
hobbies, etc...
FROM USERS

/exclude in xcopy just for a file type

The /EXCLUDE: argument expects a file containing a list of excluded files.

So create a file called excludedfileslist.txt containing:

.cs\

Then a command like this:

xcopy /r /d /i /s /y /exclude:excludedfileslist.txt C:\dev\apan C:\web\apan

Alternatively you could use Robocopy, but would require installing / copying a robocopy.exe to the machines.

Update

An anonymous comment edit which simply stated "This Solution exclude also css file!"

This is true creating a excludedfileslist.txt file contain just:

.cs

(note no backslash on the end)

Will also exclude all of the following:

  • file1.cs
  • file2.css
  • dir1.cs\file3.txt
  • dir2\anyfile.cs.something.txt

Sometimes people don't read or understand the XCOPY command's help, here is an item I would like to highlight:

Using /exclude

  • List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.

As the example states it excludes "all files with the .obj extension" but it doesn't state that it also excludes files or directories named file1.obj.tmp or dir.obj.output\example2.txt.

There is a way around .css files being excluded also, change the excludedfileslist.txt file to contain just:

.cs\

(note the backslash on the end).

Here is a complete test sequence for your reference:

C:\test1>ver

Microsoft Windows [Version 6.1.7601]

C:\test1>md src
C:\test1>md dst
C:\test1>md src\dir1
C:\test1>md src\dir2.cs
C:\test1>echo "file contents" > src\file1.cs
C:\test1>echo "file contents" > src\file2.css
C:\test1>echo "file contents" > src\dir1\file3.txt
C:\test1>echo "file contents" > src\dir1\file4.cs.txt
C:\test1>echo "file contents" > src\dir2.cs\file5.txt

C:\test1>xcopy /r /i /s /y .\src .\dst
.\src\file1.cs
.\src\file2.css
.\src\dir1\file3.txt
.\src\dir1\file4.cs.txt
.\src\dir2.cs\file5.txt
5 File(s) copied

C:\test1>echo .cs > excludedfileslist.txt
C:\test1>xcopy /r /i /s /y /exclude:excludedfileslist.txt .\src .\dst
.\src\dir1\file3.txt
1 File(s) copied

C:\test1>echo .cs\ > excludedfileslist.txt
C:\test1>xcopy /r /i /s /y /exclude:excludedfileslist.txt .\src .\dst
.\src\file2.css
.\src\dir1\file3.txt
.\src\dir1\file4.cs.txt
3 File(s) copied

This test was completed on a Windows 7 command line and retested on Windows 10 "10.0.14393".

Note that the last example does exclude .\src\dir2.cs\file5.txt which may or may not be unexpected for you.

What are the complexity guarantees of the standard containers?

I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).

Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.

Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.

How to show multiline text in a table cell

I use the html code tag after each line (see below) and it works for me.

George Benson </br> 123 Main Street </br> New York, Ny 12344 </br>

How to set a variable inside a loop for /F

To expand on the answer I came here to get a better understanding so I wrote this that can explain it and helped me too.

It has the setlocal DisableDelayedExpansion in there so you can locally set this as you wish between the setlocal EnableDelayedExpansion and it.

@echo off
title %~nx0
for /f "tokens=*" %%A in ("Some Thing") do (
  setlocal EnableDelayedExpansion
  set z=%%A
  echo !z!        Echoing the assigned variable in setlocal scope.
  echo %%A        Echoing the variable in local scope.
  setlocal DisableDelayedExpansion
  echo !z!        &rem !z!           Neither of these now work, which makes sense.
  echo %z%        &rem ECHO is off.  Neither of these now work, which makes sense.
  echo %%A        Echoing the variable in its local scope, will always work.
  )

Where can I view Tomcat log files in Eclipse?

I'm not sure if you were after catalina.out or one of the other logs produced by Tomcat.

But, if you're after the catalina.out log file then follow the directions below:

  • In the servers tab, double-click on the Tomcat Server. You will get a screen called Overview.

  • Click on "Open launch configuration". Click on the "Common" tab.

  • Towards the bottom of the screen you can check the "File" checkbox and then specify a file that can be used to log your console (catalina.out) output.

  • Finally, restart the Tomcat server.

What is the use of the init() usage in JavaScript?

In JavaScript when you create any object through a constructor call like below

step 1 : create a function say Person..

function Person(name){
this.name=name;
}
person.prototype.print=function(){
console.log(this.name);
}

step 2 : create an instance for this function..

var obj=new Person('venkat')

//above line will instantiate this function(Person) and return a brand new object called Person {name:'venkat'}

if you don't want to instantiate this function and call at same time.we can also do like below..

var Person = {
  init: function(name){
    this.name=name;
  },
  print: function(){
    console.log(this.name);
  }
};
var obj=Object.create(Person);
obj.init('venkat');
obj.print();

in the above method init will help in instantiating the object properties. basically init is like a constructor call on your class.

Getting hold of the outer class object from the inner class object

You could (but you shouldn't) use reflection for the job:

import java.lang.reflect.Field;

public class Outer {
    public class Inner {
    }

    public static void main(String[] args) throws Exception {

        // Create the inner instance
        Inner inner = new Outer().new Inner();

        // Get the implicit reference from the inner to the outer instance
        // ... make it accessible, as it has default visibility
        Field field = Inner.class.getDeclaredField("this$0");
        field.setAccessible(true);

        // Dereference and cast it
        Outer outer = (Outer) field.get(inner);
        System.out.println(outer);
    }
}

Of course, the name of the implicit reference is utterly unreliable, so as I said, you shouldn't :-)

Cordova : Requirements check failed for JDK 1.8 or greater

Today I also got this error Cordova : Requirements check failed for JDK 1.8 or greater in my Mac OS while build Ionic App when I run command ionic cordova build --release android via terminal.

Below command resolve my issue :-

export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.8.0_231.jdk/Contents/Home"

Hope it will help someone in future!

Is it possible to put CSS @media rules inline?

Inline styles cannot currently contain anything other than declarations (property: value pairs).

You can use style elements with appropriate media attributes in head section of your document.

Modulo operation with negative numbers

C99 requires that when a/b is representable:

(a/b) * b + a%b shall equal a

This makes sense, logically. Right?

Let's see what this leads to:


Example A. 5/(-3) is -1

=> (-1) * (-3) + 5%(-3) = 5

This can only happen if 5%(-3) is 2.


Example B. (-5)/3 is -1

=> (-1) * 3 + (-5)%3 = -5

This can only happen if (-5)%3 is -2

How to get active user's UserDetails

Preamble: Since Spring-Security 3.2 there is a nice annotation @AuthenticationPrincipal described at the end of this answer. This is the best way to go when you use Spring-Security >= 3.2.

When you:

  • use an older version of Spring-Security,
  • need to load your custom User Object from the Database by some information (like the login or id) stored in the principal or
  • want to learn how a HandlerMethodArgumentResolver or WebArgumentResolver can solve this in an elegant way, or just want to an learn the background behind @AuthenticationPrincipal and AuthenticationPrincipalArgumentResolver (because it is based on a HandlerMethodArgumentResolver)

then keep on reading — else just use @AuthenticationPrincipal and thank to Rob Winch (Author of @AuthenticationPrincipal) and Lukas Schmelzeisen (for his answer).

(BTW: My answer is a bit older (January 2012), so it was Lukas Schmelzeisen that come up as the first one with the @AuthenticationPrincipal annotation solution base on Spring Security 3.2.)


Then you can use in your controller

public ModelAndView someRequestHandler(Principal principal) {
   User activeUser = (User) ((Authentication) principal).getPrincipal();
   ...
}

That is ok if you need it once. But if you need it several times its ugly because it pollutes your controller with infrastructure details, that normally should be hidden by the framework.

So what you may really want is to have a controller like this:

public ModelAndView someRequestHandler(@ActiveUser User activeUser) {
   ...
}

Therefore you only need to implement a WebArgumentResolver. It has a method

Object resolveArgument(MethodParameter methodParameter,
                   NativeWebRequest webRequest)
                   throws Exception

That gets the web request (second parameter) and must return the User if its feels responsible for the method argument (the first parameter).

Since Spring 3.1 there is a new concept called HandlerMethodArgumentResolver. If you use Spring 3.1+ then you should use it. (It is described in the next section of this answer))

public class CurrentUserWebArgumentResolver implements WebArgumentResolver{

   Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) {
        if(methodParameter is for type User && methodParameter is annotated with @ActiveUser) {
           Principal principal = webRequest.getUserPrincipal();
           return (User) ((Authentication) principal).getPrincipal();
        } else {
           return WebArgumentResolver.UNRESOLVED;
        }
   }
}

You need to define the Custom Annotation -- You can skip it if every instance of User should always be taken from the security context, but is never a command object.

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ActiveUser {}

In the configuration you only need to add this:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"
    id="applicationConversionService">
    <property name="customArgumentResolver">
        <bean class="CurrentUserWebArgumentResolver"/>
    </property>
</bean>

@See: Learn to customize Spring MVC @Controller method arguments

It should be noted that if you're using Spring 3.1, they recommend HandlerMethodArgumentResolver over WebArgumentResolver. - see comment by Jay


The same with HandlerMethodArgumentResolver for Spring 3.1+

public class CurrentUserHandlerMethodArgumentResolver
                               implements HandlerMethodArgumentResolver {

     @Override
     public boolean supportsParameter(MethodParameter methodParameter) {
          return
              methodParameter.getParameterAnnotation(ActiveUser.class) != null
              && methodParameter.getParameterType().equals(User.class);
     }

     @Override
     public Object resolveArgument(MethodParameter methodParameter,
                         ModelAndViewContainer mavContainer,
                         NativeWebRequest webRequest,
                         WebDataBinderFactory binderFactory) throws Exception {

          if (this.supportsParameter(methodParameter)) {
              Principal principal = webRequest.getUserPrincipal();
              return (User) ((Authentication) principal).getPrincipal();
          } else {
              return WebArgumentResolver.UNRESOLVED;
          }
     }
}

In the configuration, you need to add this

<mvc:annotation-driven>
      <mvc:argument-resolvers>
           <bean class="CurrentUserHandlerMethodArgumentResolver"/>         
      </mvc:argument-resolvers>
 </mvc:annotation-driven>

@See Leveraging the Spring MVC 3.1 HandlerMethodArgumentResolver interface


Spring-Security 3.2 Solution

Spring Security 3.2 (do not confuse with Spring 3.2) has own build in solution: @AuthenticationPrincipal (org.springframework.security.web.bind.annotation.AuthenticationPrincipal) . This is nicely described in Lukas Schmelzeisen`s answer

It is just writing

ModelAndView someRequestHandler(@AuthenticationPrincipal User activeUser) {
    ...
 }

To get this working you need to register the AuthenticationPrincipalArgumentResolver (org.springframework.security.web.bind.support.AuthenticationPrincipalArgumentResolver) : either by "activating" @EnableWebMvcSecurity or by registering this bean within mvc:argument-resolvers - the same way I described it with may Spring 3.1 solution above.

@See Spring Security 3.2 Reference, Chapter 11.2. @AuthenticationPrincipal


Spring-Security 4.0 Solution

It works like the Spring 3.2 solution, but in Spring 4.0 the @AuthenticationPrincipal and AuthenticationPrincipalArgumentResolver was "moved" to an other package:

(But the old classes in its old packges still exists, so do not mix them!)

It is just writing

import org.springframework.security.core.annotation.AuthenticationPrincipal;
ModelAndView someRequestHandler(@AuthenticationPrincipal User activeUser) {
    ...
}

To get this working you need to register the (org.springframework.security.web.method.annotation.) AuthenticationPrincipalArgumentResolver : either by "activating" @EnableWebMvcSecurity or by registering this bean within mvc:argument-resolvers - the same way I described it with may Spring 3.1 solution above.

<mvc:annotation-driven>
    <mvc:argument-resolvers>
        <bean class="org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver" />
    </mvc:argument-resolvers>
</mvc:annotation-driven>

@See Spring Security 5.0 Reference, Chapter 39.3 @AuthenticationPrincipal

How do I clone a github project to run locally?

To clone a repository and place it in a specified directory use "git clone [url] [directory]". For example

git clone https://github.com/ryanb/railscasts-episodes.git Rails

will create a directory named "Rails" and place it in the new directory. Click here for more information.

List changes unexpectedly after assignment. How do I clone or copy it to prevent this?

Python 3.6 Timings

Here are the timing results using Python 3.6.8. Keep in mind these times are relative to one another, not absolute.

I stuck to only doing shallow copies, and also added some new methods that weren't possible in Python2, such as list.copy() (the Python3 slice equivalent) and two forms of list unpacking (*new_list, = list and new_list = [*list]):

METHOD                  TIME TAKEN
b = [*a]                2.75180600000021
b = a * 1               3.50215399999990
b = a[:]                3.78278899999986  # Python2 winner (see above)
b = a.copy()            4.20556500000020  # Python3 "slice equivalent" (see above)
b = []; b.extend(a)     4.68069800000012
b = a[0:len(a)]         6.84498999999959
*b, = a                 7.54031799999984
b = list(a)             7.75815899999997
b = [i for i in a]      18.4886440000000
b = copy.copy(a)        18.8254879999999
b = []
for item in a:
  b.append(item)        35.4729199999997

We can see the Python2 winner still does well, but doesn't edge out Python3 list.copy() by much, especially considering the superior readability of the latter.

The dark horse is the unpacking and repacking method (b = [*a]), which is ~25% faster than raw slicing, and more than twice as fast as the other unpacking method (*b, = a).

b = a * 1 also does surprisingly well.

Note that these methods do not output equivalent results for any input other than lists. They all work for sliceable objects, a few work for any iterable, but only copy.copy() works for more general Python objects.


Here is the testing code for interested parties (Template from here):

import timeit

COUNT = 50000000
print("Array duplicating. Tests run", COUNT, "times")
setup = 'a = [0,1,2,3,4,5,6,7,8,9]; import copy'

print("b = list(a)\t\t", timeit.timeit(stmt='b = list(a)', setup=setup, number=COUNT))
print("b = copy.copy(a)\t", timeit.timeit(stmt='b = copy.copy(a)', setup=setup, number=COUNT))
print("b = a.copy()\t\t", timeit.timeit(stmt='b = a.copy()', setup=setup, number=COUNT))
print("b = a[:]\t\t", timeit.timeit(stmt='b = a[:]', setup=setup, number=COUNT))
print("b = a[0:len(a)]\t\t", timeit.timeit(stmt='b = a[0:len(a)]', setup=setup, number=COUNT))
print("*b, = a\t\t\t", timeit.timeit(stmt='*b, = a', setup=setup, number=COUNT))
print("b = []; b.extend(a)\t", timeit.timeit(stmt='b = []; b.extend(a)', setup=setup, number=COUNT))
print("b = []; for item in a: b.append(item)\t", timeit.timeit(stmt='b = []\nfor item in a:  b.append(item)', setup=setup, number=COUNT))
print("b = [i for i in a]\t", timeit.timeit(stmt='b = [i for i in a]', setup=setup, number=COUNT))
print("b = [*a]\t\t", timeit.timeit(stmt='b = [*a]', setup=setup, number=COUNT))
print("b = a * 1\t\t", timeit.timeit(stmt='b = a * 1', setup=setup, number=COUNT))

What is getattr() exactly and how do I use it?

It is also clarifying from https://www.programiz.com/python-programming/methods/built-in/getattr

class Person:
    age = 23
    name = "Adam"

person = Person()
print('The age is:', getattr(person, "age"))
print('The age is:', person.age)

The age is: 23

The age is: 23

class Person:
    age = 23
    name = "Adam"

person = Person()

# when default value is provided
print('The sex is:', getattr(person, 'sex', 'Male'))

# when no default value is provided
print('The sex is:', getattr(person, 'sex'))

The sex is: Male

AttributeError: 'Person' object has no attribute 'sex'

HTML Agility pack - parsing tables

The most simple what I've found to get the XPath for a particular Element is to install FireBug extension for Firefox go to the site/webpage press F12 to bring up firebug; right select and right click the element on the page that you want to query and select "Inspect Element" Firebug will select the element in its IDE then right click the Element in Firebug and choose "Copy XPath" this function will give you the exact XPath Query you need to get the element you want using HTML Agility Library.

What is the difference between 'my' and 'our' in Perl?

print "package is: " . __PACKAGE__ . "\n";
our $test = 1;
print "trying to print global var from main package: $test\n";

package Changed;

{
        my $test = 10;
        my $test1 = 11;
        print "trying to print local vars from a closed block: $test, $test1\n";
}

&Check_global;

sub Check_global {
        print "trying to print global var from a function: $test\n";
}
print "package is: " . __PACKAGE__ . "\n";
print "trying to print global var outside the func and from \"Changed\" package:     $test\n";
print "trying to print local var outside the block $test1\n";

Will Output this:

package is: main
trying to print global var from main package: 1
trying to print local vars from a closed block: 10, 11
trying to print global var from a function: 1
package is: Changed
trying to print global var outside the func and from "Changed" package: 1
trying to print local var outside the block 

In case using "use strict" will get this failure while attempting to run the script:

Global symbol "$test1" requires explicit package name at ./check_global.pl line 24.
Execution of ./check_global.pl aborted due to compilation errors.

React navigation goBack() and update parent state

First screen

updateData=(data)=>{
    console.log('Selected data',data)
}   

this.props.navigation.navigate('FirstScreen',{updateData:this.updateData.bind(this)})

Second screen

// use this method to call FirstScreen method 
execBack(param) {
    this.props.navigation.state.params.updateData(param);
    this.props.navigation.goBack();
}

How do I print a double value without scientific notation using Java?

The following code detects if the provided number is presented in scientific notation. If so it is represented in normal presentation with a maximum of '25' digits.

 static String convertFromScientificNotation(double number) {
    // Check if in scientific notation
    if (String.valueOf(number).toLowerCase().contains("e")) {
        System.out.println("The scientific notation number'"
                + number
                + "' detected, it will be converted to normal representation with 25 maximum fraction digits.");
        NumberFormat formatter = new DecimalFormat();
        formatter.setMaximumFractionDigits(25);
        return formatter.format(number);
    } else
        return String.valueOf(number);
}

What is the difference between DAO and Repository patterns?

The key difference is that a repository handles the access to the aggregate roots in a an aggregate, while DAO handles the access to entities. Therefore, it's common that a repository delegates the actual persistence of the aggregate roots to a DAO. Additionally, as the aggregate root must handle the access of the other entities, then it may need to delegate this access to other DAOs.

Customize Bootstrap checkboxes

You have to use Bootstrap version 4 with the custom-* classes to get this style:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<!-- example code of the bootstrap website -->_x000D_
<label class="custom-control custom-checkbox">_x000D_
  <input type="checkbox" class="custom-control-input">_x000D_
  <span class="custom-control-indicator"></span>_x000D_
  <span class="custom-control-description">Check this custom checkbox</span>_x000D_
</label>_x000D_
_x000D_
<!-- your code with the custom classes of version 4 -->_x000D_
<div class="checkbox">_x000D_
  <label class="custom-control custom-checkbox">_x000D_
    <input type="checkbox" [(ngModel)]="rememberMe" name="rememberme" class="custom-control-input">_x000D_
    <span class="custom-control-indicator"></span>_x000D_
    <span class="custom-control-description">Remember me</span>_x000D_
  </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Documentation: https://getbootstrap.com/docs/4.0/components/forms/#checkboxes-and-radios-1


Custom checkbox style on Bootstrap version 3?
Bootstrap version 3 doesn't have custom checkbox styles, but you can use your own. In this case: How to style a checkbox using CSS?

These custom styles are only available since version 4.

Converting JSON String to Dictionary Not List

Your JSON is an array with a single object inside, so when you read it in you get a list with a dictionary inside. You can access your dictionary by accessing item 0 in the list, as shown below:

json1_data = json.loads(json1_str)[0]

Now you can access the data stored in datapoints just as you were expecting:

datapoints = json1_data['datapoints']

I have one more question if anyone can bite: I am trying to take the average of the first elements in these datapoints(i.e. datapoints[0][0]). Just to list them, I tried doing datapoints[0:5][0] but all I get is the first datapoint with both elements as opposed to wanting to get the first 5 datapoints containing only the first element. Is there a way to do this?

datapoints[0:5][0] doesn't do what you're expecting. datapoints[0:5] returns a new list slice containing just the first 5 elements, and then adding [0] on the end of it will take just the first element from that resulting list slice. What you need to use to get the result you want is a list comprehension:

[p[0] for p in datapoints[0:5]]

Here's a simple way to calculate the mean:

sum(p[0] for p in datapoints[0:5])/5. # Result is 35.8

If you're willing to install NumPy, then it's even easier:

import numpy
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)[0]
datapoints = numpy.array(json1_data['datapoints'])
avg = datapoints[0:5,0].mean()
# avg is now 35.8

Using the , operator with the slicing syntax for NumPy's arrays has the behavior you were originally expecting with the list slices.

How can I disable a button on a jQuery UI dialog?

this code disable the button with 'YOUR_BUTTON_LABEL'. you can replace name in contains(). to disable

$(".ui-dialog-buttonpane button:contains('YOUR_BUTTON_LABEL')").button("disable");

replace 'YOUR_BUTTON_LABEL' with your button's label. to enable

$(".ui-dialog-buttonpane button:contains('YOUR_BUTTON_LABEL')").button("enable");

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

If you don't need to handle raster files and PDF/PS/EPS through the same tool, don't loosen ImageMagick's security.

Instead, keep your defense in depth for your web applications intact, check that your Ghostscript has been patched for all known -dSAFER vulnerabilities and then invoke it directly.

gs -dSAFER -r300 -sDEVICE=png16m -o document-%03d.png document.pdf
  • -dSAFER opts you out of the legacy-compatibility "run Postscript will full permission to interact with the outside world as a turing-complete programming language" mode.
  • -r300 sets the desired DPI to 300 (the default is 72)
  • -sDEVICE specifies the output format (See the Devices section of the manual for other choices.)
  • -o is a shorthand for -dBATCH -dNOPAUSE -sOutputFile=
  • This section of the Ghostscript manual gives some example formats for for multi-file filename output but, for the actual syntax definition, it points you at the documentation for the C printf(3) function.

If you're rendering EPS files, add -dEPSCrop so it won't pad your output to page size and use -sDEVICE=pngalpha to get transparent backgrounds.

SQL Server Error : String or binary data would be truncated

You're trying to write more data than a specific column can store. Check the sizes of the data you're trying to insert against the sizes of each of the fields.

In this case transaction_status is a varchar(10) and you're trying to store 19 characters to it.

How to generate a Makefile with source in sub-directories using just one makefile

Usually, you create a Makefile in each subdirectory, and write in the top-level Makefile to call make in the subdirectories.

This page may help: http://www.gnu.org/software/make/

How to interpret "loss" and "accuracy" for a machine learning model

The lower the loss, the better a model (unless the model has over-fitted to the training data). The loss is calculated on training and validation and its interperation is how well the model is doing for these two sets. Unlike accuracy, loss is not a percentage. It is a summation of the errors made for each example in training or validation sets.

In the case of neural networks, the loss is usually negative log-likelihood and residual sum of squares for classification and regression respectively. Then naturally, the main objective in a learning model is to reduce (minimize) the loss function's value with respect to the model's parameters by changing the weight vector values through different optimization methods, such as backpropagation in neural networks.

Loss value implies how well or poorly a certain model behaves after each iteration of optimization. Ideally, one would expect the reduction of loss after each, or several, iteration(s).

The accuracy of a model is usually determined after the model parameters are learned and fixed and no learning is taking place. Then the test samples are fed to the model and the number of mistakes (zero-one loss) the model makes are recorded, after comparison to the true targets. Then the percentage of misclassification is calculated.

For example, if the number of test samples is 1000 and model classifies 952 of those correctly, then the model's accuracy is 95.2%.

enter image description here

There are also some subtleties while reducing the loss value. For instance, you may run into the problem of over-fitting in which the model "memorizes" the training examples and becomes kind of ineffective for the test set. Over-fitting also occurs in cases where you do not employ a regularization, you have a very complex model (the number of free parameters W is large) or the number of data points N is very low.

Static methods in Python?

Yes, check out the staticmethod decorator:

>>> class C:
...     @staticmethod
...     def hello():
...             print "Hello World"
...
>>> C.hello()
Hello World

MongoDB: How to update multiple documents with a single command?

To Update Entire Collection,

db.getCollection('collection_name').update({},
{$set: {"field1" : "value1", "field2" : "value2", "field3" : "value3"}},
{multi: true })

How can I change property names when serializing with Json.net?

You could decorate the property you wish controlling its name with the [JsonProperty] attribute which allows you to specify a different name:

using Newtonsoft.Json;
// ...

[JsonProperty(PropertyName = "FooBar")]
public string Foo { get; set; }

Documentation: Serialization Attributes

JPA EntityManager: Why use persist() over merge()?

I was getting lazyLoading exceptions on my entity because I was trying to access a lazy loaded collection that was in session.

What I would do was in a separate request, retrieve the entity from session and then try to access a collection in my jsp page which was problematic.

To alleviate this, I updated the same entity in my controller and passed it to my jsp, although I imagine when I re-saved in session that it will also be accessible though SessionScope and not throw a LazyLoadingException, a modification of example 2:

The following has worked for me:

// scenario 2 MY WAY
// tran starts
e = new MyEntity();
e = em.merge(e); // re-assign to the same entity "e"

//access e from jsp and it will work dandy!!

Rails: How do I create a default value for attributes in Rails activerecord's model?

Just strengthening Jim's answer

Using presence one can do

class Task < ActiveRecord::Base
  before_save :default_values
  def default_values
    self.status = status.presence || 'P'
  end
end

How to print Unicode character in C++?

Another solution in Linux:

string a = "?";
cout << "? = \xd0\xa4 = " << hex
     << int(static_cast<unsigned char>(a[0]))
     << int(static_cast<unsigned char>(a[1])) << " (" << a.length() << "B)" << endl;

string b = "v";
cout << "v = \xe2\x88\x9a = " << hex
     << int(static_cast<unsigned char>(b[0]))
     << int(static_cast<unsigned char>(b[1]))
     << int(static_cast<unsigned char>(b[2])) << " (" << b.length() << "B)" << endl;

Permission denied at hdfs

I solved this problem temporary by disabling the dfs permission.By adding below property code to conf/hdfs-site.xml

<property>
  <name>dfs.permissions</name>
  <value>false</value>
</property>

Is it possible to specify a different ssh port when using rsync?

Another option, in the host you run rsync from, set the port in the ssh config file, ie:

cat ~/.ssh/config
Host host
    Port 2222

Then rsync over ssh will talk to port 2222:

rsync -rvz --progress --remove-sent-files ./dir user@host:/path

Objects inside objects in javascript

var pause_menu = {
    pause_button : { someProperty : "prop1", someOther : "prop2" },
    resume_button : { resumeProp : "prop", resumeProp2 : false },
    quit_button : false
};

then:

pause_menu.pause_button.someProperty //evaluates to "prop1"

etc etc.

Postgres: SQL to list table foreign keys

Ollyc's answer is good as it is not Postgres-specific, however, it breaks down when the foreign key references more than one column. The following query works for arbitrary number of columns but it relies heavily on Postgres extensions:

select 
    att2.attname as "child_column", 
    cl.relname as "parent_table", 
    att.attname as "parent_column",
    conname
from
   (select 
        unnest(con1.conkey) as "parent", 
        unnest(con1.confkey) as "child", 
        con1.confrelid, 
        con1.conrelid,
        con1.conname
    from 
        pg_class cl
        join pg_namespace ns on cl.relnamespace = ns.oid
        join pg_constraint con1 on con1.conrelid = cl.oid
    where
        cl.relname = 'child_table'
        and ns.nspname = 'child_schema'
        and con1.contype = 'f'
   ) con
   join pg_attribute att on
       att.attrelid = con.confrelid and att.attnum = con.child
   join pg_class cl on
       cl.oid = con.confrelid
   join pg_attribute att2 on
       att2.attrelid = con.conrelid and att2.attnum = con.parent

Highlight all occurrence of a selected word?

  1. Add those lines in your ~/.vimrc file

" highlight the searched items set hlsearch " F8 search for word under the cursor recursively , :copen , to close -> :ccl nnoremap <F8> :grep! "\<<cword>\>" . -r<CR>:copen 33<CR>

  1. Reload the settings with :so%
  2. In normal model go over the word.

  3. Press * Press F8 to search recursively bellow your whole project over the word

How and when to use SLEEP() correctly in MySQL?

SELECT ...
SELECT SLEEP(5);
SELECT ...

But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?

Set active tab style with AngularJS

Bootstrap example.

If you are using Angulars built in routing (ngview) this directive can be used:

angular.module('myApp').directive('classOnActiveLink', [function() {
    return {
        link: function(scope, element, attrs) {

            var anchorLink = element.children()[0].getAttribute('ng-href') || element.children()[0].getAttribute('href');
            anchorLink = anchorLink.replace(/^#/, '');

            scope.$on("$routeChangeSuccess", function (event, current) {
                if (current.$$route.originalPath == anchorLink) {
                    element.addClass(attrs.classOnActiveLink);
                }
                else {
                    element.removeClass(attrs.classOnActiveLink);
                }
            });

        }
    };
}]);

Assuming your markup looks like this:

    <ul class="nav navbar-nav">
        <li class-on-active-link="active"><a href="/orders">Orders</a></li>
        <li class-on-active-link="active"><a href="/distributors">Distributors</a></li>
    </ul>

I like this was of doing it since you can set the class name you want in your attribute.

Why .NET String is immutable?

Why are string types immutable in C#

String is a reference type, so it is never copied, but passed by reference. Compare this to the C++ std::string object (which is not immutable), which is passed by value. This means that if you want to use a String as a key in a Hashtable, you're fine in C++, because C++ will copy the string to store the key in the hashtable (actually std::hash_map, but still) for later comparison. So even if you later modify the std::string instance, you're fine. But in .Net, when you use a String in a Hashtable, it will store a reference to that instance. Now assume for a moment that strings aren't immutable, and see what happens: 1. Somebody inserts a value x with key "hello" into a Hashtable. 2. The Hashtable computes the hash value for the String, and places a reference to the string and the value x in the appropriate bucket. 3. The user modifies the String instance to be "bye". 4. Now somebody wants the value in the hashtable associated with "hello". It ends up looking in the correct bucket, but when comparing the strings it says "bye"!="hello", so no value is returned. 5. Maybe somebody wants the value "bye"? "bye" probably has a different hash, so the hashtable would look in a different bucket. No "bye" keys in that bucket, so our entry still isn't found.

Making strings immutable means that step 3 is impossible. If somebody modifies the string he's creating a new string object, leaving the old one alone. Which means the key in the hashtable is still "hello", and thus still correct.

So, probably among other things, immutable strings are a way to enable strings that are passed by reference to be used as keys in a hashtable or similar dictionary object.

Prevent redirect after form is submitted

Using Ajax

Using the jQuery Ajax request method you can post the email data to a script (submit.php). Using the success callback option to animate elements after the script is executed.

note - I would suggest utilizing the ajax Response Object to make sure the script executed successfully.

$(function() {
    $('.submit').click(function() {
        $.ajax({
            type: 'POST',
            url: 'submit.php',
            data: 'password=p4ssw0rt',
            error: function()
            {
               alert("Request Failed");
            },
            success: function(response)
            {  
               //EXECUTE ANIMATION HERE
            } // this was missing
        });
        return false;
    }); 
})

Counting Chars in EditText Changed Listener

how about just getting the length of char in your EditText and display it?

something along the line of

tv.setText(s.length() + " / " + String.valueOf(charCounts));

Git: How do I list only local branches?

git branch -a - All branches.

git branch -r - Remote branches only.

git branch -l or git branch - Local branches only.

How do I break a string in YAML over multiple lines?

For situations were the string might contain spaces or not, I prefer double quotes and line continuation with backslashes:

key: "String \
  with long c\
  ontent"

But note about the pitfall for the case that a continuation line begins with a space, it needs to be escaped (because it will be stripped away elsewhere):

key: "String\
  \ with lon\
  g content"

If the string contains line breaks, this needs to be written in C style \n.

See also this question.

Convert a python UTC datetime to a local datetime using only python standard library?

Building on Alexei's comment. This should work for DST too.

import time
import datetime

def utc_to_local(dt):
    if time.localtime().tm_isdst:
        return dt - datetime.timedelta(seconds = time.altzone)
    else:
        return dt - datetime.timedelta(seconds = time.timezone)

Javascript Array.sort implementation?

If you look at this bug 224128, it appears that MergeSort is being used by Mozilla.

How to unblock with mysqladmin flush hosts

You can easily restart your MySql service. This kicks the error off.

count of entries in data frame in R

A one-line solution with data.table could be

library(data.table)
setDT(x)[,.N,by=Believe]
   Believe N
1:   FALSE 1
2:    TRUE 3

How can I reverse a list in Python?

I find (contrary to some other suggestions) that l.reverse() is by far the fastest way to reverse a long list in Python 3 and 2. I'd be interested to know if others can replicate these timings.

l[::-1] is probably slower because it copies the list prior to reversing it. Adding the list() call around the iterator made by reversed(l) must add some overhead. Of course if you want a copy of the list or an iterator then use those respective methods, but if you want to just reverse the list then l.reverse() seems to be the fastest way.

Functions

def rev_list1(l):
    return l[::-1]

def rev_list2(l):
    return list(reversed(l))

def rev_list3(l):
    l.reverse()
    return l

List

l = list(range(1000000))

Python 3.5 timings

timeit(lambda: rev_list1(l), number=1000)
# 6.48
timeit(lambda: rev_list2(l), number=1000)
# 7.13
timeit(lambda: rev_list3(l), number=1000)
# 0.44

Python 2.7 timings

timeit(lambda: rev_list1(l), number=1000)
# 6.76
timeit(lambda: rev_list2(l), number=1000)
# 9.18
timeit(lambda: rev_list3(l), number=1000)
# 0.46

Flask Value error view function did not return a response

You are not returning a response object from your view my_form_post. The function ends with implicit return None, which Flask does not like.

Make the function my_form_post return an explicit response, for example

return 'OK'

at the end of the function.

How to check if a process is in hang state (Linux)

What do you mean by ‘hang state’? Typically, a process that is unresponsive and using 100% of a CPU is stuck in an endless loop. But there's no way to determine whether that has happened or whether the process might not eventually reach a loop exit state and carry on.

Desktop hang detectors just work by sending a message to the application's event loop and seeing if there's any response. If there's not for a certain amount of time they decide the app has ‘hung’... but it's entirely possible it was just doing something complicated and will come back to life in a moment once it's done. Anyhow, that's not something you can use for any arbitrary process.

SQL Query Multiple Columns Using Distinct on One Column Only

I suppose the easiest and the best solution is using OUTER APPLY. You only use one field with DISTINCT but to retrieve more data about that record, you utilize OUTER APPLY.

To test the solution, execute following query which firstly creates a temp table then retrieves data:

 DECLARE @tblFruit TABLE (tblFruit_ID int, tblFruit_FruitType varchar(10), tblFruit_FruitName varchar(50))
 SET NOCOUNT ON
 INSERT @tblFruit VALUES (1,'Citrus ','Orange')
 INSERT @tblFruit VALUES (2,'Citrus','Lime')
 INSERT @tblFruit VALUES (3,'Citrus','Lemon')
 INSERT @tblFruit VALUES (4,'Seed','Cherry')
 INSERT @tblFruit VALUES (5,'Seed','Banana')
   
SELECT DISTINCT (f.tblFruit_FruitType), outter_f.tblFruit_ID
FROM @tblFruit AS f
OUTER APPLY (
    SELECT TOP(1) *
    FROM @tblFruit AS inner_f
    WHERE inner_f.tblFruit_FruitType = f.tblFruit_FruitType
) AS outter_f

The result will be:

Citrus 1

Seed 4

How to comment lines in rails html.erb files?

ruby on rails notes has a very nice blogpost about commenting in erb-files

the short version is

to comment a single line use

<%# commented line %>

to comment a whole block use a if false to surrond your code like this

<% if false %>
code to comment
<% end %>

How to prevent robots from automatically filling up a form?

I'm thinking of many things here:

  1. using JS (although you don't want it) to track mouse move, key press, mouse click
  2. getting the referral url (which in this case should be one from the same domain) ... the normal user must navigate through the website before reaching the contact form: PHP: How to get referrer URL?
  3. using a $_SESSION variable to acquire the IP and check the form submit against that list of IPs
  4. Fill in one text field with some dummy text that you can check on server side if it had been overwritten
  5. Check the browser version: http://chrisschuld.com/projects/browser-php-detecting-a-users-browser-from-php.html ... It's clear that a bot won't use a browser but just a script.
  6. Use AJAX to send the fields one by one and check the difference in time between submissions
  7. Use a fake page before/after the form, just to send another input

How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

(Updated - Thanks to the people who commented)

Modern Versions of PostgreSQL

Suppose you have a table named test1, to which you want to add an auto-incrementing, primary-key id (surrogate) column. The following command should be sufficient in recent versions of PostgreSQL:

   ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;

Older Versions of PostgreSQL

In old versions of PostgreSQL (prior to 8.x?) you had to do all the dirty work. The following sequence of commands should do the trick:

  ALTER TABLE test1 ADD COLUMN id INTEGER;
  CREATE SEQUENCE test_id_seq OWNED BY test1.id;
  ALTER TABLE test ALTER COLUMN id SET DEFAULT nextval('test_id_seq');
  UPDATE test1 SET id = nextval('test_id_seq');

Again, in recent versions of Postgres this is roughly equivalent to the single command above.

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>

The IEnumerable<T> interface does not include an indexer, you're probably confusing it with IList<T>

If the object really is an IList<T> (e.g. List<T> or an array T[]), try making the reference to it of type IList<T> too.

Otherwise, you can use myEnumerable.ElementAt(index) which uses the Enumerable.ElementAt extension method. This should work for all IEnumerable<T>s . Note that unless the (run-time) object implements IList<T>, this will cause all of the first index + 1 items to be enumerated, with all but the last being discarded.

EDIT: As an explanation, IEnumerable<T> is simply an interface that represents "that which exposes an enumerator." A concrete implementation may well be some sort of in-memory list that does allow fast-access by index, or it may not. For instance, it could be a collection that cannot efficiently satisfy such a query, such as a linked-list (as mentioned by James Curran). It may even be no sort of in-memory data-structure at all, such as an iterator, where items are generated ('yielded') on demand, or by an enumerator that fetches the items from some remote data-source. Because IEnumerable<T> must support all these cases, indexers are excluded from its definition.

How to pass an event object to a function in Javascript?

  1. Modify the definition of the function check_me as::

     function check_me(ev) {
    
  2. Now you can access the methods and parameters of the event, in your case:

     ev.preventDefault();
    
  3. Then, you have to pass the parameter on the onclick in the inline call::

     <button type="button" onclick="check_me(event);">Click Me!</button>
    

A useful link to understand this.


Full example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script type="text/javascript">
      function check_me(ev) {
        ev.preventDefault();
        alert("Hello World!")
      }
    </script>
  </head>
  <body>
    <button type="button" onclick="check_me(event);">Click Me!</button>
  </body>
</html>









Alternatives (best practices):

Although the above is the direct answer to the question (passing an event object to an inline event), there are other ways of handling events that keep the logic separated from the presentation

A. Using addEventListener:

<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>
    <button id='my_button' type="button">Click Me!</button>

    <!-- put the javascript at the end to guarantee that the DOM is ready to use-->
    <script type="text/javascript">
      function check_me(ev) {
        ev.preventDefault();
        alert("Hello World!")
      }
      
      <!-- add the event to the button identified #my_button -->
      document.getElementById("my_button").addEventListener("click", check_me);
    </script>
  </body>
</html>

B. Isolating Javascript:

Both of the above solutions are fine for a small project, or a hackish quick and dirty solution, but for bigger projects, it is better to keep the HTML separated from the Javascript.

Just put this two files in the same folder:

  • example.html:
<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>
    <button id='my_button' type="button">Click Me!</button>

    <!-- put the javascript at the end to guarantee that the DOM is ready to use-->
    <script type="text/javascript" src="example.js"></script>
  </body>
</html>
  • example.js:
function check_me(ev) {
    ev.preventDefault();
    alert("Hello World!")
}
document.getElementById("my_button").addEventListener("click", check_me);

If statement with String comparison fails

You shouldn't do string comparisons with ==. That operator will only check to see if it is the same instance, not the same value. Use the .equals method to check for the same value.

Upload a file to Amazon S3 with NodeJS

Uploading a file to AWS s3 and sending the url in response for accessing the file.

Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency. check this npm module here.

When you are sending the request, make sure the headers, have Content-Type is multipart/form-data. We are sending the file location in the response, which will give the url, but if you want to access that url, make the bucket public or else you will not be able to access it.

upload.router.js

const express = require('express');
const router = express.Router();
const AWS = require('aws-sdk');
const multer = require('multer');
const storage = multer.memoryStorage()
const upload = multer({storage: storage});

const s3Client = new AWS.S3({
    accessKeyId: 'your_access_key_id',
    secretAccessKey: 'your_secret_access_id',
    region :'ur region'
});

const uploadParams = {
         Bucket: 'ur_bucket_name', 
         Key: '', // pass key
         Body: null, // pass file body
};


router.post('/api/file/upload', upload.single("file"),(req,res) => {
    const params = uploadParams;

    uploadParams.Key = req.file.originalname;
    uploadParams.Body = req.file.buffer;

    s3Client.upload(params, (err, data) => {
        if (err) {
            res.status(500).json({error:"Error -> " + err});
        }
        res.json({message: 'File uploaded successfully','filename': 
        req.file.originalname, 'location': data.Location});
    });
});

module.exports = router;

app.js

const express = require('express');
const app = express();

const router = require('./app/routers/upload.router.js');
app.use('/', router);

// Create a Server
  const server = app.listen(8080, () => {
  console.log("App listening at 8080"); 
})

Bind class toggle to window scroll event

Directives are not "inside the angular world" as they say. So you have to use apply to get back into it when changing stuff

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

A few years ago it was said that update() and digest() were legacy methods and the new streaming API approach was introduced. Now the docs say that either method can be used. For example:

var crypto    = require('crypto');
var text      = 'I love cupcakes';
var secret    = 'abcdeg'; //make this your secret!!
var algorithm = 'sha1';   //consider using sha256
var hash, hmac;

// Method 1 - Writing to a stream
hmac = crypto.createHmac(algorithm, secret);    
hmac.write(text); // write in to the stream
hmac.end();       // can't read from the stream until you call end()
hash = hmac.read().toString('hex');    // read out hmac digest
console.log("Method 1: ", hash);

// Method 2 - Using update and digest:
hmac = crypto.createHmac(algorithm, secret);
hmac.update(text);
hash = hmac.digest('hex');
console.log("Method 2: ", hash);

Tested on node v6.2.2 and v7.7.2

See https://nodejs.org/api/crypto.html#crypto_class_hmac. Gives more examples for using the streaming approach.

Java Inheritance - calling superclass method

It is possible to use super to call the method from mother class, but this would mean you probably have a design problem. Maybe B.alphaMethod1() shouldn't override A's method and be called B.betaMethod1().

If it depends on the situation, you can put some code logic like :

public void alphaMethod1(){
    if (something) {
        super.alphaMethod1();
        return;
    }
    // Rest of the code for other situations
}

Like this it will only call A's method when needed and will remain invisible for the class user.

Deep-Learning Nan loss reasons

If you're training for cross entropy, you want to add a small number like 1e-8 to your output probability.

Because log(0) is negative infinity, when your model trained enough the output distribution will be very skewed, for instance say I'm doing a 4 class output, in the beginning my probability looks like

0.25 0.25 0.25 0.25

but toward the end the probability will probably look like

1.0 0 0 0

And you take a cross entropy of this distribution everything will explode. The fix is to artifitially add a small number to all the terms to prevent this.

C programming: Dereferencing pointer to incomplete type error

The reason why you're getting that error is because you've declared your struct as:

struct {
 char name[32];
 int  size;
 int  start;
 int  popularity;
} stasher_file;

This is not declaring a stasher_file type. This is declaring an anonymous struct type and is creating a global instance named stasher_file.

What you intended was:

struct stasher_file {
 char name[32];
 int  size;
 int  start;
 int  popularity;
};

But note that while Brian R. Bondy's response wasn't correct about your error message, he's right that you're trying to write into the struct without having allocated space for it. If you want an array of pointers to struct stasher_file structures, you'll need to call malloc to allocate space for each one:

struct stasher_file *newFile = malloc(sizeof *newFile);
if (newFile == NULL) {
   /* Failure handling goes here. */
}
strncpy(newFile->name, name, 32);
newFile->size = size;
...

(BTW, be careful when using strncpy; it's not guaranteed to NUL-terminate.)

How do you round a double in Dart to a given degree of precision AFTER the decimal point?

void main() {
  int decimals = 2;
  int fac = pow(10, decimals);
  double d = 1.234567889;
  d = (d * fac).round() / fac;
  print("d: $d");
}

Prints: 1.23

How does one represent the empty char?

There are two ways to do the same instruction, that is, an empty string. The first way is to allocate an empty string on static memory:

char* my_variable = "";

or, if you want to be explicit:

char my_variable = '\0';

The way posted above is only for a character. And, the second way:

#include <string.h>
char* my_variable = strdup("");

Don't forget to use free() with this one because strdup() use malloc inside.

How to remove commits from a pull request

This is what helped me:

  1. Create a new branch with the existing one. Let's call the existing one branch_old and new as branch_new.

  2. Reset branch_new to a stable state, when you did not have any problem commit at all. For example, to put it at your local master's level do the following:

    git reset —hard master git push —force origin

  3. cherry-pick the commits from branch_old into branch_new

  4. git push

visual c++: #include files from other projects in the same solution

Expanding on @Benav's answer, my preferred approach is to:

  1. Add the solution directory to your include paths:
    • right click on your project in the Solution Explorer
    • select Properties
    • select All Configurations and All Platforms from the drop-downs
    • select C/C++ > General
    • add $(SolutionDir) to the Additional Include Directories
  2. Add references to each project you want to use:
    • right click on your project's References in the Solution Explorer
    • select Add Reference...
    • select the project(s) you want to refer to

Now you can include headers from your referenced projects like so:

#include "OtherProject/Header.h"

Notes:

  • This assumes that your solution file is stored one folder up from each of your projects, which is the default organization when creating projects with Visual Studio.
  • You could now include any file from a path relative to the solution folder, which may not be desirable but for the simplicity of the approach I'm ok with this.
  • Step 2 isn't necessary for #includes, but it sets the correct build dependencies, which you probably want.

On design patterns: When should I use the singleton?

One of the ways you use a singleton is to cover an instance where there must be a single "broker" controlling access to a resource. Singletons are good in loggers because they broker access to, say, a file, which can only be written to exclusively. For something like logging, they provide a way of abstracting away the writes to something like a log file -- you could wrap a caching mechanism to your singleton, etc...

Also think of a situation where you have an application with many windows/threads/etc, but which needs a single point of communication. I once used one to control jobs that I wanted my application to launch. The singleton was responsible for serializing the jobs and displaying their status to any other part of the program which was interested. In this sort of scenario, you can look at a singleton as being sort of like a "server" class running inside your application... HTH

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

I've implemented a sqlite table schema parser in PHP, you may check here: https://github.com/c9s/LazyRecord/blob/master/src/LazyRecord/TableParser/SqliteTableDefinitionParser.php

You can use this definition parser to parse the definitions like the code below:

$parser = new SqliteTableDefinitionParser;
$parser->parseColumnDefinitions('x INTEGER PRIMARY KEY, y DOUBLE, z DATETIME default \'2011-11-10\', name VARCHAR(100)');

How to pass a value from one jsp to another jsp page?

Use sessions

On your search.jsp

Put your scard in sessions using session.setAttribute("scard","scard")

//the 1st variable is the string name that you will retrieve in ur next page,and the 2nd variable is the its value,i.e the scard value.

And in your next page you retrieve it using session.getAttribute("scard")

UPDATE

<input type="text" value="<%=session.getAttribute("scard")%>"/>

Write to UTF-8 file in Python

I believe the problem is that codecs.BOM_UTF8 is a byte string, not a Unicode string. I suspect the file handler is trying to guess what you really mean based on "I'm meant to be writing Unicode as UTF-8-encoded text, but you've given me a byte string!"

Try writing the Unicode string for the byte order mark (i.e. Unicode U+FEFF) directly, so that the file just encodes that as UTF-8:

import codecs

file = codecs.open("lol", "w", "utf-8")
file.write(u'\ufeff')
file.close()

(That seems to give the right answer - a file with bytes EF BB BF.)

EDIT: S. Lott's suggestion of using "utf-8-sig" as the encoding is a better one than explicitly writing the BOM yourself, but I'll leave this answer here as it explains what was going wrong before.

Using Custom Domains With IIS Express

The invalid hostname indicates that the actual site you configured in the IIS Express configuration file is (most likely) not running. IIS Express doesn't have a process model like IIS does.


For your site to run it would need to be started explicitly (either by opening and accessing from webmatrix, or from command line calling iisexpress.exe (from it's installation directory) with the /site parameter.


In general, the steps to allow fully qualified DNS names to be used for local access are Let's use your example of the DNS name dev.example.com

  1. edit %windows%\system32\drivers\etc\hosts file to map dev.example.com to 127.0.0.1 (admin privilege required). If you control DNS server (like in Nick's case) then the DNS entry is sufficient as this step is not needed.
  2. If you access internet through proxy, make sure the dev.example.com will not be forwared to proxy (you have to put in on the exception list in your browser (for IE it would be Tools/Internet Options/Connections/Lan Settings, then go to Proxy Server/Advanced and put dev.example.com on the exeption list.
  3. Configure IIS Express binding for your site (eg:Site1) to include dev.example.com. Administrative privilege will be needed to use the binding. Alternatively, a one-time URL reservation can be made with http.sys using

    netsh http add urlacl url=http://dev.example.com:<port>/ user=<user_name>

  4. start iisexpress /site:Site1 or open Site1 in WebMatrix

Run Java Code Online

I found this online java compiler and runner. It work also with threads and showing results immediately. http://www.browxy.com

Java - Reading XML file

Reading xml the easy way:

http://www.mkyong.com/java/jaxb-hello-world-example/

package com.mkyong.core;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

} 

.

package com.mkyong.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
    public static void main(String[] args) {

      Customer customer = new Customer();
      customer.setId(100);
      customer.setName("mkyong");
      customer.setAge(29);

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

          } catch (JAXBException e) {
              e.printStackTrace();
          }

    }
}

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

Install a .NET windows service without InstallUtil.exe

In the case of trying to install a command line application as a Windows service try the 'NSSM' utility. Related ServerFault details found here.

How to generate gcc debug symbol outside the build target?

No answer so far mentions eu-strip --strip-debug -f <out.debug> <input>.

  • This is provided by elfutils package.
  • The result will be that <input> file has been stripped of debug symbols which are now all in <out.debug>.

npm - how to show the latest version of a package

You can see all the version of a module with npm view. eg: To list all versions of bootstrap including beta.

npm view bootstrap versions

But if the version list is very big it will truncate. An --json option will print all version including beta versions as well.

npm view bootstrap versions --json

If you want to list only the stable versions not the beta then use singular version

npm view bootstrap@* versions

Or

npm view bootstrap@* versions --json

And, if you want to see only latest version then here you go.

npm view bootstrap version

How to resolve 'unrecognized selector sent to instance'?

Set flag -ObjC in Other linker Flag in your Project setting... (Not in the static library project but the project you that is using static library...) And make sure that in Project setting Configuration is set to All Configuration

HTML Entity Decode

Inspired by Robert K's solution, this version does not strip HTML tags, and is just as secure.

var decode_entities = (function() {
    // Remove HTML Entities
    var element = document.createElement('div');

    function decode_HTML_entities (str) {

        if(str && typeof str === 'string') {

            // Escape HTML before decoding for HTML Entities
            str = escape(str).replace(/%26/g,'&').replace(/%23/g,'#').replace(/%3B/g,';');

            element.innerHTML = str;
            if(element.innerText){
                str = element.innerText;
                element.innerText = '';
            }else{
                // Firefox support
                str = element.textContent;
                element.textContent = '';
            }
        }
        return unescape(str);
    }
    return decode_HTML_entities;
})();

When is each sorting algorithm used?

First, a definition, since it's pretty important: A stable sort is one that's guaranteed not to reorder elements with identical keys.

Recommendations:

Quick sort: When you don't need a stable sort and average case performance matters more than worst case performance. A quick sort is O(N log N) on average, O(N^2) in the worst case. A good implementation uses O(log N) auxiliary storage in the form of stack space for recursion.

Merge sort: When you need a stable, O(N log N) sort, this is about your only option. The only downsides to it are that it uses O(N) auxiliary space and has a slightly larger constant than a quick sort. There are some in-place merge sorts, but AFAIK they are all either not stable or worse than O(N log N). Even the O(N log N) in place sorts have so much larger a constant than the plain old merge sort that they're more theoretical curiosities than useful algorithms.

Heap sort: When you don't need a stable sort and you care more about worst case performance than average case performance. It's guaranteed to be O(N log N), and uses O(1) auxiliary space, meaning that you won't unexpectedly run out of heap or stack space on very large inputs.

Introsort: This is a quick sort that switches to a heap sort after a certain recursion depth to get around quick sort's O(N^2) worst case. It's almost always better than a plain old quick sort, since you get the average case of a quick sort, with guaranteed O(N log N) performance. Probably the only reason to use a heap sort instead of this is in severely memory constrained systems where O(log N) stack space is practically significant.

Insertion sort: When N is guaranteed to be small, including as the base case of a quick sort or merge sort. While this is O(N^2), it has a very small constant and is a stable sort.

Bubble sort, selection sort: When you're doing something quick and dirty and for some reason you can't just use the standard library's sorting algorithm. The only advantage these have over insertion sort is being slightly easier to implement.


Non-comparison sorts: Under some fairly limited conditions it's possible to break the O(N log N) barrier and sort in O(N). Here are some cases where that's worth a try:

Counting sort: When you are sorting integers with a limited range.

Radix sort: When log(N) is significantly larger than K, where K is the number of radix digits.

Bucket sort: When you can guarantee that your input is approximately uniformly distributed.

Replace values in list using Python

Riffing on a side question asked by the OP in a comment, i.e.:

what if I had a generator that yields the values from range(11) instead of a list. Would it be possible to replace values in the generator?

Sure, it's trivially easy...:

def replaceiniter(it, predicate, replacement=None):
  for item in it:
    if predicate(item): yield replacement
    else: yield item

Just pass any iterable (including the result of calling a generator) as the first arg, the predicate to decide if a value must be replaced as the second arg, and let 'er rip.

For example:

>>> list(replaceiniter(xrange(11), lambda x: x%2))
[0, None, 2, None, 4, None, 6, None, 8, None, 10]

How do I replace multiple spaces with a single space in C#?

Here is a slight modification on Nolonar original answer.

Checking if the character is not just a space, but any whitespace, use this:

It will replace any multiple whitespace character with a single space.

public static string FilterWhiteSpaces(string input)
{
    if (input == null)
        return string.Empty;

    var stringBuilder = new StringBuilder(input.Length);
    for (int i = 0; i < input.Length; i++)
    {
        char c = input[i];
        if (i == 0 || !char.IsWhiteSpace(c) || (char.IsWhiteSpace(c) && 
            !char.IsWhiteSpace(strValue[i - 1])))
            stringBuilder.Append(c);
    }
    return stringBuilder.ToString();
}

SQL Server 2008 Insert with WHILE LOOP

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

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

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

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

And result would be

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

Firebase (FCM) how to get token

FirebaseInstanceId.getInstance().getInstanceId() deprecated. Now get user FCM token

 FirebaseMessaging.getInstance().getToken()
            .addOnCompleteListener(new OnCompleteListener<String>() {
                @Override
                public void onComplete(@NonNull Task<String> task) {
                    if (!task.isSuccessful()) {
                        System.out.println("--------------------------");
                        System.out.println(" " + task.getException());
                        System.out.println("--------------------------");
                        return;
                    }

                    // Get new FCM registration token
                    String token = task.getResult();

                    // Log 
                    String msg = "GET TOKEN " + token;
                    System.out.println("--------------------------");
                    System.out.println(" " + msg);
                    System.out.println("--------------------------");

                }
            });

How can I change the size of a Bootstrap checkbox?

input[type=checkbox]
{
  /* Double-sized Checkboxes */
  -ms-transform: scale(2); /* IE */
  -moz-transform: scale(2); /* FF */
  -webkit-transform: scale(2); /* Safari and Chrome */
  -o-transform: scale(2); /* Opera */
  padding: 10px;
}

SQL Server remove milliseconds from datetime

May be this will help.. SELECT [Datetime] = CAST('20120228' AS smalldatetime)

o/p: 2012-02-28 00:00:00

jQuery: Change button text on click

its work short code

$('.SeeMore2').click(function(){ var $this = $(this).toggleClass('SeeMore2'); if($(this).hasClass('SeeMore2')) { $(this).text('See More');
} else { $(this).text('See Less'); } });

Meaning of *& and **& in C++

That's passing a pointer by reference rather than by value. This for example allows altering the pointer (not the pointed-to object) in the function is such way that the calling code sees the change.

Compare:

void nochange( int* pointer ) //passed by value
{
   pointer++; // change will be discarded once function returns
}

void change( int*& pointer ) //passed by reference
{
   pointer++; // change will persist when function returns
}

Hive: Filtering Data between Specified Dates when Date is a String

Hive has a lot of good date parsing UDFs: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions

Just doing the string comparison as Nigel Tufnel suggests is probably the easiest solution, although technically it's unsafe. But you probably don't need to worry about that unless your tables have historical data about the medieval ages (dates with only 3 year digits) or dates from scifi novels (dates with more than 4 year digits).

Anyway, if you ever find yourself in a situation where you would want to do fancier date comparisons, or if your date format is not in a "biggest to smallest" order, e.g. the American convention of "mm/dd/yyyy", then you could use unix_timestamp with two arguments:

select *
from your_table
where unix_timestamp(your_date_column, 'yyyy-MM-dd') >= unix_timestamp('2010-09-01', 'yyyy-MM-dd')
and unix_timestamp(your_date_column, 'yyyy-MM-dd') <= unix_timestamp('2013-08-31', 'yyyy-MM-dd')

How to get the current time in milliseconds in C Programming

quick answer

#include<stdio.h>   
#include<time.h>   

int main()   
{   
    clock_t t1, t2;  
    t1 = clock();   
    int i;
    for(i = 0; i < 1000000; i++)   
    {   
        int x = 90;  
    }   

    t2 = clock();   

    float diff = ((float)(t2 - t1) / 1000000.0F ) * 1000;   
    printf("%f",diff);   

    return 0;   
}

DirectX SDK (June 2010) Installation Problems: Error Code S1023

I had the same problem and for me it was because the vc2010 redist x86 was too recent.

Check your temp folder (C:\Users\\AppData\Local\Temp) for the most recent file named

Microsoft Visual C++ 2010 x64 Redistributable Setup_20110608_xxx.html ##

and check if you have the following error

Installation Blockers:

A newer version of Microsoft Visual C++ 2010 Redistributable has been detected on the machine.

Final Result: Installation failed with error code: (0x000013EC), "A StopBlock was hit or a System >Requirement was not met." (Elapsed time: 0 00:00:00).

then go to Control Panel>Program & Features and uninstall all the

Microsoft Visual C++ 2010 x86/x64 redistributable - 10.0.(number over 30319)

After successful installation of DXSDK, simply run Windows Update and it will update the redistributables back to the latest version.

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

Alternatively you can do:

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

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

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

Disabling of EditText in Android

I believe the correct would be to set android:editable="false".

And if you wonder why my link point to the attributes of TextView, you the answer is because EditText inherits from TextView:

EditText is a thin veneer over TextView that configures itself to be editable.

Update:
As mentioned in the comments below, editable is deprecated (since API level 3). You should instead be using inputType (with the value none).

How do I open a new fragment from another fragment?

This is more described code of @Narendra's code,

First you need an instance of the 2nd fragment. Then you should have objects of FragmentManager and FragmentTransaction. The complete code is as below,

Fragment2 fragment2=new Fragment2();
FragmentManager fragmentManager=getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_main,fragment2,"tag");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

Hope this will work. In case you use androidx, you need getSupportFragmentManager() instead of getFragmentManager().

How to get current foreground activity context in android?

Personally I did as "Cheok Yan Cheng" said, but I used a "List" to have a "Backstack" of all my activities.

If you want to check Which is the Current Activity you just need to get the last activity class in the list.

Create an application which extends "Application" and do this:

public class MyApplication extends Application implements Application.ActivityLifecycleCallbacks,
EndSyncReceiver.IEndSyncCallback {

private List<Class> mActivitiesBackStack;
private EndSyncReceiver mReceiver;
    private Merlin mMerlin;
    private boolean isMerlinBound;
    private boolean isReceiverRegistered;

@Override
    public void onCreate() {
        super.onCreate();
        [....]
RealmHelper.initInstance();
        initMyMerlin();
        bindMerlin();
        initEndSyncReceiver();
        mActivitiesBackStack = new ArrayList<>();
    }

/* START Override ActivityLifecycleCallbacks Methods */
    @Override
    public void onActivityCreated(Activity activity, Bundle bundle) {
        mActivitiesBackStack.add(activity.getClass());
    }

    @Override
    public void onActivityStarted(Activity activity) {
        if(!isMerlinBound){
            bindMerlin();
        }
        if(!isReceiverRegistered){
            registerEndSyncReceiver();
        }
    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {
        if(!AppUtils.isAppOnForeground(this)){
            if(isMerlinBound) {
                unbindMerlin();
            }
            if(isReceiverRegistered){
                unregisterReceiver(mReceiver);
            }
            if(RealmHelper.getInstance() != null){
                RealmHelper.getInstance().close();
                RealmHelper.getInstance().logRealmInstanceCount("AppInBackground");
                RealmHelper.setMyInstance(null);
            }
        }
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        if(mActivitiesBackStack.contains(activity.getClass())){
            mActivitiesBackStack.remove(activity.getClass());
        }
    }
    /* END Override ActivityLifecycleCallbacks Methods */

/* START Override IEndSyncCallback Methods */
    @Override
    public void onEndSync(Intent intent) {
        Constants.SyncType syncType = null;
        if(intent.hasExtra(Constants.INTENT_DATA_SYNC_TYPE)){
            syncType = (Constants.SyncType) intent.getSerializableExtra(Constants.INTENT_DATA_SYNC_TYPE);
        }
        if(syncType != null){
            checkSyncType(syncType);
        }
    }
    /* END IEndSyncCallback Methods */

private void checkSyncType(Constants.SyncType){
    [...]
    if( mActivitiesBackStack.contains(ActivityClass.class) ){
         doOperation()     }
}

}

In my case I used "Application.ActivityLifecycleCallbacks" to:

  • Bind/Unbind Merlin Instance (used to get event when the app lose or get connection, for example when you close mobile data or when you open it). It is useful after the "OnConnectivityChanged" intent action was disabled. For more info about MERLIN see: MERLIN INFO LINK

  • Close my last Realm Instance when the application is closed; I will init it inside a BaseActivity wich is extended from all others activities and which has a private RealmHelper Instance. For more info about REALM see: REALM INFO LINK For instance I have a static "RealmHelper" instance inside my "RealmHelper" class which is instantiated inside my application "onCreate". I have a synchronization service in which I create I new "RealmHelper" because Realm is "Thread-Linked" and a Realm Instance can't work inside a different Thread. So in order to follow Realm Documentation "You Need To Close All Opened Realm Instances to avoid System Resources Leaks", to accomplish this thing I used the "Application.ActivityLifecycleCallbacks" as you can see up.

  • Finally I have a receiver wich is triggered when I finish to synchronize my application, then when the sync end it will call the "IEndSyncCallback" "onEndSync" method in which I look if I have a specific Activity Class inside my ActivitiesBackStack List because I need to update the data on the view if the sync updated them and I could need to do others operations after the app sync.

That's all, hope this is helpful. See u :)

Docker: Multiple Dockerfiles in project

In Intellij, I simple changed the name of the docker files to *.Dockerfile, and associated the file type *.Dockerfile to docker syntax.

Read binary file as string in Ruby

You can probably encode the tar file in Base64. Base 64 will give you a pure ASCII representation of the file that you can store in a plain text file. Then you can retrieve the tar file by decoding the text back.

You do something like:

require 'base64'

file_contents = Base64.encode64(tar_file_data)

Have look at the Base64 Rubydocs to get a better idea.

Overloading operators in typedef structs (c++)

The breakdown of your declaration and its members is somewhat littered:

Remove the typedef

The typedef is neither required, not desired for class/struct declarations in C++. Your members have no knowledge of the declaration of pos as-written, which is core to your current compilation failure.

Change this:

typedef struct {....} pos;

To this:

struct pos { ... };

Remove extraneous inlines

You're both declaring and defining your member operators within the class definition itself. The inline keyword is not needed so long as your implementations remain in their current location (the class definition)


Return references to *this where appropriate

This is related to an abundance of copy-constructions within your implementation that should not be done without a strong reason for doing so. It is related to the expression ideology of the following:

a = b = c;

This assigns c to b, and the resulting value b is then assigned to a. This is not equivalent to the following code, contrary to what you may think:

a = c;
b = c;

Therefore, your assignment operator should be implemented as such:

pos& operator =(const pos& a)
{
    x = a.x;
    y = a.y;
    return *this;
}

Even here, this is not needed. The default copy-assignment operator will do the above for you free of charge (and code! woot!)

Note: there are times where the above should be avoided in favor of the copy/swap idiom. Though not needed for this specific case, it may look like this:

pos& operator=(pos a) // by-value param invokes class copy-ctor
{
    this->swap(a);
    return *this;
}

Then a swap method is implemented:

void pos::swap(pos& obj)
{
    // TODO: swap object guts with obj
}

You do this to utilize the class copy-ctor to make a copy, then utilize exception-safe swapping to perform the exchange. The result is the incoming copy departs (and destroys) your object's old guts, while your object assumes ownership of there's. Read more the copy/swap idiom here, along with the pros and cons therein.


Pass objects by const reference when appropriate

All of your input parameters to all of your members are currently making copies of whatever is being passed at invoke. While it may be trivial for code like this, it can be very expensive for larger object types. An exampleis given here:

Change this:

bool operator==(pos a) const{
    if(a.x==x && a.y== y)return true;
    else return false;
}

To this: (also simplified)

bool operator==(const pos& a) const
{
    return (x == a.x && y == a.y);
}

No copies of anything are made, resulting in more efficient code.


Finally, in answering your question, what is the difference between a member function or operator declared as const and one that is not?

A const member declares that invoking that member will not modifying the underlying object (mutable declarations not withstanding). Only const member functions can be invoked against const objects, or const references and pointers. For example, your operator +() does not modify your local object and thus should be declared as const. Your operator =() clearly modifies the local object, and therefore the operator should not be const.


Summary

struct pos
{
    int x;
    int y;

    // default + parameterized constructor
    pos(int x=0, int y=0) 
        : x(x), y(y)
    {
    }

    // assignment operator modifies object, therefore non-const
    pos& operator=(const pos& a)
    {
        x=a.x;
        y=a.y;
        return *this;
    }

    // addop. doesn't modify object. therefore const.
    pos operator+(const pos& a) const
    {
        return pos(a.x+x, a.y+y);
    }

    // equality comparison. doesn't modify object. therefore const.
    bool operator==(const pos& a) const
    {
        return (x == a.x && y == a.y);
    }
};

EDIT OP wanted to see how an assignment operator chain works. The following demonstrates how this:

a = b = c;

Is equivalent to this:

b = c;
a = b;

And that this does not always equate to this:

a = c;
b = c;

Sample code:

#include <iostream>
#include <string>
using namespace std;

struct obj
{
    std::string name;
    int value;

    obj(const std::string& name, int value)
        : name(name), value(value)
    {
    }

    obj& operator =(const obj& o)
    {
        cout << name << " = " << o.name << endl;
        value = (o.value+1); // note: our value is one more than the rhs.
        return *this;
    }    
};

int main(int argc, char *argv[])
{

    obj a("a", 1), b("b", 2), c("c", 3);

    a = b = c;
    cout << "a.value = " << a.value << endl;
    cout << "b.value = " << b.value << endl;
    cout << "c.value = " << c.value << endl;

    a = c;
    b = c;
    cout << "a.value = " << a.value << endl;
    cout << "b.value = " << b.value << endl;
    cout << "c.value = " << c.value << endl;

    return 0;
}

Output

b = c
a = b
a.value = 5
b.value = 4
c.value = 3
a = c
b = c
a.value = 4
b.value = 4
c.value = 3

Take a screenshot via a Python script on Linux

From this thread:

 import os
 os.system("import -window root temp.png")

VB.Net .Clear() or txtbox.Text = "" textbox clear methods

Public Sub EmptyTxt(ByVal Frm As Form)
    Dim Ctl As Control
    For Each Ctl In Frm.Controls
        If TypeOf Ctl Is TextBox Then Ctl.Text = ""
        If TypeOf Ctl Is GroupBox Then
            Dim Ctl1 As Control
            For Each Ctl1 In Ctl.Controls
                If TypeOf Ctl1 Is TextBox Then
                    Ctl1.Text = ""
                End If
            Next
        End If
    Next
End Sub

add this code in form and call this function

EmptyTxt(Me)

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

One quick note. Generators are cancellable, async/await — not. So for an example from the question, it does not really make sense of what to pick. But for more complicated flows sometimes there is no better solution than using generators.

So, another idea could be is to use generators with redux-thunk, but for me, it seems like trying to invent a bicycle with square wheels.

And of course, generators are easier to test.

Node JS Error: ENOENT

"/tmp/test.jpg" is not the correct path – this path starts with / which is the root directory.

In unix, the shortcut to the current directory is .

Try this "./tmp/test.jpg"

How does one generate a random number in Apple's Swift language?

Since Swift 4.2

There is a new set of APIs:

let randomIntFrom0To10 = Int.random(in: 0 ..< 10)
let randomDouble = Double.random(in: 1 ... 10)
  • All numeric types now have the random(in:) method that takes range.

  • It returns a number uniformly distributed in that range.


TL;DR

Well, what is wrong with the "good" old way?

  1. You have to use imported C APIs (They are different between platforms).

  2. And moreover...

What if I told you that the random is not that random?

If you use arc4random() (to calculate the remainder) like arc4random() % aNumber, the result is not uniformly distributed between the 0 and aNumber. There is a problem called the Modulo bias.

Modulo bias

Normally, the function generates a random number between 0 and MAX (depends on the type etc.). To make a quick, easy example, let's say the max number is 7 and you care about a random number in the range 0 ..< 2 (or the interval [0, 3) if you prefer that).

The probabilities for individual numbers are:

  • 0: 3/8 = 37.5%
  • 1: 3/8 = 37.5%
  • 2: 2/8 = 25%

In other words, you are more likely to end up with 0 or 1 than 2. Of course, bare in mind that this is extremely simplified and the MAX number is much higher, making it more "fair".

This problem is addressed by SE-0202 - Random unification in Swift 4.2

How to run a JAR file

You have to add a manifest to the jar, which tells the java runtime what the main class is. Create a file 'Manifest.mf' with the following content:

Manifest-Version: 1.0
Main-Class: your.programs.MainClass

Change 'your.programs.MainClass' to your actual main class. Now put the file into the Jar-file, in a subfolder named 'META-INF'. You can use any ZIP-utility for that.

Can't find file executable in your configured search path for gnc gcc compiler

Here's an easy way for Windows users.

  1. Uninstall the existing codeblocks from your system.
  2. Restart system.
  3. Go to http://www.codeblocks.org/downloads/26
  4. Download the codeblocks-16.01mingw-setup.exe file. It includes the GCC/G++ compiler and GDB debugger from TDM-GCC (version 4.9.2, 32 bit, SJLJ).

Xcode 6.1 - How to uninstall command line tools?

An excerpt from an apple technical note (Thanks to matthias-bauch)

Xcode includes all your command-line tools. If it is installed on your system, remove it to uninstall your tools.

If your tools were downloaded separately from Xcode, then they are located at /Library/Developer/CommandLineTools on your system. Delete the CommandLineTools folder to uninstall them.

you could easily delete using terminal:

Here is an article that explains how to remove the command line tools but do it at your own risk.Try this only if any of the above doesn't work.

How to make a owl carousel with arrows instead of next previous

The following code works for me on owl carousel .

https://github.com/OwlFonk/OwlCarousel

$(".owl-carousel").owlCarousel({
    items: 1,
    autoplay: true,
    navigation: true,
    navigationText: ["<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>"]
});

For OwlCarousel2

https://owlcarousel2.github.io/OwlCarousel2/docs/api-options.html

 $(".owl-carousel").owlCarousel({
    items: 1,
    autoplay: true,
    nav: true,
    navText: ["<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>"]
});

Make xargs execute the command once for each line of input

find path -type f | xargs -L1 command 

is all you need.

MySQL: ERROR 1227 (42000): Access denied - Cannot CREATE USER

First thing to do is run this:

SHOW GRANTS;

You will quickly see you were assigned the anonymous user to authenticate into mysql.

Instead of logging into mysql with

mysql

login like this:

mysql -uroot

By default, root@localhost has all rights and no password.

If you cannot login as root without a password, do the following:

Step 01) Add the two options in the mysqld section of my.ini:

[mysqld]
skip-grant-tables
skip-networking

Step 02) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 03) Connect to mysql

mysql

Step 04) Create a password from root@localhost

UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit

Step 05) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 06) Login as root with password

mysql -u root -p

You should be good from there.

CAVEAT: Please remove anonymous users !!!

Change a Rails application to production

If mipadi's suggestion doesn't work, add this to config/environment.rb

# force Rails into production mode when                          
# you don't control web/app server and can't set it the proper way                  
ENV['RAILS_ENV'] ||= 'production'

StringBuilder vs String concatenation in toString() in Java

Version 1 is preferable because it is shorter and the compiler will in fact turn it into version 2 - no performance difference whatsoever.

More importantly given we have only 3 properties it might not make a difference, but at what point do you switch from concat to builder?

At the point where you're concatenating in a loop - that's usually when the compiler can't substitute StringBuilder by itself.

How to Code Double Quotes via HTML Codes

There is no difference, in browsers that you can find in the wild these days (that is, excluding things like Netscape 1 that you might find in a museum). There is no reason to suspect that any of them would be deprecated ever, especially since they are all valid in XML, in HTML 4.01, and in HTML5 CR.

There is no reason to use any of them, as opposite to using the Ascii quotation mark (") directly, except in the very special case where you have an attribute value enclosed in such marks and you would like to use the mark inside the value (e.g., title="Hello &quot;world&quot;"), and even then, there are almost always better options (like title='Hello "word"' or title="Hello “word”".

If you want to use “smart” quotation marks instead, then it’s a different question, and none of the constructs has anything to do with them. Some people expect notations like &quot; to produce “smart” quotes, but it is easy to see that they don’t; the notations unambiguously denote the Ascii quote ("), as used in computer languages.

Adding sheets to end of workbook in Excel (normal method not working?)

Try this

mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name

Android Studio: Gradle: error: cannot find symbol variable

Open project in android studio click file and click Invalidate Caches/Restart

fatal error C1083: Cannot open include file: 'xyz.h': No such file or directory?

I ran into this error in a different situation, posting the resolution for those arriving via search: from within Visual Studio, I had copied a file from one project and pasted into another. Turns out that creates a symbolic link, not an actual copy. Thus the project did not find the file in the current working directory as expected. When I made a physical copy instead, in Windows Explorer, suddenly #include "myfile.h" worked.

How do I change the color of radio buttons?

Well to create extra elements we can use :after, :before (so we don’t have to change the HTML that much). Then for radio buttons and checkboxes we can use :checked. There are a few other pseudo elements we can use as well (such as :hover). Using a mixture of these we can create some pretty cool custom forms. check this

string decode utf-8

A string needs no encoding. It is simply a sequence of Unicode characters.

You need to encode when you want to turn a String into a sequence of bytes. The charset the you choose (UTF-8, cp1255, etc.) determines the Character->Byte mapping. Note that a character is not necessarily translated into a single byte. In most charsets, most Unicode characters are translated to at least two bytes.

Encoding of a String is carried out by:

String s1 = "some text";
byte[] bytes = s1.getBytes("UTF-8"); // Charset to encode into

You need to decode when you have ? sequence of bytes and you want to turn them into a String. When y?u d? that you need to specify, again, the charset with which the byt?s were originally encoded (otherwise you'll end up with garbl?d t?xt).

Decoding:

String s2 = new String(bytes, "UTF-8"); // Charset with which bytes were encoded 

If you want to understand this better, a great text is "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)"

How to end a session in ExpressJS

req.session.destroy(); 

The above did not work for me so I did this.

req.session.cookie.expires = new Date().getTime();

By setting the expiration of the cookie to the current time, the session expired on its own.

How to change ReactJS styles dynamically?

Ok, finally found the solution.

Probably due to lack of experience with ReactJS and web development...

    var Task = React.createClass({
    render: function() {
      var percentage = this.props.children + '%';
      ....
        <div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
      ...

I created the percentage variable outside in the render function.

Find Number of CPUs and Cores per CPU using Command Prompt

In order to check the absence of physical sockets run:

wmic cpu get SocketDesignation

Equivalent of String.format in jQuery

The source code for ASP.NET AJAX is available for your reference, so you can pick through it and include the parts you want to continue using into a separate JS file. Or, you can port them to jQuery.

Here is the format function...

String.format = function() {
  var s = arguments[0];
  for (var i = 0; i < arguments.length - 1; i++) {       
    var reg = new RegExp("\\{" + i + "\\}", "gm");             
    s = s.replace(reg, arguments[i + 1]);
  }

  return s;
}

And here are the endsWith and startsWith prototype functions...

String.prototype.endsWith = function (suffix) {
  return (this.substr(this.length - suffix.length) === suffix);
}

String.prototype.startsWith = function(prefix) {
  return (this.substr(0, prefix.length) === prefix);
}

ReflectionException: Class ClassName does not exist - Laravel

If the issue is not resolved by composer dump-autoload or is not a newly created class.

Check for syntax errors in your class and its traits as well. In my case, there was a syntax error in a Trait, but ReflectionException was shown for the actual Class using that Trait instead.

Left Join With Where Clause

You might find it easier to understand by using a simple subquery

SELECT `settings`.*, (
    SELECT `value` FROM `character_settings`
    WHERE `character_settings`.`setting_id` = `settings`.`id`
      AND `character_settings`.`character_id` = '1') AS cv_value
FROM `settings`

The subquery is allowed to return null, so you don't have to worry about JOIN/WHERE in the main query.

Sometimes, this works faster in MySQL, but compare it against the LEFT JOIN form to see what works best for you.

SELECT s.*, c.value
FROM settings s
LEFT JOIN character_settings c ON c.setting_id = s.id AND c.character_id = '1'

How can I return the difference between two lists?

With Stream API you can do something like this:

List<String> aWithoutB = a.stream()
    .filter(element -> !b.contains(element))
    .collect(Collectors.toList());

List<String> bWithoutA = b.stream()
    .filter(element -> !a.contains(element))
    .collect(Collectors.toList());

Run java jar file on a server as background process

If you're using Ubuntu and have "Upstart" (http://upstart.ubuntu.com/) you can try this:

Create /var/init/yourservice.conf

with the following content

description "Your Java Service"  
author "You"  

start on runlevel [3]  
stop on shutdown  

expect fork  

script     
    cd /web 
    java -jar server.jar >/var/log/yourservice.log 2>&1  
    emit yourservice_running  
end script  

Now you can issue the service yourservice start and service yourservice stop commands. You can tail /var/log/yourservice.log to verify that it's working.

If you just want to run your jar from the console without it hogging the console window, you can just do:

java -jar /web/server.jar > /var/log/yourservice.log 2>&1

Are 64 bit programs bigger and faster than 32 bit versions?

Any applications that require CPU usage such as transcoding, display performance and media rendering, whether it be audio or visual, will certainly require (at this point) and benefit from using 64 bit versus 32 bit due to the CPU's ability to deal with the sheer amount of data being thrown at it. It's not so much a question of address space as it is the way the data is being dealt with. A 64 bit processor, given 64 bit code, is going to perform better, especially with mathematically difficult things like transcoding and VoIP data - in fact, any sort of 'math' applications should benefit by the usage of 64 bit CPUs and operating systems. Prove me wrong.

How can I create 2 separate log files with one log4j config file?

Try the following configuration:

log4j.rootLogger=TRACE, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.appender.debugLog=org.apache.log4j.FileAppender
log4j.appender.debugLog.File=logs/debug.log
log4j.appender.debugLog.layout=org.apache.log4j.PatternLayout
log4j.appender.debugLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.appender.reportsLog=org.apache.log4j.FileAppender
log4j.appender.reportsLog.File=logs/reports.log
log4j.appender.reportsLog.layout=org.apache.log4j.PatternLayout
log4j.appender.reportsLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.category.debugLogger=TRACE, debugLog
log4j.additivity.debugLogger=false

log4j.category.reportsLogger=DEBUG, reportsLog
log4j.additivity.reportsLogger=false

Then configure the loggers in the Java code accordingly:

static final Logger debugLog = Logger.getLogger("debugLogger");
static final Logger resultLog = Logger.getLogger("reportsLogger");

Do you want output to go to stdout? If not, change the first line of log4j.properties to:

log4j.rootLogger=OFF

and get rid of the stdout lines.

Pass variable to function in jquery AJAX success callback

Since the settings object is tied to that ajax call, you can simply add in the indexer as a custom property, which you can then access using this in the success callback:

//preloader for images on gallery pages
window.onload = function() {
    var urls = ["./img/party/","./img/wedding/","./img/wedding/tree/"];

    setTimeout(function() {
        for ( var i = 0; i < urls.length; i++ ) {
            $.ajax({
                url: urls[i],
                indexValue: i,
                success: function(data) {
                    image_link(data , this.indexValue);

                    function image_link(data, i) {
                        $(data).find("a:contains(.jpg)").each(function(){ 
                            console.log(i);
                            new Image().src = urls[i] + $(this).attr("href");
                        });
                    }
                }
            });
        };  
    }, 1000);       
};

Edit: Adding in an updated JSFiddle example, as they seem to have changed how their ECHO endpoints work: https://jsfiddle.net/djujx97n/26/.

To understand how this works see the "context" field on the ajaxSettings object: http://api.jquery.com/jquery.ajax/, specifically this note:

"The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves."

A server with the specified hostname could not be found

If the problem occured in a MacOS project, as @nstein commented in this answer just go to your Target's Signing & Capabilities and allow Incoming and Outgoing network options.

PHP/MySQL Insert null values

This is one example where using prepared statements really saves you some trouble.

In MySQL, in order to insert a null value, you must specify it at INSERT time or leave the field out which requires additional branching:

INSERT INTO table2 (f1, f2)
  VALUES ('String Value', NULL);

However, if you want to insert a value in that field, you must now branch your code to add the single quotes:

INSERT INTO table2 (f1, f2)
  VALUES ('String Value', 'String Value');

Prepared statements automatically do that for you. They know the difference between string(0) "" and null and write your query appropriately:

$stmt = $mysqli->prepare("INSERT INTO table2 (f1, f2) VALUES (?, ?)");
$stmt->bind_param('ss', $field1, $field2);

$field1 = "String Value";
$field2 = null;

$stmt->execute();

It escapes your fields for you, makes sure that you don't forget to bind a parameter. There is no reason to stay with the mysql extension. Use mysqli and it's prepared statements instead. You'll save yourself a world of pain.

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

You are using str methods on an open file object.

You can read the file as a list of lines by simply calling list() on the file object:

with open('goodlines.txt') as f:
    mylist = list(f)

This does include the newline characters. You can strip those in a list comprehension:

with open('goodlines.txt') as f:
    mylist = [line.rstrip('\n') for line in f]

How do I call the base class constructor?

Use the name of the base class in an initializer-list. The initializer-list appears after the constructor signature before the method body and can be used to initialize base classes and members.

class Base
{
public:
  Base(char* name)
  {
     // ...
  }
};

class Derived : Base
{
public:
  Derived()
    : Base("hello")
  {
      // ...
  }
};

Or, a pattern used by some people is to define 'super' or 'base' yourself. Perhaps some of the people who favour this technique are Java developers who are moving to C++.

class Derived : Base
{
public:
  typedef Base super;
  Derived()
    : super("hello")
  {
      // ...
  }
};

Changing precision of numeric column in Oracle

If the table is compressed this will work:

alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);

update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;

update EVAPP_FEES set AMOUNT = null;

alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;

alter table EVAPP_FEES move nocompress;

alter table EVAPP_FEES drop column AMOUNT_TEMP;

alter table EVAPP_FEES compress;

Adding a JAR to an Eclipse Java library

You might also consider using a build tool like Maven to manage your dependencies. It is very easy to setup and helps manage those dependencies automatically in eclipse. Definitely worth the effort if you have a large project with a lot of external dependencies.

How to input automatically when running a shell over SSH?

There definitely is... Use the spawn, expect, and send commands:

spawn test.sh
expect "Are you sure you want to continue connecting (yes/no)?"
send "yes"

There are more examples all over Stack Overflow, see: Help with Expect within a bash script

You may need to install these commands first, depending on your system.

com.google.android.gms:play-services-measurement-base is being requested by various other libraries

If the message is:

The library com.google.android.gms:play-services-measurement-base is being requested by various other libraries at [[15.0.4,15.0.4]], but resolves to 15.0.2. Disable the plugin and check your dependencies tree using ./gradlew :app:dependencies.

Change the version of all the play services libraries you are using to the one you need (15.0.2 in this case) could solve the problem.

In my case, I've changed:

implementation 'com.google.android.gms:play-services-base:+' -> implementation 'com.google.android.gms:play-services-base:15.0.2'
implementation 'com.google.android.gms:play-services-location:+' -> implementation 'com.google.android.gms:play-services-location:15.0.2'
implementation 'com.google.android.gms:play-services-maps:+' -> implementation 'com.google.android.gms:play-services-maps:15.0.2'
implementation 'com.google.android.gms:play-services-auth:+' -> implementation 'com.google.android.gms:play-services-auth:15.0.2'
implementation 'com.google.android.gms:play-services-places:+' -> implementation 'com.google.android.gms:play-services-places:15.0.2'

How to create Java gradle project

Unfortunately you cannot do it in one command. There is an open issue for the very feature.

Currently you'll have to do it by hand. If you need to do it often, you can create a custom gradle plugin, or just prepare your own project skeleton and copy it when needed.

EDIT

The JIRA issue mentioned above has been resolved, as of May 1, 2013, and fixed in 1.7-rc-1. The documentation on the Build Init Plugin is available, although it indicates that this feature is still in the "incubating" lifecycle.

java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication Maven

Your jar does not contain the dependencies such as spring-boot which it is looking for during runtime. You can build a consolidated jar with all the dependencies as outlined in this question.

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

The error you have is because -credential without -computername can't exist.

You can try this way:

Invoke-Command -Credential $migratorCreds  -ScriptBlock ${function:Get-LocalUsers} -ArgumentList $xmlPRE,$migratorCreds -computername YOURCOMPUTERNAME