Programs & Examples On #Pisa

Pisa is a Python HTML/XHTML/CSS to PDF converter

Angular 2 - How to navigate to another route using this.router.parent.navigate('/about')?

import { Router } from '@angular/router';
//in your constructor
constructor(public router: Router){}

//navigation 
link.this.router.navigateByUrl('/home');

What is the PostgreSQL equivalent for ISNULL()

How do I emulate the ISNULL() functionality ?

SELECT (Field IS NULL) FROM ...

how to open .mat file without using MATLAB?

.mat files contain binary data, so you will not be able to open them easily with a word processor. There are some options for opening them outside of MATLAB:

If all you need to do is look at the files, you could obtain Octave, which is a free, but somewhat slower implementation of MATLAB. You can refer to How do you open .mat files in Octave? for more information on the subject. You can get octave from http://www.gnu.org/software/octave/download.html. The interface is very similar to MATLAB's.

As NKN and Ergodicity mentioned, there are python libaries available for this as well.

The most hardcore solution would be to write your own processor from scratch. The MAT file specification is available from MathWorks at http://www.mathworks.com/help/pdf_doc/matlab/matfile_format.pdf.

Issue with adding common code as git submodule: "already exists in the index"

You need to remove your submodule git repository (projectfolder in this case) first for git path.

rm -rf projectfolder

git rm -r projectfolder

and then add submodule

git submodule add <git_submodule_repository> projectfolder

Docker error response from daemon: "Conflict ... already in use by container"

For people landing here from google like me and just want to build containers using multiple docker-compose files with one shared service:

Sometimes you have different projects that would share e.g. a database docker container. Only the first run should start the DB-Docker, the second should be detect that the DB is already running and skip this. To achieve such a behaviour we need the Dockers to lay in the same network and in the same project. Also the docker container name needs to be the same.

1st: Set the same network and container name in docker-compose

docker-compose in project 1:

version: '3'

services:
    service1:
        depends_on:
            - postgres
        # ...
        networks:
            - dockernet

    postgres:
        container_name: project_postgres
        image: postgres:10-alpine
        restart: always
        # ...
        networks:
            - dockernet

networks:
    dockernet:

docker-compose in project 2:

version: '3'

services:
    service2:
        depends_on:
            - postgres
        # ...
        networks:
            - dockernet

    postgres:
        container_name: project_postgres
        image: postgres:10-alpine
        restart: always
        # ...
        networks:
            - dockernet

networks:
    dockernet:

2nd: Set the same project using -p param or put both files in the same directory.

docker-compose -p {projectname} up

How to remove element from an array in JavaScript?

You can also do this with reduce:

let arr = [1, 2, 3]

arr.reduce((xs, x, index) => {
        if (index == 0) {
            return xs
        } else {
            return xs.concat(x)
        }
    }, Array())

// Or if you like a oneliner
arr.reduce((xs, x, index) => index == 0 ? xs : xs.concat(x), Array())

Direct method from SQL command text to DataSet

Just finish it up.

string sqlCommand = "SELECT * FROM TABLE";
string connectionString = "blahblah";

DataSet ds = GetDataSet(sqlCommand, connectionString);
DataSet GetDataSet(string sqlCommand, string connectionString)
{
    DataSet ds = new DataSet();
    using (SqlCommand cmd = new SqlCommand(
        sqlCommand, new SqlConnection(connectionString)))
    {
        cmd.Connection.Open();
        DataTable table = new DataTable();
        table.Load(cmd.ExecuteReader());
        ds.Tables.Add(table);
    }
    return ds;
}

WPF: Grid with column/row margin/padding?

Edited:

To give margin to any control you could wrap the control with border like this

<!--...-->
    <Border Padding="10">
            <AnyControl>
<!--...-->

Is there an equivalent to e.PageX position for 'touchstart' event as there is for click event?

Check Safari developer reference on Touch class.

According to this, pageX/Y should be available - maybe you should check spelling? make sure it's pageX and not PageX

How to read a specific line using the specific line number from a file in Java?

Joachim is right on, of course, and an alternate implementation to Chris' (for small files only because it loads the entire file) might be to use commons-io from Apache (though arguably you might not want to introduce a new dependency just for this, if you find it useful for other stuff too though, it could make sense).

For example:

String line32 = (String) FileUtils.readLines(file).get(31);

http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html#readLines(java.io.File, java.lang.String)

How do you add an image?

In order to add attributes, XSL wants

<xsl:element name="img">
     (attributes)
</xsl:element>

instead of just

<img>
     (attributes)
</img>

Although, yes, if you're just copying the element as-is, you don't need any of that.

Load HTML File Contents to Div [without the use of iframes]

2019
Using fetch

<script>
fetch('page.html')
  .then(data => data.text())
  .then(html => document.getElementById('elementID').innerHTML = html);
</script>

<div id='elementID'> </div>

fetch needs to receive a http or https link, this means that it won't work locally.

Note: As Altimus Prime said, it is a feature for modern browsers

String replacement in Objective-C

If you want multiple string replacement:

NSString *s = @"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); // => foobarbazfoo

How to position text over an image in css

A small and short way of doing the same

HTML

<div class="image">
     <p>
        <h3>Heading 3</h3>
        <h5>Heading 5</h5>
     </p>
</div>

CSS

.image {
        position: relative;
        margin-bottom: 20px;
        width: 100%;
        height: 300px;
        color: white;
        background: url('../../Images/myImg.jpg') no-repeat;
        background-size: 250px 250px;
    }

Programmatically Add CenterX/CenterY Constraints

Center in container

enter image description here

The code below does the same thing as centering in the Interface Builder.

override func viewDidLoad() {
    super.viewDidLoad()

    // set up the view
    let myView = UIView()
    myView.backgroundColor = UIColor.blue
    myView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(myView)

    // Add code for one of the constraint methods below
    // ...
}

Method 1: Anchor Style

myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

Method 2: NSLayoutConstraint Style

NSLayoutConstraint(item: myView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0).isActive = true

Notes

  • Anchor style is the preferred method over NSLayoutConstraint Style, however it is only available from iOS 9, so if you are supporting iOS 8 then you should still use NSLayoutConstraint Style.
  • You will also need to add length and width constraints.
  • My full answer is here.

Multithreading in Bash

You can run several copies of your script in parallel, each copy for different input data, e.g. to process all *.cfg files on 4 cores:

    ls *.cfg | xargs -P 4 -n 1 read_cfg.sh

The read_cfg.sh script takes just one parameters (as enforced by -n)

MySQL my.ini location

You have to look I the folder C:\Program Files\MySQL\MySQL Server 5.5 but there is a problem. When you perform an MSI install of MySQL, my.ini is not created. There will be sample .ini files in that folder. In order to use one of them, say my-medium.ini, you need to do the following before a MySQL restart:

cd C:\Program Files\MySQL\MySQL Server 5.5
copy my-medium.ini my.ini
net stop mysql
net start mysql

Once, you do this, my.ini can be read by C:\Program Files\MySQL\MySQL Server 5.5\bin\mysql.exe.

Is there a 'box-shadow-color' property?

Maybe this is new (I am also pretty crap at css3), but I have a page that uses exactly what you suggest:

-moz-box-shadow: 10px 10px 5px #384e69;
-webkit-box-shadow: 10px 10px 5px #384e69;
box-shadow: 10px 10px 5px #384e69;}

.. and it works fine for me (in Chrome at least).

Have a div cling to top of screen if scrolled down past it

There was a previous question today (no answers) that gave a good example of this functionality. You can check the relevant source code for specifics (search for "toolbar"), but basically they use a combination of webdestroya's solution and a bit of JavaScript:

  1. Page loads and element is position: static
  2. On scroll, the position is measured, and if the element is position: static and it's off the page then the element is flipped to position: fixed.

I'd recommend checking the aforementioned source code though, because they do handle some "gotchas" that you might not immediately think of, such as adjusting scroll position when clicking on anchor links.

How to find SQL Server running port?

try once:-

USE master
DECLARE       @portNumber   NVARCHAR(10)
EXEC   xp_instance_regread
@rootkey    = 'HKEY_LOCAL_MACHINE',
@key        =
'Software\Microsoft\Microsoft SQL Server\MSSQLServer\SuperSocketNetLib\Tcp\IpAll',
@value_name = 'TcpDynamicPorts',
@value      = @portNumber OUTPUT
SELECT [Port Number] = @portNumber
GO

How to read data from a zip file without having to unzip the entire file

In such case you will need to parse zip local header entries. Each file, stored in zip file, has preceding Local File Header entry, which (normally) contains enough information for decompression, Generally, you can make simple parsing of such entries in stream, select needed file, copy header + compressed file data to other file, and call unzip on that part (if you don't want to deal with the whole Zip decompression code or library).

javascript clear field value input

Here is one solution with jQuery for browsers that don't support the placeholder attribute.

$('[placeholder]').focus(function() {
  var input = $(this);

  if (input.val() == input.attr('placeholder')) {
    input.val('');
    input.removeClass('placeholder');
  }
}).blur(function() {
  var input = $(this);

  if (input.val() == '' || input.val() == input.attr('placeholder')) {
    input.addClass('placeholder');
    input.val(input.attr('placeholder'));
  }
}).blur();

Found here: http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html

Angular 2 Unit Tests: Cannot find name 'describe'

You need to install typings for jasmine. Assuming you are on a relatively recent version of typescript 2 you should be able to do:

npm install --save-dev @types/jasmine

Beginner Python Practice?

You may be interested in Python interactive tutorial for begginers and advance users , it has many available practices together with interactive interface + advance development tricks for advance users.

How to hide action bar before activity is created, and then show it again?

Setting android:windowActionBar="false" truly disables the ActionBar but then, as you say, getActionBar(); returns null. This is solved by:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    getActionBar().hide();

    setContentView(R.layout.splash); // be sure you call this AFTER requestFeature

This creates the ActionBar and immediately hides it before it had the chance to be displayed.

But now there is another problem. After putting windowActionBar="false" in the theme, the Activity draws its normal Window Title instead of an ActionBar.
If we try to avoid this by using some of the *.NoTitleBar stock themes or we try to put <item name="android:windowNoTitle">true</item> in our own theme, it won't work.
The reason is that the ActionBar depends on the Window Title to display itself - that is the ActionBar is a transformed Window Title.
So the trick which can help us out is to add one more thing to our Activity theme xml:

<item name="android:windowActionBar">false</item>
<item name="android:windowTitleSize">0dp</item>

This will make the Window Title with zero height, thus practically invisible .

In your case, after you are done with displaying the splash screen you can simply call

setContentView(R.layout.main);
getActionBar().show();

and you are done. The Activity will start with no ActionBar flickering, nor Window Title showing.

ADDON: If you show and hide the ActionBar multiple times maybe you have noticed that the first showing is not animated. From then on showing and hiding are animated. If you want to have animation on the first showing too you can use this:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_ACTION_BAR);

    // delaying the hiding of the ActionBar
    Handler h = new Handler();
    h.post(new Runnable() {     
        @Override
        public void run() {
            getActionBar().hide();
        }
    });

The same thing can be achieved with:

protected void onPostResume() {
    super.onPostResume();
    getActionBar().hide();

but it may need some extra logic to check if this is the first showing of the Activity.

The idea is to delay a little the hiding of the ActionBar. In a way we let the ActionBar be shown, but then hide it immediately. Thus we go beyond the first non-animated showing and next showing will be considered second, thus it will be animated.

As you may have guessed there is a chance that the ActionBar could be seen before it has been hidden by the delayed operation. This is actually the case. Most of the time nothing is seen but yet, once in a while, you can see the ActionBar flicker for a split second.

In any case this is not a pretty solution, so I welcome any suggestions.

Addition for v7 support actionbar user, the code will be:

getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
getSupportActionBar().hide();

Show a leading zero if a number is less than 10

Try this

function pad (str, max) {
  return str.length < max ? pad("0" + str, max) : str;
}

alert(pad("5", 2));

Example

http://jsfiddle.net/

Or

var number = 5;
var i;
if (number < 10) {
    alert("0"+number);
}

Example

http://jsfiddle.net/

How to toggle font awesome icon on click?

Generally and simply it works like this:

_x000D_
_x000D_
<script>_x000D_
            $(document).ready(function () {_x000D_
                $('i').click(function () {_x000D_
                    $(this).toggleClass('fa-plus-square fa-minus-square');_x000D_
                });_x000D_
            });_x000D_
</script>
_x000D_
_x000D_
_x000D_

JSON string to JS object

You can use eval(jsonString) if you trust the data in the string, otherwise you'll need to parse it properly - check json.org for some code samples.

Javascript one line If...else...else if statement

tl;dr

Yes, you can... If a then a, else if b then if c then c(b), else b, else null

a ? a : (b ? (c ? c(b) : b) : null)

a
  ? a
  : b
      ? c
        ? c(b)
        : b
      : null

longer version

Ternary operator ?: used as inline if-else is right associative. In short this means that the rightmost ? gets fed first and it takes exactly one closest operand on the left and two, with a :, on the right.

Practically speaking, consider the following statement (same as above):

a ? a : b ? c ? c(b) : b : null

The rightmost ? gets fed first, so find it and its surrounding three arguments and consecutively expand to the left to another ?.

   a ? a : b ? c ? c(b) : b : null
                 ^                  <---- RTL
1.            |1-?-2----:-3|
             ^ <-
2.        |1-?|--2---------|:-3---|
     ^ <-
3.|1-?-2-:|--3--------------------|

result: a ? a : (b ? (c ? c(b) : b) : null)

This is how computers read it:

  1. Term a is read.
    Node: a
  2. Nonterminal ? is read.
    Node: a ?
  3. Term a is read.
    Node: a ? a
  4. Nonterminal : is read.
    Node: a ? a :
  5. Term b is read.
    Node: a ? a : b
  6. Nonterminal ? is read, triggering the right-associativity rule. Associativity decides:
    node: a ? a : (b ?
  7. Term c is read.
    Node: a ? a : (b ? c
  8. Nonterminal ? is read, re-applying the right-associativity rule.
    Node: a ? a : (b ? (c ?
  9. Term c(b) is read.
    Node: a ? a : (b ? (c ? c(b)
  10. Nonterminal : is read.
    Node: a ? a : (b ? (c ? c(b) :
  11. Term b is read.
    Node: a ? a : (b ? (c ? c(b) : b
  12. Nonterminal : is read. The ternary operator ?: from previous scope is satisfied and the scope is closed.
    Node: a ? a : (b ? (c ? c(b) : b) :
  13. Term null is read.
    Node: a ? a : (b ? (c ? c(b) : b) : null
  14. No tokens to read. Close remaining open parenthesis.
    #Result is: a ? a : (b ? (c ? c(b) : b) : null)

Better readability

The ugly oneliner from above could (and should) be rewritten for readability as:
(Note that the indentation does not implicitly define correct closures as brackets () do.)

a
  ? a
  : b
      ? c
        ? c(b)
        : b
      : null

for example

return a + some_lengthy_variable_name > another_variable
        ? "yep"
        : "nop"

More reading

Mozilla: JavaScript Conditional Operator
Wiki: Operator Associativity


Bonus: Logical operators

var a = 0 // 1
var b = 20
var c = null // x=> {console.log('b is', x); return true} // return true here!

a
  && a
  || b
      && c
        && c(b) // if this returns false, || b is processed
        || b
      || null

Using logical operators as in this example is ugly and wrong, but this is where they shine...

"Null coalescence"

This approach comes with subtle limitations as explained in the link below. For proper solution, see Nullish coalescing in Bonus2.

function f(mayBeNullOrFalsy) {
  var cantBeNull = mayBeNullOrFalsy || 42                    // "default" value
  var alsoCantBe = mayBeNullOrFalsy ? mayBeNullOrFalsy : 42  // ugly...
  ..
}

Short-circuit evaluation

false && (anything) // is short-circuit evaluated to false.
true || (anything)  // is short-circuit evaluated to true.

Logical operators
Null coalescence
Short-circuit evaluation


Bonus2: new in JS

Proper "Nullish coalescing"

developer.mozilla.org~Nullish_coalescing_operator

function f(mayBeNullOrUndefined, another) {
  var cantBeNullOrUndefined = mayBeNullOrUndefined ?? 42
  another ??= 37 // nullish coalescing self-assignment
  another = another ?? 37 // same effect
  ..
}

Optional chaining

Stage 4 finished proposal https://github.com/tc39/proposal-optional-chaining https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

// before
var street = user.address && user.address.street
// after
var street = user.address?.street

// combined with Nullish coalescing
// before
var street = user.address
  ? user.address.street
  : "N/A"

// after
var street = user.address?.street ?? "N/A"

// arrays
obj.someArray?.[index]

// functions
obj.someMethod?.(args)

Tooltip with HTML content without JavaScript

Similar to koningdavid's, but works on display:none and block, and adds additional styling.

_x000D_
_x000D_
div.tooltip {_x000D_
  position: relative;_x000D_
  /*  DO NOT include below two lines, as they were added so that the text that_x000D_
        is hovered over is offset from top of page*/_x000D_
  top: 10em;_x000D_
  left: 10em;_x000D_
  /* if want hover over icon instead of text based, uncomment below */_x000D_
  /*    background-image: url("../images/info_tooltip.svg");_x000D_
            /!* width and height of svg *!/_x000D_
            width: 16px;_x000D_
            height: 16px;*/_x000D_
}_x000D_
_x000D_
_x000D_
/* hide tooltip */_x000D_
_x000D_
div.tooltip span {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
_x000D_
/* show and style tooltip */_x000D_
_x000D_
div.tooltip:hover span {_x000D_
  /* show tooltip */_x000D_
  display: block;_x000D_
  /* position relative to container div.tooltip */_x000D_
  position: absolute;_x000D_
  bottom: 1em;_x000D_
  /* prettify */_x000D_
  padding: 0.5em;_x000D_
  color: #000000;_x000D_
  background: #ebf4fb;_x000D_
  border: 0.1em solid #b7ddf2;_x000D_
  /* round the corners */_x000D_
  border-radius: 0.5em;_x000D_
  /* prevent too wide tooltip */_x000D_
  max-width: 10em;_x000D_
}
_x000D_
<div class="tooltip">_x000D_
  hover_over_me_x000D_
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis purus dui. Sed at orci. </span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

To remove all the documents in all the collections:

db.getCollectionNames().forEach( function(collection_name) { 
    if (collection_name.indexOf("system.") == -1) {
        print ( ["Removing: ", db[collection_name].count({}), " documents from ", collection_name].join('') );
        db[collection_name].remove({}); 
    }
});

How to check if an object is defined?

If a class type is not defined, you'll get a compiler error if you try to use the class, so in that sense you should have to check.

If you have an instance, and you want to ensure it's not null, simply check for null:

if (value != null)
{
    // it's not null. 
}

no target device found android studio 2.1.1

trick that works for me when target device not found:

  • click the "attach debugger to android process" button. (that will enable adb integration for you)

  • click the run button

Web API optional parameters

I figured it out. I was using a bad example I found in the past of how to map query string to the method parameters.

In case anyone else needs it, in order to have optional parameters in a query string such as:

  • ~/api/products/filter?apc=AA&xpc=BB
  • ~/api/products/filter?sku=7199123

you would use:

[Route("products/filter/{apc?}/{xpc?}/{sku?}")]
public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null)
{ ... }

It seems odd to have to define default values for the method parameters when these types already have a default.

How to use JavaScript variables in jQuery selectors?

var name = this.name;
$("input[name=" + name + "]").hide();

OR you can do something like this.

var id = this.id;
$('#' + id).hide();

OR you can give some effect also.

$("#" + this.id).slideUp();

If you want to remove the entire element permanently form the page.

$("#" + this.id).remove();

You can also use it in this also.

$("#" + this.id).slideUp('slow', function (){
    $("#" + this.id).remove();
});

Get int from String, also containing letters, in Java

Just go through the string, building up an int as usual, but ignore non-number characters:

int res = 0;
for (int i=0; i < str.length(); i++) {
    char c = s.charAt(i);
    if (c < '0' || c > '9') continue;
    res = res * 10 + (c - '0');
}

Python: What OS am I running on?

try this:

import os

os.uname()

and you can make it :

info=os.uname()
info[0]
info[1]

Is there a Visual Basic 6 decompiler?

For the final, compiled code of your application, the short answer is “no”. Different tools are able to extract different information from the code (e.g. the forms setups) and there are P code decompilers (see Edgar's excellent link for such tools). However, up to this day, there is no decompiler for native code. I'm not aware of anything similar for other high-level languages either.

python JSON only get keys in first level

As Karthik mentioned, dct.keys() will work but it will return all the keys in dict_keys type not in list type. So if you want all the keys in a list, then list(dct.keys()) will work.

Git refusing to merge unrelated histories on rebase

I had the same problem. Try this:

git pull origin master --allow-unrelated-histories 

git push origin master

JavaScript: changing the value of onclick with or without jQuery

One gotcha with Jquery is that the click function do not acknowledge the hand coded onclick from the html.

So, you pretty much have to choose. Set up all your handlers in the init function or all of them in html.

The click event in JQuery is the click function $("myelt").click (function ....).

Differences between unique_ptr and shared_ptr

When wrapping a pointer in a unique_ptr you cannot have multiple copies of unique_ptr. The shared_ptr holds a reference counter which count the number of copies of the stored pointer. Each time a shared_ptr is copied, this counter is incremented. Each time a shared_ptr is destructed, this counter is decremented. When this counter reaches 0, then the stored object is destroyed.

TypeError: 'in <string>' requires string as left operand, not int

You simply need to make cab a string:

cab = '6176'

As the error message states, you cannot do <int> in <string>:

>>> 1 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
>>> 

because integers and strings are two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").

In fact, Python only allows you to use the in operator with a right operand of type string if the left operand is also of type string:

>>> '1' in '123'  # Works!
True
>>>
>>> [] in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> 1.0 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>>
>>> {} in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict
>>>

How to mock location on device?

I've had success with the following code. Albeit it got me a single lock for some reason (even if I've tried different LatLng pairs), it worked for me. mLocationManager is a LocationManager which is hooked up to a LocationListener:

private void getMockLocation()
{
    mLocationManager.removeTestProvider(LocationManager.GPS_PROVIDER);
    mLocationManager.addTestProvider
    (
      LocationManager.GPS_PROVIDER,
      "requiresNetwork" == "",
      "requiresSatellite" == "",
      "requiresCell" == "",
      "hasMonetaryCost" == "",
      "supportsAltitude" == "",
      "supportsSpeed" == "",
      "supportsBearing" == "",

      android.location.Criteria.POWER_LOW,
      android.location.Criteria.ACCURACY_FINE
    );      

    Location newLocation = new Location(LocationManager.GPS_PROVIDER);

    newLocation.setLatitude (/* TODO: Set Some Lat */);
    newLocation.setLongitude(/* TODO: Set Some Lng */);

    newLocation.setAccuracy(500);

    mLocationManager.setTestProviderEnabled
    (
      LocationManager.GPS_PROVIDER, 
      true
    );

    mLocationManager.setTestProviderStatus
    (
       LocationManager.GPS_PROVIDER,
       LocationProvider.AVAILABLE,
       null,
       System.currentTimeMillis()
    );      

    mLocationManager.setTestProviderLocation
    (
      LocationManager.GPS_PROVIDER, 
      newLocation
    );      
}

Visual Studio: Relative Assembly References Paths

Yes, just create a directory in your solution like lib/, and then add your dll to that directory in the filesystem and add it in the project (Add->Existing Item->etc). Then add the reference based on your project.

I have done this several times under svn and under cvs.

How to use readline() method in Java?

I advise you to go with Scanner instead of DataInputStream. Scanner is specifically designed for this purpose and introduced in Java 5. See the following links to know how to use Scanner.

Example

Scanner s = new Scanner(System.in);
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());

How do I increase the scrollback buffer in a running screen session?

Press Ctrl-a then : and then type

scrollback 10000

to get a 10000 line buffer, for example.

You can also set the default number of scrollback lines by adding

defscrollback 10000

to your ~/.screenrc file.

To scroll (if your terminal doesn't allow you to by default), press Ctrl-a ESC and then scroll (with the usual Ctrl-f for next page or Ctrl-a for previous page, or just with your mouse wheel / two-fingers). To exit the scrolling mode, just press ESC.

Another tip: Ctrl-a i shows your current buffer setting.

Convert java.util.Date to String

Here are examples of using new Java 8 Time API to format legacy java.util.Date:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z")
        .withZone(ZoneOffset.UTC);
    String utcFormatted = formatter.format(date.toInstant()); 

    ZonedDateTime utcDatetime = date.toInstant().atZone(ZoneOffset.UTC);
    String utcFormatted2 = utcDatetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z"));
    // gives the same as above

    ZonedDateTime localDatetime = date.toInstant().atZone(ZoneId.systemDefault());
    String localFormatted = localDatetime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
    // 2011-12-03T10:15:30+01:00[Europe/Paris]

    String nowFormatted = LocalDateTime.now().toString(); // 2007-12-03T10:15:30.123

It is nice about DateTimeFormatter that it can be efficiently cached as it is thread-safe (unlike SimpleDateFormat).

List of predefined fomatters and pattern notation reference.

Credits:

How to parse/format dates with LocalDateTime? (Java 8)

Java8 java.util.Date conversion to java.time.ZonedDateTime

Format Instant to String

What's the difference between java 8 ZonedDateTime and OffsetDateTime?

Regex for checking if a string is strictly alphanumeric

It's 2016 or later and things have progressed. This matches Unicode alphanumeric strings:

^[\\p{IsAlphabetic}\\p{IsDigit}]+$

See the reference (section "Classes for Unicode scripts, blocks, categories and binary properties"). There's also this answer that I found helpful.

How can I compare two strings in java and define which of them is smaller than the other alphabetically?

Haven't you heard about the Comparable interface being implemented by String ? If no, try to use

"abcda".compareTo("abcza")

And it will output a good root for a solution to your problem.

Set selected radio from radio group with a value

Try this:

$('input:radio[name="mygroup"][value="5"]').attr('checked',true);

JS Fiddle demo.

Storing an object in state of a React component?

this.setState({abc: {xyz: 'new value'}}); will NOT work, as state.abc will be entirely overwritten, not merged.

This works for me:

this.setState((previousState) => {
  previousState.abc.xyz = 'blurg';
  return previousState;
});

Unless I'm reading the docs wrong, Facebook recommends the above format. https://facebook.github.io/react/docs/component-api.html

Additionally, I guess the most direct way without mutating state is to directly copy by using the ES6 spread/rest operator:

const newState = { ...this.state.abc }; // deconstruct state.abc into a new object-- effectively making a copy
newState.xyz = 'blurg';
this.setState(newState);

Output single character in C

As mentioned in one of the other answers, you can use putc(int c, FILE *stream), putchar(int c) or fputc(int c, FILE *stream) for this purpose.

What's important to note is that using any of the above functions is from some to signicantly faster than using any of the format-parsing functions like printf.

Using printf is like using a machine gun to fire one bullet.

Is it possible to install both 32bit and 64bit Java on Windows 7?

To install 32-bit Java on Windows 7 (64-bit OS + Machine). You can do:

1) Download JDK: http://javadl.sun.com/webapps/download/AutoDL?BundleId=58124
2) Download JRE: http://www.java.com/en/download/installed.jsp?jre_version=1.6.0_22&vendor=Sun+Microsystems+Inc.&os=Linux&os_version=2.6.41.4-1.fc15.i686

3) System variable create: C:\program files (x86)\java\jre6\bin\

4) Anywhere you type java -version

it use 32-bit on (64-bit). I have to use this because lots of third party libraries do not work with 64-bit. Java wake up from the hell, give us peach :P. Go-language is killer.

How do I `jsonify` a list in Flask?

A list in a flask can be easily jsonify using jsonify like:

from flask import Flask,jsonify
app = Flask(__name__)

tasks = [
    {
        'id':1,
        'task':'this is first task'
    },
    {
        'id':2,
        'task':'this is another task'
    }
]

@app.route('/app-name/api/v0.1/tasks',methods=['GET'])
def get_tasks():
    return jsonify({'tasks':tasks})  #will return the json

if(__name__ == '__main__'):
    app.run(debug = True)

Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship

This code worked for me

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<UserDetail>()
            .HasRequired(d => d.User)
            .WithOptional(u => u.UserDetail)
            .WillCascadeOnDelete(true);
    }

The migration code was:

public override void Up()
    {
        AddForeignKey("UserDetail", "UserId", "User", "UserId", cascadeDelete: true);
    }

And it worked fine. When I first used

modelBuilder.Entity<User>()
    .HasOptional(a => a.UserDetail)
    .WithOptionalDependent()
    .WillCascadeOnDelete(true);

The migration code was:

AddForeignKey("User", "UserDetail_UserId", "UserDetail", "UserId", cascadeDelete: true); 

but it does not match any of the two overloads available (in EntityFramework 6)

How to add multiple classes to a ReactJS Component?

clsx makes this simple!

"The clsx function can take any number of arguments, each of which can be an Object, Array, Boolean, or String."

-- clsx docs on npmjs.com

Import it:

import clsx from 'clsx'

Use it:

<li key={index} className={clsx(activeClass, data.class, "main-class")}></li>

Maven: mvn command not found

Maven setup:

a. install maven from https://maven.apache.org/download.cgi

b. unzip maven and keep in C drive.

c. Set MAVEN_HOME in system variable. enter image description here

d. Set path for maven enter image description here

Powershell command to hide user from exchange address lists

I use this as a daily scheduled task to hide users disabled in AD from the Global Address List

$mailboxes = get-user | where {$_.UserAccountControl -like '*AccountDisabled*' -and $_.RecipientType -eq 'UserMailbox' } | get-mailbox  | where {$_.HiddenFromAddressListsEnabled -eq $false}

foreach ($mailbox in $mailboxes) { Set-Mailbox -HiddenFromAddressListsEnabled $true -Identity $mailbox }

What is meant by the term "hook" in programming?

In a generic sense, a "hook" is something that will let you, a programmer, view and/or interact with and/or change something that's already going on in a system/program.

For example, the Drupal CMS provides developers with hooks that let them take additional action after a "content node" is created. If a developer doesn't implement a hook, the node is created per normal. If a developer implements a hook, they can have some additional code run whenever a node is created. This code could do anything, including rolling back and/or altering the original action. It could also do something unrelated to the node creation entirely.

A callback could be thought of as a specific kind of hook. By implementing callback functionality into a system, that system is letting you call some additional code after an action has completed. However, hooking (as a generic term) is not limited to callbacks.

Another example. Sometimes Web Developers will refer to class names and/or IDs on elements as hooks. That's because by placing the ID/class name on an element, they can then use Javascript to modify that element, or "hook in" to the page document. (this is stretching the meaning, but it is commonly used and worth mentioning)

Is it possible to change a UIButtons background color?

This isn't as elegant as sub-classing UIButton, however if you just want something quick - what I did was create custom button, then a 1px by 1px image with the colour I'd want the button to be, and set the background of the button to that image for the highlighted state - works for my needs.

How do I redirect users after submit button click?

use

window.location.replace("login.php");

or simply window.location("login.php");

It is better than using window.location.href =, because replace() does not put the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco. If you want to simulate someone clicking on a link, use location.href. If you want to simulate an HTTP redirect, use location.replace.

jQuery checkbox check/uncheck

 $('mainCheckBox').click(function(){
    if($(this).prop('checked')){
        $('Id or Class of checkbox').prop('checked', true);
    }else{
        $('Id or Class of checkbox').prop('checked', false);
    }
});

Selecting default item from Combobox C#

This means that your selectedindex is out of the range of the array of items in the combobox. The array of items in your combo box is zero-based, so if you have 2 items, it's item 0 and item 1.

How to get values from selected row in DataGrid for Windows Form Application?

Description

Assuming i understand your question.

You can get the selected row using the DataGridView.SelectedRows Collection. If your DataGridView allows only one selected, have a look at my sample.

DataGridView.SelectedRows Gets the collection of rows selected by the user.

Sample

if (dataGridView1.SelectedRows.Count != 0)
{
    DataGridViewRow row = this.dataGridView1.SelectedRows[0];
    row.Cells["ColumnName"].Value
}

More Information

How to create standard Borderless buttons (like in the design guideline mentioned)?

To clear some confusion:

This is done in 2 steps: Setting the button background attribute to android:attr/selectableItemBackground creates you a button with feedback but no background.

android:background="?android:attr/selectableItemBackground"

The line to divide the borderless button from the rest of you layout is done by a view with the background android:attr/dividerVertical

android:background="?android:attr/dividerVertical"

For a better understanding here is a layout for a OK / Cancel borderless button combination at the bottom of your screen (like in the right picture above).

<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_alignParentBottom="true">
        <View
            android:layout_width="match_parent"
            android:layout_height="1dip"
            android:layout_marginLeft="4dip"
            android:layout_marginRight="4dip"
            android:background="?android:attr/dividerVertical"
            android:layout_alignParentTop="true"/>
        <View
            android:id="@+id/ViewColorPickerHelper"
            android:layout_width="1dip"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_alignParentBottom="true"
            android:layout_marginBottom="4dip"
            android:layout_marginTop="4dip"
            android:background="?android:attr/dividerVertical" 
            android:layout_centerHorizontal="true"/>
        <Button
            android:id="@+id/BtnColorPickerCancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_toLeftOf="@id/ViewColorPickerHelper"
            android:background="?android:attr/selectableItemBackground"
            android:text="@android:string/cancel" 
            android:layout_alignParentBottom="true"/>
        <Button
            android:id="@+id/BtnColorPickerOk"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:background="?android:attr/selectableItemBackground"
            android:text="@android:string/ok" 
            android:layout_alignParentBottom="true" 
            android:layout_toRightOf="@id/ViewColorPickerHelper"/>
    </RelativeLayout>

Differences between CHMOD 755 vs 750 permissions set

0755 = User:rwx Group:r-x World:r-x

0750 = User:rwx Group:r-x World:--- (i.e. World: no access)

r = read
w = write
x = execute (traverse for directories)

About "*.d.ts" in TypeScript

Like @takeshin said .d stands for declaration file for typescript (.ts).

Few points to be clarified before proceeding to answer this post -

  1. Typescript is syntactic superset of javascript.
  2. Typescript doesn't run on its own, it needs to be transpiled into javascript (typescript to javascript conversion)
  3. "Type definition" and "Type checking" are major add-on functionalities that typescript provides over javascript. (check difference between type script and javascript)

If you are thinking if typescript is just syntactic superset, what benefits does it offer - https://basarat.gitbooks.io/typescript/docs/why-typescript.html#the-typescript-type-system

To Answer this post -

As we discussed, typescript is superset of javascript and needs to be transpiled into javascript. So if a library or third party code is written in typescript, it eventually gets converted to javascript which can be used by javascript project but vice versa does not hold true.

For ex -

If you install javascript library -

npm install --save mylib

and try importing it in typescript code -

import * from "mylib";

you will get error.

"Cannot find module 'mylib'."

As mentioned by @Chris, many libraries like underscore, Jquery are already written in javascript. Rather than re-writing those libraries for typescript projects, an alternate solution was needed.

In order to do this, you can provide type declaration file in javascript library named as *.d.ts, like in above case mylib.d.ts. Declaration file only provides type declarations of functions and variables defined in respective javascript file.

Now when you try -

import * from "mylib";

mylib.d.ts gets imported which acts as an interface between javascript library code and typescript project.

Adjust plot title (main) position

We can use title() function with negative line value to bring down the title.

See this example:

plot(1, 1)
title("Title", line = -2)

enter image description here

How to see full query from SHOW PROCESSLIST

SHOW FULL PROCESSLIST

If you don't use FULL, "only the first 100 characters of each statement are shown in the Info field".

When using phpMyAdmin, you should also click on the "Full texts" option ("? T ?" on top left corner of a results table) to see untruncated results.

Modify XML existing content in C#

The XmlTextWriter is usually used for generating (not updating) XML content. When you load the xml file into an XmlDocument, you don't need a separate writer.

Just update the node you have selected and .Save() that XmlDocument.

Is there any WinSCP equivalent for linux?

Nautilus can be used easily in this case.

For Fedora 16, go to File -> Connect To server, select the appropriate protocol, enter required details and simply connect, just make sure that the SSH Server is running on other side. It works great.

Edit: This is valid on Ubuntu 14.04 as well

How do I change Bootstrap 3's glyphicons to white?

You can just create your own .white class and add it to the glyphicon element.

.white, .white a {
  color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>

Get GPS location via a service in Android

I don't understand what exactly is the problem with implementing location listening functionality in the Service. It looks pretty similar to what you do in Activity. Just define a location listener and register for location updates. You can refer to the following code as example:

Manifest file:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity android:label="@string/app_name" android:name=".LocationCheckerActivity" >
        <intent-filter >
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service android:name=".MyService" android:process=":my_service" />
</application>

The service file:

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {

    private static final String TAG = "BOOMBOOMTESTGPS";
    private LocationManager mLocationManager = null;
    private static final int LOCATION_INTERVAL = 1000;
    private static final float LOCATION_DISTANCE = 10f;

    private class LocationListener implements android.location.LocationListener {
        Location mLastLocation;

        public LocationListener(String provider) {
            Log.e(TAG, "LocationListener " + provider);
            mLastLocation = new Location(provider);
        }

        @Override
        public void onLocationChanged(Location location) {
            Log.e(TAG, "onLocationChanged: " + location);
            mLastLocation.set(location);
        }

        @Override
        public void onProviderDisabled(String provider) {
            Log.e(TAG, "onProviderDisabled: " + provider);
        }

        @Override
        public void onProviderEnabled(String provider) {
            Log.e(TAG, "onProviderEnabled: " + provider);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.e(TAG, "onStatusChanged: " + provider);
        }
    }

    LocationListener[] mLocationListeners = new LocationListener[]{
            new LocationListener(LocationManager.GPS_PROVIDER),
            new LocationListener(LocationManager.NETWORK_PROVIDER)
    };

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        Log.e(TAG, "onCreate");
        initializeLocationManager();
        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                    mLocationListeners[1]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "network provider does not exist, " + ex.getMessage());
        }
        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                    mLocationListeners[0]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "gps provider does not exist " + ex.getMessage());
        }
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy");
        super.onDestroy();
        if (mLocationManager != null) {
            for (int i = 0; i < mLocationListeners.length; i++) {
                try {
                    mLocationManager.removeUpdates(mLocationListeners[i]);
                } catch (Exception ex) {
                    Log.i(TAG, "fail to remove location listners, ignore", ex);
                }
            }
        }
    }

    private void initializeLocationManager() {
        Log.e(TAG, "initializeLocationManager");
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        }
    }
}

How to change the Eclipse default workspace?

In Eclipse, go to File -> Switch Workspace, choose or create a new workspace.

Create session factory in Hibernate 4

Yes, they have deprecated the previous buildSessionFactory API, and it's quite easy to do well.. you can do something like this..

EDIT : ServiceRegistryBuilder is deprecated. you must use StandardServiceRegistryBuilder

public void testConnection() throws Exception {

            logger.info("Trying to create a test connection with the database.");
            Configuration configuration = new Configuration();
            configuration.configure("hibernate_sp.cfg.xml");
            StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
            SessionFactory sessionFactory = configuration.buildSessionFactory(ssrb.build());
            Session session = sessionFactory.openSession();
            logger.info("Test connection with the database created successfuly.");
    }

For more reference and in depth detail, you can check the hibernate's official test case at https://github.com/hibernate/hibernate-orm/blob/master/hibernate-testing/src/main/java/org/hibernate/testing/junit4/BaseCoreFunctionalTestCase.java function (buildSessionFactory()).

Convert integer into byte array (Java)

You can use BigInteger:

From Integers:

byte[] array = BigInteger.valueOf(0xAABBCCDD).toByteArray();
System.out.println(Arrays.toString(array))
// --> {-86, -69, -52, -35 }

The returned array is of the size that is needed to represent the number, so it could be of size 1, to represent 1 for example. However, the size cannot be more than four bytes if an int is passed.

From Strings:

BigInteger v = new BigInteger("AABBCCDD", 16);
byte[] array = v.toByteArray();

However, you will need to watch out, if the first byte is higher 0x7F (as is in this case), where BigInteger would insert a 0x00 byte to the beginning of the array. This is needed to distinguish between positive and negative values.

How to uninstall downloaded Xcode simulator?

NOTE: This will only remove a device configuration from the Xcode devices list. To remove the simulator files from your hard drive see the previous answer.

For Xcode 7 just use Window \ Devices menu in Xcode:

Devices menu

Then select emulator to delete in the list on the left side and right click on it. Here is Delete option: enter image description here

That's all.

Saving a high resolution image in R

You can do the following. Add your ggplot code after the first line of code and end with dev.off().

tiff("test.tiff", units="in", width=5, height=5, res=300)
# insert ggplot code
dev.off()

res=300 specifies that you need a figure with a resolution of 300 dpi. The figure file named 'test.tiff' is saved in your working directory.

Change width and height in the code above depending on the desired output.

Note that this also works for other R plots including plot, image, and pheatmap.

Other file formats

In addition to TIFF, you can easily use other image file formats including JPEG, BMP, and PNG. Some of these formats require less memory for saving.

Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

This happens where a column is explicitly set to a different collation or the default collation is different in the table queried.

if you have many tables you want to change collation on run this query:

select concat('ALTER TABLE ', t.table_name , ' CONVERT TO CHARACTER 
SET utf8 COLLATE utf8_unicode_ci;') from (SELECT table_name FROM 
information_schema.tables where table_schema='SCHRMA') t;

this will output the queries needed to convert all the tables to use the correct collation per column

How to connect TFS in Visual Studio code

It seems that the extension cannot be found anymore using "Visual Studio Team Services". Instead, by following the link in Using Visual Studio Code & Team Foundation Version Control on "Get the TFVC plugin working in Visual Studio Code" you get to the Azure Repos Extension for Visual Studio Code GitHub. There it is explained that you now have to look for "Team Azure Repos".

Also, please note, that with the new Settings editor in Visual Studio Code the additional slashes do not have to be added. The path to tf.exe for VS 2017 - if specified using the "user friendly" Settings editor - would be just

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe

What is the difference between Scala's case class and class?

A case class is a class that may be used with the match/case statement.

def isIdentityFun(term: Term): Boolean = term match {
  case Fun(x, Var(y)) if x == y => true
  case _ => false
}

You see that case is followed by an instance of class Fun whose 2nd parameter is a Var. This is a very nice and powerful syntax, but it cannot work with instances of any class, therefore there are some restrictions for case classes. And if these restrictions are obeyed, it is possible to automatically define hashcode and equals.

The vague phrase "a recursive decomposition mechanism via pattern matching" means just "it works with case". (Indeed, the instance followed by match is compared to (matched against) the instance that follows case, Scala has to decompose them both, and has to recursively decompose what they are made of.)

What case classes are useful for? The Wikipedia article about Algebraic Data Types gives two good classical examples, lists and trees. Support for algebraic data types (including knowing how to compare them) is a must for any modern functional language.

What case classes are not useful for? Some objects have state, the code like connection.setConnectTimeout(connectTimeout) is not for case classes.

And now you can read A Tour of Scala: Case Classes

How to actually search all files in Visual Studio

So the answer seems to be to NOT use the Solution Explorer search box.

Rather, open any file in the solution, then use the control-f search pop-up to search all files by:

  1. selecting "Find All" from the "--> Find Next / <-- Find Previous" selector
  2. selecting "Current Project" or "Entire Solution" from the selector that normally says just "Current Document".

How to combine two or more querysets in a Django view?

In case you want to chain a lot of querysets, try this:

from itertools import chain
result = list(chain(*docs))

where: docs is a list of querysets

Compare DATETIME and DATE ignoring time portion

For Compare two date like MM/DD/YYYY to MM/DD/YYYY . Remember First thing column type of Field must be dateTime. Example : columnName : payment_date dataType : DateTime .

after that you can easily compare it. Query is :

select  *  from demo_date where date >= '3/1/2015' and date <=  '3/31/2015'.

It very simple ...... It tested it.....

SQL comment header examples

The header that we currently use looks like this:

---------------------------------------------------
-- Produced By   : Our company  
-- URL       : www.company.com  
-- Author        : me   
-- Date      : yesterday    
-- Purpose       : to do something  
-- Called by     : some other process   
-- Modifications : some other guy - today - to fix my bug   
------------------------------------------------------------

On a side note, any comments that I place within the SQL i always use the format:

/* Comment */

As in the past I had problems where scripting (by SQL Server) does funny things wrapping lines round and comments starting -- have commented out required SQL.... but that might just be me.

Is there a way to view past mysql queries with phpmyadmin?

You have to click on query window just below the phpMyAdmin logo, a new window will open. Just click on SQL History tab. There you can see history of SQL Queries.

How to modify PATH for Homebrew?

open your /etc/paths file, put /usr/local/bin on top of /usr/bin

$ sudo vi /etc/paths
/usr/local/bin
/usr/local/sbin
/usr/bin
/bin
/usr/sbin
/sbin

and Restart the terminal, @mmel

How to store custom objects in NSUserDefaults

Taking @chrissr's answer and running with it, this code can be implemented into a nice category on NSUserDefaults to save and retrieve custom objects:

@interface NSUserDefaults (NSUserDefaultsExtensions)

- (void)saveCustomObject:(id<NSCoding>)object
                     key:(NSString *)key;
- (id<NSCoding>)loadCustomObjectWithKey:(NSString *)key;

@end


@implementation NSUserDefaults (NSUserDefaultsExtensions)


- (void)saveCustomObject:(id<NSCoding>)object
                     key:(NSString *)key {
    NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
    [self setObject:encodedObject forKey:key];
    [self synchronize];

}

- (id<NSCoding>)loadCustomObjectWithKey:(NSString *)key {
    NSData *encodedObject = [self objectForKey:key];
    id<NSCoding> object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
    return object;
}

@end

Usage:

[[NSUserDefaults standardUserDefaults] saveCustomObject:myObject key:@"myKey"];

remove script tag from HTML content

A simple way by manipulating string.

$str = stripStr($str, '<script', '</script>');

function stripStr($str, $ini, $fin)
{
    while(($pos = mb_stripos($str, $ini)) !== false)
    {
        $aux = mb_substr($str, $pos + mb_strlen($ini));
        $str = mb_substr($str, 0, $pos).mb_substr($aux, mb_stripos($aux, $fin) + mb_strlen($fin));
    }

    return $str;
}

What's the difference between OpenID and OAuth?

I am currently working on OAuth 2.0 and OpenID connect spec. So here is my understanding: Earlier they were:

  1. OpenID was proprietary implementation of Google allowing third party applications like for newspaper websites you can login using google and comment on an article and so on other usecases. So essentially, no password sharing to newspaper website. Let me put up a definition here, this approach in enterprise approach is called Federation. In Federation, You have a server where you authenticate and authorize (called IDP, Identity Provider) and generally the keeper of User credentials. the client application where you have business is called SP or Service Provider. If we go back to same newspaper website example then newspaper website is SP here and Google is IDP. In enterprise this problem was earlier solved using SAML. that time XML used to rule the software industry. So from webservices to configuration, everything used to go to XML so we have SAML, a complete Federation protocol
  2. OAuth: OAuth saw it's emergence as an standard looking at all these kind of proprietary approaches and so we had OAuth 1.o as standard but addressing only authorization. Not many people noticed but it kind of started picking up. Then we had OAuth 2.0 in 2012. CTOs, Architects really started paying attention as world is moving towards Cloud computing and with computing devices moving towards mobile and other such devices. OAuth kind of looked upon as solving major problem where software customers might give IDP Service to one company and have many services from different vendors like salesforce, SAP, etc. So integration here really looks like federation scenario bit one big problem, using SAML is costly so let's explore OAuth 2.o. Ohh, missed one important point that during this time, Google sensed that OAuth actually doesn't address Authentication, how will IDP give user data to SP (which is actually wonderfully addressed in SAML) and with other loose ends like:

    a. OAuth 2.o doesn't clearly say, how client registration will happen b. it doesn't mention anything about the interaction between SP (Resource Server) and client application (like Analytics Server providing data is Resource Server and application displaying that data is Client)

There are already wonderful answers given here technically, I thought of giving of giving brief evolution perspective

MySQL CONCAT returns NULL if any field contain NULL

SELECT CONCAT(isnull(`affiliate_name`,''),'-',isnull(`model`,''),'-',isnull(`ip`,''),'-',isnull(`os_type`,''),'-',isnull(`os_version`,'')) AS device_name
FROM devices

How to detect browser using angularjs?

So, you can declare more utilities for angular by create file with content (I follow RGraph Library)

(function(window, angular, undefined) {'use strict';
    var agl = angular || {};
    var ua  = navigator.userAgent;

    agl.ISFF     = ua.indexOf('Firefox') != -1;
    agl.ISOPERA  = ua.indexOf('Opera') != -1;
    agl.ISCHROME = ua.indexOf('Chrome') != -1;
    agl.ISSAFARI = ua.indexOf('Safari') != -1 && !agl.ISCHROME;
    agl.ISWEBKIT = ua.indexOf('WebKit') != -1;

    agl.ISIE   = ua.indexOf('Trident') > 0 || navigator.userAgent.indexOf('MSIE') > 0;
    agl.ISIE6  = ua.indexOf('MSIE 6') > 0;
    agl.ISIE7  = ua.indexOf('MSIE 7') > 0;
    agl.ISIE8  = ua.indexOf('MSIE 8') > 0;
    agl.ISIE9  = ua.indexOf('MSIE 9') > 0;
    agl.ISIE10 = ua.indexOf('MSIE 10') > 0;
    agl.ISOLD  = agl.ISIE6 || agl.ISIE7 || agl.ISIE8; // MUST be here

    agl.ISIE11UP = ua.indexOf('MSIE') == -1 && ua.indexOf('Trident') > 0;
    agl.ISIE10UP = agl.ISIE10 || agl.ISIE11UP;
    agl.ISIE9UP  = agl.ISIE9 || agl.ISIE10UP;

})(window, window.angular);

after that, in your function use can use it like

function SampleController($scope){
    $scope.click = function () {
        if(angular.ISCHROME) {
        alert("is chrome");
    }
}

Get form data in ReactJS

An easy way to deal with refs:

_x000D_
_x000D_
class UserInfo extends React.Component {_x000D_
_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
    this.handleSubmit = this.handleSubmit.bind(this);_x000D_
  }_x000D_
_x000D_
  handleSubmit(e) {_x000D_
    e.preventDefault();_x000D_
    _x000D_
    const formData = {};_x000D_
    for (const field in this.refs) {_x000D_
      formData[field] = this.refs[field].value;_x000D_
    }_x000D_
    console.log('-->', formData);_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
        <div>_x000D_
          <form onSubmit={this.handleSubmit}>_x000D_
            <input ref="phone" className="phone" type='tel' name="phone"/>_x000D_
            <input ref="email" className="email" type='tel' name="email"/>_x000D_
            <input type="submit" value="Submit"/>_x000D_
          </form>_x000D_
        </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
export default UserInfo;
_x000D_
_x000D_
_x000D_

laravel 5.3 new Auth::routes()

If you are searching these same routes for laravel 7 version you'll find it here Vendor/laravel/ui/src/AuthRouteMethods.php

is there a 'block until condition becomes true' function in java?

Polling like this is definitely the least preferred solution.

I assume that you have another thread that will do something to make the condition true. There are several ways to synchronize threads. The easiest one in your case would be a notification via an Object:

Main thread:

synchronized(syncObject) {
    try {
        // Calling wait() will block this thread until another thread
        // calls notify() on the object.
        syncObject.wait();
    } catch (InterruptedException e) {
        // Happens if someone interrupts your thread.
    }
}

Other thread:

// Do something
// If the condition is true, do the following:
synchronized(syncObject) {
    syncObject.notify();
}

syncObject itself can be a simple Object.

There are many other ways of inter-thread communication, but which one to use depends on what precisely you're doing.

OpenMP set_num_threads() is not working

Besides calling omp_get_num_threads() outside of the parallel region in your case, calling omp_set_num_threads() still doesn't guarantee that the OpenMP runtime will use exactly the specified number of threads. omp_set_num_threads() is used to override the value of the environment variable OMP_NUM_THREADS and they both control the upper limit of the size of the thread team that OpenMP would spawn for all parallel regions (in the case of OMP_NUM_THREADS) or for any consequent parallel region (after a call to omp_set_num_threads()). There is something called dynamic teams that could still pick smaller number of threads if the run-time system deems it more appropriate. You can disable dynamic teams by calling omp_set_dynamic(0) or by setting the environment variable OMP_DYNAMIC to false.

To enforce a given number of threads you should disable dynamic teams and specify the desired number of threads with either omp_set_num_threads():

omp_set_dynamic(0);     // Explicitly disable dynamic teams
omp_set_num_threads(4); // Use 4 threads for all consecutive parallel regions
#pragma omp parallel ...
{
    ... 4 threads used here ...
}

or with the num_threads OpenMP clause:

omp_set_dynamic(0);     // Explicitly disable dynamic teams
// Spawn 4 threads for this parallel region only
#pragma omp parallel ... num_threads(4)
{
    ... 4 threads used here ...
}

Swift Beta performance: sorting arrays

I decided to take a look at this for fun, and here are the timings that I get:

Swift 4.0.2           :   0.83s (0.74s with `-Ounchecked`)
C++ (Apple LLVM 8.0.0):   0.74s

Swift

// Swift 4.0 code
import Foundation

func doTest() -> Void {
    let arraySize = 10000000
    var randomNumbers = [UInt32]()

    for _ in 0..<arraySize {
        randomNumbers.append(arc4random_uniform(UInt32(arraySize)))
    }

    let start = Date()
    randomNumbers.sort()
    let end = Date()

    print(randomNumbers[0])
    print("Elapsed time: \(end.timeIntervalSince(start))")
}

doTest()

Results:

Swift 1.1

xcrun swiftc --version
Swift version 1.1 (swift-600.0.54.20)
Target: x86_64-apple-darwin14.0.0

xcrun swiftc -O SwiftSort.swift
./SwiftSort     
Elapsed time: 1.02204304933548

Swift 1.2

xcrun swiftc --version
Apple Swift version 1.2 (swiftlang-602.0.49.6 clang-602.0.49)
Target: x86_64-apple-darwin14.3.0

xcrun -sdk macosx swiftc -O SwiftSort.swift
./SwiftSort     
Elapsed time: 0.738763988018036

Swift 2.0

xcrun swiftc --version
Apple Swift version 2.0 (swiftlang-700.0.59 clang-700.0.72)
Target: x86_64-apple-darwin15.0.0

xcrun -sdk macosx swiftc -O SwiftSort.swift
./SwiftSort     
Elapsed time: 0.767306983470917

It seems to be the same performance if I compile with -Ounchecked.

Swift 3.0

xcrun swiftc --version
Apple Swift version 3.0 (swiftlang-800.0.46.2 clang-800.0.38)
Target: x86_64-apple-macosx10.9

xcrun -sdk macosx swiftc -O SwiftSort.swift
./SwiftSort     
Elapsed time: 0.939633965492249

xcrun -sdk macosx swiftc -Ounchecked SwiftSort.swift
./SwiftSort     
Elapsed time: 0.866258025169373

There seems to have been a performance regression from Swift 2.0 to Swift 3.0, and I'm also seeing a difference between -O and -Ounchecked for the first time.

Swift 4.0

xcrun swiftc --version
Apple Swift version 4.0.2 (swiftlang-900.0.69.2 clang-900.0.38)
Target: x86_64-apple-macosx10.9

xcrun -sdk macosx swiftc -O SwiftSort.swift
./SwiftSort     
Elapsed time: 0.834299981594086

xcrun -sdk macosx swiftc -Ounchecked SwiftSort.swift
./SwiftSort     
Elapsed time: 0.742045998573303

Swift 4 improves the performance again, while maintaining a gap between -O and -Ounchecked. -O -whole-module-optimization did not appear to make a difference.

C++

#include <chrono>
#include <iostream>
#include <vector>
#include <cstdint>
#include <stdlib.h>

using namespace std;
using namespace std::chrono;

int main(int argc, const char * argv[]) {
    const auto arraySize = 10000000;
    vector<uint32_t> randomNumbers;

    for (int i = 0; i < arraySize; ++i) {
        randomNumbers.emplace_back(arc4random_uniform(arraySize));
    }

    const auto start = high_resolution_clock::now();
    sort(begin(randomNumbers), end(randomNumbers));
    const auto end = high_resolution_clock::now();

    cout << randomNumbers[0] << "\n";
    cout << "Elapsed time: " << duration_cast<duration<double>>(end - start).count() << "\n";

    return 0;
}

Results:

Apple Clang 6.0

clang++ --version
Apple LLVM version 6.0 (clang-600.0.54) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin14.0.0
Thread model: posix

clang++ -O3 -std=c++11 CppSort.cpp -o CppSort
./CppSort     
Elapsed time: 0.688969

Apple Clang 6.1.0

clang++ --version
Apple LLVM version 6.1.0 (clang-602.0.49) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.3.0
Thread model: posix

clang++ -O3 -std=c++11 CppSort.cpp -o CppSort
./CppSort     
Elapsed time: 0.670652

Apple Clang 7.0.0

clang++ --version
Apple LLVM version 7.0.0 (clang-700.0.72)
Target: x86_64-apple-darwin15.0.0
Thread model: posix

clang++ -O3 -std=c++11 CppSort.cpp -o CppSort
./CppSort     
Elapsed time: 0.690152

Apple Clang 8.0.0

clang++ --version
Apple LLVM version 8.0.0 (clang-800.0.38)
Target: x86_64-apple-darwin15.6.0
Thread model: posix

clang++ -O3 -std=c++11 CppSort.cpp -o CppSort
./CppSort     
Elapsed time: 0.68253

Apple Clang 9.0.0

clang++ --version
Apple LLVM version 9.0.0 (clang-900.0.38)
Target: x86_64-apple-darwin16.7.0
Thread model: posix

clang++ -O3 -std=c++11 CppSort.cpp -o CppSort
./CppSort     
Elapsed time: 0.736784

Verdict

As of the time of this writing, Swift's sort is fast, but not yet as fast as C++'s sort when compiled with -O, with the above compilers & libraries. With -Ounchecked, it appears to be as fast as C++ in Swift 4.0.2 and Apple LLVM 9.0.0.

Could not open input file: artisan

What did the trick for me was to do cd src from my project directoy, and then use the php artisan command, since my artisan file was in the src folder. Here is my project structure:

project
|__ config
|__ src
    |__ app
    |__ ..
    |__ artisan  // hello there!
    |__ ...
|__ ...

How to add results of two select commands in same query

Yes. It is possible :D

SELECT  SUM(totalHours) totalHours
FROM
        ( 
            select sum(hours) totalHours from resource
            UNION ALL
            select sum(hours) totalHours from projects-time
        ) s

As a sidenote, the tablename projects-time must be delimited to avoid syntax error. Delimiter symbols vary on RDBMS you are using.

android listview get selected item

final ListView lv = (ListView) findViewById(R.id.ListView01);

lv.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
        String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));

      }                 
});

I hope this fixes your problem.

how to modify the size of a column

If you run it, it will work, but in order for SQL Developer to recognize and not warn about a possible error you can change it as:

ALTER TABLE TEST_PROJECT2 MODIFY (proj_name VARCHAR2(300));

What does "pending" mean for request in Chrome Developer Window?

I had some problems with pending request for mp3 files. I had a list of mp3 files and one player to play them. If I picked a file that had already been downloaded, Chrome would block the request and show "pending request" in the network tab of the developer tools.

All versions of Chrome seem to be affected.

Here is a solution I found:

player[0].setAttribute('src','video.webm?dummy=' + Date.now());

You just add a dummy query string to the end of each url. This forces Chrome to download the file again.

Another example with popcorn player (using jquery) :

url = $(this).find('.url_song').attr('url');
pop = Popcorn.smart( "#player_",  url + '?i=' + Date.now());

This works for me. In fact, the resource is not stored in the cache system. This should also work in the same way for .csv files.

How to format a date using ng-model?

I prefer to have the server return the date without modification, and have javascript do the view massaging. My API returns "MM/DD/YYYY hh:mm:ss" from SQL Server.

Resource

angular.module('myApp').factory('myResource',
    function($resource) {
        return $resource('api/myRestEndpoint/', null,
        {
            'GET': { method: 'GET' },
            'QUERY': { method: 'GET', isArray: true },
            'POST': { method: 'POST' },
            'PUT': { method: 'PUT' },
            'DELETE': { method: 'DELETE' }
        });
    }
);

Controller

var getHttpJson = function () {
    return myResource.GET().$promise.then(
        function (response) {

            if (response.myDateExample) {
                response.myDateExample = $filter('date')(new Date(response.myDateExample), 'M/d/yyyy');
            };

            $scope.myModel= response;
        },
        function (response) {
            console.log(response.data);
        }
    );
};

myDate Validation Directive

angular.module('myApp').directive('myDate',
    function($window) {
        return {
            require: 'ngModel',
            link: function(scope, element, attrs, ngModel) {

                var moment = $window.moment;

                var acceptableFormats = ['M/D/YYYY', 'M-D-YYYY'];

                function isDate(value) {

                    var m = moment(value, acceptableFormats, true);

                    var isValid = m.isValid();

                    //console.log(value);
                    //console.log(isValid);

                    return isValid;

                };

                ngModel.$parsers.push(function(value) {

                    if (!value || value.length === 0) {
                         return value;
                    };

                    if (isDate(value)) {
                        ngModel.$setValidity('myDate', true);
                    } else {
                        ngModel.$setValidity('myDate', false);
                    }

                    return value;

                });

            }
        }
    }
);

HTML

<div class="form-group">
    <label for="myDateExample">My Date Example</label>
    <input id="myDateExample"
           name="myDateExample"
           class="form-control"
           required=""
           my-date
           maxlength="50"
           ng-model="myModel.myDateExample"
           type="text" />
    <div ng-messages="myForm.myDateExample.$error" ng-if="myForm.$submitted || myForm.myDateExample.$touched" class="errors">
        <div ng-messages-include="template/validation/messages.html"></div>
    </div>
</div>

template/validation/messages.html

<div ng-message="required">Required Field</div>
<div ng-message="number">Must be a number</div>
<div ng-message="email">Must be a valid email address</div>
<div ng-message="minlength">The data entered is too short</div>
<div ng-message="maxlength">The data entered is too long</div>
<div ng-message="myDate">Must be a valid date</div>

Fill remaining vertical space with CSS using display:flex

A more modern approach would be to use the grid property.

_x000D_
_x000D_
section {_x000D_
  display: grid;_x000D_
  align-items: stretch;_x000D_
  height: 300px;_x000D_
  grid-template-rows: min-content auto 60px;_x000D_
}_x000D_
header {_x000D_
  background: tomato;_x000D_
}_x000D_
div {_x000D_
  background: gold;_x000D_
  overflow: auto;_x000D_
}_x000D_
footer {_x000D_
  background: lightgreen;_x000D_
}
_x000D_
<section>_x000D_
  <header>_x000D_
    header: sized to content_x000D_
    <br>(but is it really?)_x000D_
  </header>_x000D_
  <div>_x000D_
    main content: fills remaining space<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    _x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    _x000D_
  </div>_x000D_
  <footer>_x000D_
    footer: fixed height in px_x000D_
  </footer>_x000D_
</section>
_x000D_
_x000D_
_x000D_

CSS /JS to prevent dragging of ghost image?

You can use "Empty Img Element".
Empty Img Element - document.createElement("img")

[HTML Code]
<div id="hello" draggable="true">Drag!!!</div>
[JavaScript Code]
var block = document.querySelector('#hello');
block.addEventListener('dragstart', function(e){
    var img = document.createElement("img");
    e.dataTransfer.setDragImage(img, 0, 0);
})

Eclipse 3.5 Unable to install plugins

I had a similar problem setting up eclipse in the office. I had set up the for HTTP, HTTPS and SOCKS in:

Window>pref>general>network connections

Clearing the proxy settings for SOCKS fixed the problem for me.

How to ping a server only once from within a batch file?

Just write the command "ping your server IP" without the double quote. save file name as filename.bat and then run the batch file as administrator

How to get first N elements of a list in C#?

var firstFiveItems = myList.Take(5);

Or to slice:

var secondFiveItems = myList.Skip(5).Take(5);

And of course often it's convenient to get the first five items according to some kind of order:

var firstFiveArrivals = myList.OrderBy(i => i.ArrivalTime).Take(5);

How can I simulate mobile devices and debug in Firefox Browser?

Most web applications detects mobile devices based on the HTTP Headers.

If your web site also uses HTTP Headers to identify mobile device, you can do the following:

  1. Add Modify Headers plug in to your Firefox browser ( https://addons.mozilla.org/en-US/firefox/addon/modify-headers/ )
  2. Using plugin modify headers:
    • select Headers tab-> select Action 'ADD'
    • to simulate e.g. iPhone add a header with name User-Agent and value: Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543 Safari/419.3
    • click 'Add' button
  3. After that you should be able to see mobile version of you web application in Firefox and use Firebug plugin.

Hope it helps!

How do I get the current username in .NET using C#?

I totally second the other answers, but I would like to highlight one more method which says

String UserName = Request.LogonUserIdentity.Name;

The above method returned me the username in the format: DomainName\UserName. For example, EUROPE\UserName

Which is different from:

String UserName = Environment.UserName;

Which displayed in the format: UserName

And finally:

String UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

which gave: NT AUTHORITY\IUSR (while running the application on IIS server) and DomainName\UserName (while running the application on a local server).

How to verify CuDNN installation?

Installing CuDNN just involves placing the files in the CUDA directory. If you have specified the routes and the CuDNN option correctly while installing caffe it will be compiled with CuDNN.

You can check that using cmake. Create a directory caffe/build and run cmake .. from there. If the configuration is correct you will see these lines:

-- Found cuDNN (include: /usr/local/cuda-7.0/include, library: /usr/local/cuda-7.0/lib64/libcudnn.so)

-- NVIDIA CUDA:
--   Target GPU(s)     :   Auto
--   GPU arch(s)       :   sm_30
--   cuDNN             :   Yes

If everything is correct just run the make orders to install caffe from there.

How to change value of process.env.PORT in node.js?

EDIT: Per @sshow's comment, if you're trying to run your node app on port 80, the below is not the best way to do it. Here's a better answer: How do I run Node.js on port 80?

Original Answer:

If you want to do this to run on port 80 (or want to set the env variable more permanently),

  1. Open up your bash profile vim ~/.bash_profile
  2. Add the environment variable to the file export PORT=80
  3. Open up the sudoers config file sudo visudo
  4. Add the following line to the file exactly as so Defaults env_keep +="PORT"

Now when you run sudo node app.js it should work as desired.

What is bootstrapping?

In the context of application development, "bootstrapping" usually comes up when talking about modular and/or auto-updatable software.

Rather than the user downloading the entire app, including features he does not need, and re-downloading and manually updating it whenever there is an update, the user only downloads and starts a small "bootstrap" executable, which in turn downloads and installs those parts of the application that the user needs. Additionally, the bootstrap component is able to look for updates and install them each time it is started.

Javascript getElementsByName.value not working

Here is the example for having one or more checkboxes value. If you have two or more checkboxes and need values then this would really help.

_x000D_
_x000D_
function myFunction() {_x000D_
  var selchbox = [];_x000D_
  var inputfields = document.getElementsByName("myCheck");_x000D_
  var ar_inputflds = inputfields.length;_x000D_
_x000D_
  for (var i = 0; i < ar_inputflds; i++) {_x000D_
    if (inputfields[i].type == 'checkbox' && inputfields[i].checked == true)_x000D_
      selchbox.push(inputfields[i].value);_x000D_
  }_x000D_
  return selchbox;_x000D_
_x000D_
}_x000D_
_x000D_
document.getElementById('btntest').onclick = function() {_x000D_
  var selchb = myFunction();_x000D_
  console.log(selchb);_x000D_
}
_x000D_
Checkbox:_x000D_
<input type="checkbox" name="myCheck" value="UK">United Kingdom_x000D_
<input type="checkbox" name="myCheck" value="USA">United States_x000D_
<input type="checkbox" name="myCheck" value="IL">Illinois_x000D_
<input type="checkbox" name="myCheck" value="MA">Massachusetts_x000D_
<input type="checkbox" name="myCheck" value="UT">Utah_x000D_
_x000D_
<input type="button" value="Click" id="btntest" />
_x000D_
_x000D_
_x000D_

Lazy Method for Reading Big File in Python?

I think we can write like this:

def read_file(path, block_size=1024): 
    with open(path, 'rb') as f: 
        while True: 
            piece = f.read(block_size) 
            if piece: 
                yield piece 
            else: 
                return

for piece in read_file(path):
    process_piece(piece)

SQL (MySQL) vs NoSQL (CouchDB)

Here's a quote from a recent blog post from Dare Obasanjo.

SQL databases are like automatic transmission and NoSQL databases are like manual transmission. Once you switch to NoSQL, you become responsible for a lot of work that the system takes care of automatically in a relational database system. Similar to what happens when you pick manual over automatic transmission. Secondly, NoSQL allows you to eke more performance out of the system by eliminating a lot of integrity checks done by relational databases from the database tier. Again, this is similar to how you can get more performance out of your car by driving a manual transmission versus an automatic transmission vehicle.

However the most notable similarity is that just like most of us can’t really take advantage of the benefits of a manual transmission vehicle because the majority of our driving is sitting in traffic on the way to and from work, there is a similar harsh reality in that most sites aren’t at Google or Facebook’s scale and thus have no need for a Bigtable or Cassandra.

To which I can add only that switching from MySQL, where you have at least some experience, to CouchDB, where you have no experience, means you will have to deal with a whole new set of problems and learn different concepts and best practices. While by itself this is wonderful (I am playing at home with MongoDB and like it a lot), it will be a cost that you need to calculate when estimating the work for that project, and brings unknown risks while promising unknown benefits. It will be very hard to judge if you can do the project on time and with the quality you want/need to be successful, if it's based on a technology you don't know.

Now, if you have on the team an expert in the NoSQL field, then by all means take a good look at it. But without any expertise on the team, don't jump on NoSQL for a new commercial project.

Update: Just to throw some gasoline in the open fire you started, here are two interesting articles from people on the SQL camp. :-)

I Can't Wait for NoSQL to Die (original article is gone, here's a copy)
Fighting The NoSQL Mindset, Though This Isn't an anti-NoSQL Piece
Update: Well here is an interesting article about NoSQL
Making Sense of NoSQL

Turn off display errors using file "php.ini"

In php.ini, comment out:

error_reporting = E_ALL & ~E_NOTICE
error_reporting = E_ALL & ~E_NOTICE | E_STRICT
error_reporting = E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ER… _ERROR
error_reporting = E_ALL & ~E_NOTICE

By placing a ; ahead of it (i.e., like ;error_reporting = E_ALL & ~E_NOTICE)

For disabling in a single file, place error_reporting(0); after opening a php tag.

How to combine paths in Java?

In Java 7, you should use resolve:

Path newPath = path.resolve(childPath);

While the NIO2 Path class may seem a bit redundant to File with an unnecessarily different API, it is in fact subtly more elegant and robust.

Note that Paths.get() (as suggested by someone else) doesn't have an overload taking a Path, and doing Paths.get(path.toString(), childPath) is NOT the same thing as resolve(). From the Paths.get() docs:

Note that while this method is very convenient, using it will imply an assumed reference to the default FileSystem and limit the utility of the calling code. Hence it should not be used in library code intended for flexible reuse. A more flexible alternative is to use an existing Path instance as an anchor, such as:

Path dir = ...
Path path = dir.resolve("file");

The sister function to resolve is the excellent relativize:

Path childPath = path.relativize(newPath);

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

Calculate distance in meters when you know longitude and latitude in java

Based on another question on stackoverflow, I got this code.. This calculates the result in meters, not in miles :)

 public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
    double earthRadius = 6371000; //meters
    double dLat = Math.toRadians(lat2-lat1);
    double dLng = Math.toRadians(lng2-lng1);
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
               Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
               Math.sin(dLng/2) * Math.sin(dLng/2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    float dist = (float) (earthRadius * c);

    return dist;
    }

Read a text file in R line by line

Here is the solution with a for loop. Importantly, it takes the one call to readLines out of the for loop so that it is not improperly called again and again. Here it is:

fileName <- "up_down.txt"
conn <- file(fileName,open="r")
linn <-readLines(conn)
for (i in 1:length(linn)){
   print(linn[i])
}
close(conn)

getting the screen density programmatically in android?

Actualy if you want to have the real display dpi the answer is somewhere in between if you query for display metrics:

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int dpiClassification = dm.densityDpi;
float xDpi = dm.xdpi;
float yDpi = dm.ydpi;

densityDpi * 160 will give you the values/suggestion which density you should use

0.75 - ldpi - 120 dpi
1.0 - mdpi - 160 dpi
1.5 - hdpi - 240 dpi
2.0 - xhdpi - 320 dpi
3.0 - xxhdpi - 480 dpi
4.0 - xxxhdpi - 640 dpi

as specified in previous posts

but dm.xdpi won't give you always the REAL dpi of given display: Example:

Device: Sony ericsson xperia mini pro (SK17i)
Density: 1.0 (e.g. suggests you use 160dpi resources)
xdpi: 193.5238
Real device ppi is arround 193ppi


Device: samsung GT-I8160 (Samsung ace 2)
Density 1.5 (e.g. suggests you use 240dpi resources)
xdpi 160.42105
Real device ppi is arround 246ppi

so maybe real dpi of the display should be Density*xdpi .. but i'm not sure if this is the correct way to do!

How to add line break for UILabel?

On Xcode 6, you can just use \n even inside a string when using word wrap. It will work. So for example:

UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, screenRect.size.width, 50)];
label.textAlignment = NSTextAlignmentCenter;
label.text = @"This will be on the first line\nfollowed by a line under it.";
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;

ssh_exchange_identification: Connection closed by remote host under Git bash

You can get "ssh_exchange_identification: Connection closed by remote host" if your sshd service is not operational!

If you have access to the server check you have the sshd service running with:

  ps aux | grep ssh

and check it is listening on port 22:

 netstat -plant | grep :22

more details here

Display a view from another controller in ASP.NET MVC

With this code you can obtain any controller:

var controller = DependencyResolver.Current.GetService<ControllerB>();
controller.ControllerContext = new ControllerContext(this.Request.RequestContext, 
controller);

How to create multiple class objects with a loop in python?

This question is asked every day in some variation. The answer is: keep your data out of your variable names, and this is the obligatory blog post.

In this case, why not make a list of objs?

objs = [MyClass() for i in range(10)]
for obj in objs:
    other_object.add(obj)

objs[0].do_sth()

How to prevent scrollbar from repositioning web page?

If changing size or after loading some data it is adding the scroll bar then you can try following, create class and apply this class.

.auto-scroll {
   overflow-y: overlay;
   overflow-x: overlay;
}

How do I get the SelectedItem or SelectedIndex of ListView in vb.net?

VB6: Listview1.selecteditem

VB10: Listview1.FocusedItem.Text

'Class' does not contain a definition for 'Method'

I had the same problem, "Rebuild Solution" and then "Clean Solution" didn't work.I solved that by checking my DLL references.

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

IIS7 defines a defaultDocument section in its configuration files which can be found in the %WinDir%\System32\InetSrv\Config folder. Most likely, the file index.aspx is already defined as a default document in one of IIS7's configuration files and you are adding it again in your web.config.

I suspect that removing the line <add value="index.aspx" />

from the defaultDocument/files section will fix your issue.

The defaultDocument section of your config will look like:

<defaultDocument>
  <files>
    <remove value="default.aspx" />
    <remove value="index.html" />
    <remove value="iisstart.htm" />
    <remove value="index.htm" />
    <remove value="Default.asp" />
    <remove value="Default.htm" />
  </files>
</defaultDocument>

Note that index.aspx will still appear in the list of default documents for your site in the IIS manager.

For more information about IIS7 configuration, click here.

What are forward declarations in C++?

One problem is, that the compiler does not know, which kind of value is delivered by your function; is assumes, that the function returns an int in this case, but this can be as correct as it can be wrong. Another problem is, that the compiler does not know, which kind of arguments your function expects, and cannot warn you, if you are passing values of the wrong kind. There are special "promotion" rules, which apply when passing, say floating point values to an undeclared function (the compiler has to widen them to type double), which is often not, what the function actually expects, leading to hard to find bugs at run-time.

How can I insert vertical blank space into an html document?

i always use this cheap word for vertical spaces.

    <p>Q1</p>
    <br>
    <p>Q2</p>

How do I loop through or enumerate a JavaScript object?

In ES6 we have well-known symbols to expose some previously internal methods, you can use it to define how iterators work for this object:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3",
    *[Symbol.iterator]() {
        yield *Object.keys(this);
    }
};

[...p] //["p1", "p2", "p3"]

this will give the same result as using for...in es6 loop.

for(var key in p) {
    console.log(key);
}

But its important to know the capabilities you now have using es6!

How do you convert Html to plain text?

Three Step Process for converting HTML into Plain Text

First You need to Install Nuget Package For HtmlAgilityPack Second Create This class

public class HtmlToText
{
    public HtmlToText()
    {
    }

    public string Convert(string path)
    {
        HtmlDocument doc = new HtmlDocument();
        doc.Load(path);

        StringWriter sw = new StringWriter();
        ConvertTo(doc.DocumentNode, sw);
        sw.Flush();
        return sw.ToString();
    }

    public string ConvertHtml(string html)
    {
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(html);

        StringWriter sw = new StringWriter();
        ConvertTo(doc.DocumentNode, sw);
        sw.Flush();
        return sw.ToString();
    }

    private void ConvertContentTo(HtmlNode node, TextWriter outText)
    {
        foreach(HtmlNode subnode in node.ChildNodes)
        {
            ConvertTo(subnode, outText);
        }
    }

    public void ConvertTo(HtmlNode node, TextWriter outText)
    {
        string html;
        switch(node.NodeType)
        {
            case HtmlNodeType.Comment:
                // don't output comments
                break;

            case HtmlNodeType.Document:
                ConvertContentTo(node, outText);
                break;

            case HtmlNodeType.Text:
                // script and style must not be output
                string parentName = node.ParentNode.Name;
                if ((parentName == "script") || (parentName == "style"))
                    break;

                // get text
                html = ((HtmlTextNode)node).Text;

                // is it in fact a special closing node output as text?
                if (HtmlNode.IsOverlappedClosingElement(html))
                    break;

                // check the text is meaningful and not a bunch of whitespaces
                if (html.Trim().Length > 0)
                {
                    outText.Write(HtmlEntity.DeEntitize(html));
                }
                break;

            case HtmlNodeType.Element:
                switch(node.Name)
                {
                    case "p":
                        // treat paragraphs as crlf
                        outText.Write("\r\n");
                        break;
                }

                if (node.HasChildNodes)
                {
                    ConvertContentTo(node, outText);
                }
                break;
        }
    }
}

By using above class with reference to Judah Himango's answer

Third you need to create the Object of above class and Use ConvertHtml(HTMLContent) Method for converting HTML into Plain Text rather than ConvertToPlainText(string html);

HtmlToText htt=new HtmlToText();
var plainText = htt.ConvertHtml(HTMLContent);

jQuery input button click event listener

$("#filter").click(function(){
    //Put your code here
});

Calling constructors in c++ without new

I played a bit with it and the syntax seems to get quite strange when a constructor takes no arguments. Let me give an example:

#include <iostream> 

using namespace std;

class Thing
{
public:
    Thing();
};

Thing::Thing()
{
    cout << "Hi" << endl;
}

int main()
{
    //Thing myThing(); // Does not work
    Thing myThing; // Works

}

so just writing Thing myThing w/o brackets actually calls the constructor, while Thing myThing() makes the compiler thing you want to create a function pointer or something ??!!

5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error

Started working after adding property:

mail.smtp.starttls.enable=true

Using:

mail.smtp.host=smtp.office365.com
mail.smtp.port=587
mail.transport.protocol=smtp
mail.smtp.auth=true
mail.smtp.starttls.enable=true
[email protected]
mail.smtp.password=xxx
[email protected]

What is "Connect Timeout" in sql server connection string?

Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error. (MSDN, SqlConnection.ConnectionTimeout Property, 2013)

Laravel 5 Failed opening required bootstrap/../vendor/autoload.php

We got an error because we have missing vendor folder in our project, The vendor directory contains our Composer dependencies.

Need /vendor folder because all packages are there and including all the classes Laravel uses, A problem can be solved after following just two steps:

composer update --no-scripts 
composer update
  • --no-scripts: Skips execution of scripts defined in composer.json
  • composer update: This will check for newer versions of the libraries you required in your project. If a newer version is found and it's compatible with the version constraint defined in the composer.json file, it will replace the previous version installed. The composer.lock file will be updated to reflect these changes.

These two commands, we will Recreate the vendor folder in our project and after that our project will be working smoothly.

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

It is known Chrome problem. According to Chrome and Chromium bug trackers there is no universal solution for this. This problem is not related with server type and version, it is right in Chrome.

Setting Content-Encoding header to identity solved this problem to me.

from developer.mozilla.org

identity | Indicates the identity function (i.e. no compression, nor modification).

So, I can suggest, that in some cases Chrome can not perform gzip compress correctly.

How to generate auto increment field in select query

DECLARE @id INT 
SET @id = 0 
UPDATE cartemp
SET @id = CarmasterID = @id + 1 
GO

How do I convert a single character into it's hex ascii value in python

This might help

import binascii

x = b'test'
x = binascii.hexlify(x)
y = str(x,'ascii')

print(x) # Outputs b'74657374' (hex encoding of "test")
print(y) # Outputs 74657374

x_unhexed = binascii.unhexlify(x)
print(x_unhexed) # Outputs b'test'

x_ascii = str(x_unhexed,'ascii')
print(x_ascii) # Outputs test

This code contains examples for converting ASCII characters to and from hexadecimal. In your situation, the line you'd want to use is str(binascii.hexlify(c),'ascii').

horizontal scrollbar on top and bottom of table

If you are using iscroll.js on webkit browser or mobile browser, you could try:

$('#pageWrapper>div:last-child').css('top', "0px");

How to use Tomcat 8 in Eclipse?

In addition to @Jason's answer I had to do a bit more to get my app to run.

Calculating text width

text width can be different for different parents, for example if u add a text into h1 tag it will be wider than div or label, so my solution like this:

<h1 id="header1">

</h1>

alert(calcTextWidth("bir iki", $("#header1")));

function calcTextWidth(text, parentElem){
    var Elem = $("<label></label>").css("display", "none").text(text);
    parentElem.append(Elem);
  var width = Elem.width();
  Elem.remove();
    return width;
}

Base64 PNG data to HTML5 canvas

Jerryf's answer is fine, except for one flaw.

The onload event should be set before the src. Sometimes the src can be loaded instantly and never fire the onload event.

(Like Totty.js pointed out.)

var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");

var image = new Image();
image.onload = function() {
    ctx.drawImage(image, 0, 0);
};
image.src = "data:image/  png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";

Good examples of python-memcache (memcached) being used in Python?

It's fairly simple. You write values using keys and expiry times. You get values using keys. You can expire keys from the system.

Most clients follow the same rules. You can read the generic instructions and best practices on the memcached homepage.

If you really want to dig into it, I'd look at the source. Here's the header comment:

"""
client module for memcached (memory cache daemon)

Overview
========

See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.

Usage summary
=============

This should give you a feel for how this module operates::

    import memcache
    mc = memcache.Client(['127.0.0.1:11211'], debug=0)

    mc.set("some_key", "Some value")
    value = mc.get("some_key")

    mc.set("another_key", 3)
    mc.delete("another_key")

    mc.set("key", "1")   # note that the key used for incr/decr must be a string.
    mc.incr("key")
    mc.decr("key")

The standard way to use memcache with a database is like this::

    key = derive_key(obj)
    obj = mc.get(key)
    if not obj:
        obj = backend_api.get(...)
        mc.set(key, obj)

    # we now have obj, and future passes through this code
    # will use the object from the cache.

Detailed Documentation
======================

More detailed documentation is available in the L{Client} class.
"""

PHP upload image

I would recommend you to save the image in the server, and then save the URL in MYSQL database.

First of all, you should do more validation on your image, before non-validated files can lead to huge security risks.

  1. Check the image

    if (empty($_FILES['image']))
      throw new Exception('Image file is missing');
    
  2. Save the image in a variable

    $image = $_FILES['image'];
    
  3. Check the upload time errors

    if ($image['error'] !== 0) {
       if ($image['error'] === 1) 
          throw new Exception('Max upload size exceeded');
    
       throw new Exception('Image uploading error: INI Error');
    }
    
  4. Check whether the uploaded file exists in the server

    if (!file_exists($image['tmp_name']))
        throw new Exception('Image file is missing in the server');
    
  5. Validate the file size (Change it according to your needs)

     $maxFileSize = 2 * 10e6; // = 2 000 000 bytes = 2MB
        if ($image['size'] > $maxFileSize)
            throw new Exception('Max size limit exceeded'); 
    
  6. Validate the image (Check whether the file is an image)

     $imageData = getimagesize($image['tmp_name']);
         if (!$imageData) 
         throw new Exception('Invalid image');
    
  7. Validate the image mime type (Do this according to your needs)

     $mimeType = $imageData['mime'];
     $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
     if (!in_array($mimeType, $allowedMimeTypes)) 
        throw new Exception('Only JPEG, PNG and GIFs are allowed');
    

This might help you to create a secure image uploading script with PHP.

Code source: https://developer.hyvor.com/php/image-upload-ajax-php-mysql

Additionally, I suggest you use MYSQLI prepared statements for queries to improve security.

Thank you.

Javascript - User input through HTML input tag to set a Javascript variable?

When your script is running, it blocks the page from doing anything. You can work around this with one of two ways:

  • Use var foo = prompt("Give me input");, which will give you the string that the user enters into a popup box (or null if they cancel it)
  • Split your code into two function - run one function to set up the user interface, then provide the second function as a callback that gets run when the user clicks the button.

HttpClient does not exist in .net 4.0: what can I do?

Referring to the answers above, I am only adding this to help clarify things. It is possible to use HttpClient from .Net 4.0, and you have to install the package from here

However, the text is very confusion and contradicts itself.

This package is not supported in Visual Studio 2010, and is only required for projects targeting .NET Framework 4.5, Windows 8, or Windows Phone 8.1 when consuming a library that uses this package.

But underneath it states that these are the supported platforms.

Supported Platforms:

  • .NET Framework 4

  • Windows 8

  • Windows Phone 8.1

  • Windows Phone Silverlight 7.5

  • Silverlight 4

  • Portable Class Libraries

Ignore what it ways about targeting .Net 4.5. This is wrong. The package is all about using HttpClient in .Net 4.0. However, you may need to use VS2012 or higher. Not sure if it works in VS2010, but that may be worth testing.

Why doesn't "System.out.println" work in Android?

Recently I noticed the same issue in Android Studio 3.3. I closed the other Android studio projects and Logcat started working. The accepted answer above is not logical at all.

How can the default node version be set using NVM?

Alert: This answer is for MacOS only

Let suppose you have 2 versions of nodeJS inside your nvm, namely v13.10.1 & v15.4.0

And, v15.4.0 is default

> nvm list
       v13.10.1
->      v15.4.0
         system
default -> 15.4.0 (-> v15.4.0)

And, you want to switch the default to v13.10.1

Follow these steps on your Mac terminal:

  1. Run the command:

    nvm alias default 13.10.1

This will make the default point to v13.10.1 as...

default -> 13.10.1 (-> v13.10.1)
  1. Open new instance of terminal. Now check the node version here as...

node -v

You will get...

v13.10.1
  1. nvm list will also show the new default version.

    nvm list

Just an info: The NodeJS versions taken as example above will have their different npm versions. You can cross-verify it in terminal by running npm -v

Algorithm/Data Structure Design Interview Questions

When interviewing recently, I was often asked to implement a data structure, usually LinkedList or HashMap. Both of these are easy enough to be doable in a short time, and difficult enough to eliminate the clueless.

Wait until all jQuery Ajax requests are done?

Try this way. make a loop inside java script function to wait until the ajax call finished.

function getLabelById(id)
{
    var label = '';
    var done = false;
    $.ajax({
       cache: false,
       url: "YourMvcActionUrl",
       type: "GET",
       dataType: "json",
       async: false,
       error: function (result) {
         label='undefined';
         done = true;
        },
       success: function (result) {
            label = result.Message;
            done = true;
        }
     });

   //A loop to check done if ajax call is done.
   while (!done)
   {
      setTimeout(function(){ },500); // take a sleep.
   }

    return label;
}

Accessing the index in 'for' loops?

As is the norm in Python there are several ways to do this. In all examples assume: lst = [1, 2, 3, 4, 5]

1. Using enumerate (considered most idiomatic)

for index, element in enumerate(lst):
    # do the things that need doing here

This is also the safest option in my opinion because the chance of going into infinite recursion has been eliminated. Both the item and its index are held in variables and there is no need to write any further code to access the item.

2. Creating a variable to hold the index (using for)

for index in range(len(lst)):   # or xrange
    # you will have to write extra code to get the element

3. Creating a variable to hold the index (using while)

index = 0
while index < len(lst):
    # you will have to write extra code to get the element
    index += 1  # escape infinite recursion

4. There is always another way

As explained before, there are other ways to do this that have not been explained here and they may even apply more in other situations. e.g using itertools.chain with for. It handles nested loops better than the other examples.

Cannot refer to a non-final variable inside an inner class defined in a different method

To avoid strange side-effects with closures in java variables referenced by an anonymous delegate must be marked as final, so to refer to lastPrice and price within the timer task they need to be marked as final.

This obviously won't work for you because you wish to change them, in this case you should look at encapsulating them within a class.

public class Foo {
    private PriceObject priceObject;
    private double lastPrice;
    private double price;

    public Foo(PriceObject priceObject) {
        this.priceObject = priceObject;
    }

    public void tick() {
        price = priceObject.getNextPrice(lastPrice);
        lastPrice = price;
    }
}

now just create a new Foo as final and call .tick from the timer.

public static void main(String args[]){
    int period = 2000;
    int delay = 2000;

    Price priceObject = new Price();
    final Foo foo = new Foo(priceObject);

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            foo.tick();
        }
    }, delay, period);
}

How to create a vector of user defined size but with no predefined values?

With the constructor:

// create a vector with 20 integer elements
std::vector<int> arr(20);

for(int x = 0; x < 20; ++x)
   arr[x] = x;

getting the error: expected identifier or ‘(’ before ‘{’ token

{
int main(void);

should be

int main(void)
{

Then I let you fix the next compilation errors of your program...

What is the difference between precision and scale?

Precision is the number of significant digits. Oracle guarantees the portability of numbers with precision ranging from 1 to 38.

Scale is the number of digits to the right (positive) or left (negative) of the decimal point. The scale can range from -84 to 127.

In your case, ID with precision 6 means it won't accept a number with 7 or more significant digits.

Reference:

http://download.oracle.com/docs/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT1832

That page also has some examples that will make you understand precision and scale.

How to force remounting on React components?

Use setState in your view to change employed property of state. This is example of React render engine.

 someFunctionWhichChangeParamEmployed(isEmployed) {
      this.setState({
          employed: isEmployed
      });
 }

 getInitialState() {
      return {
          employed: true
      }
 },

 render(){
    if (this.state.employed) {
        return (
            <div>
                <MyInput ref="job-title" name="job-title" />
            </div>
        );
    } else {
        return (
            <div>
                <span>Diff me!</span>
                <MyInput ref="unemployment-reason" name="unemployment-reason" />
                <MyInput ref="unemployment-duration" name="unemployment-duration" />
            </div>
        );
    }
}

Clang vs GCC - which produces faster binaries?

There is very little overall difference between GCC 4.8 and clang 3.3 in terms of speed of the resulting binary. In most cases code generated by both compilers performs similarly. Neither of these two compilers dominates the other one.

Benchmarks telling that there is a significant performance gap between GCC and clang are coincidental.

Program performance is affected by the choice of the compiler. If a developer or a group of developers is exclusively using GCC then the program can be expected to run slightly faster with GCC than with clang, and vice versa.

From developer viewpoint, a notable difference between GCC 4.8+ and clang 3.3 is that GCC has the -Og command line option. This option enables optimizations that do not interfere with debugging, so for example it is always possible to get accurate stack traces. The absence of this option in clang makes clang harder to use as an optimizing compiler for some developers.

How to import existing *.sql files in PostgreSQL 8.4?

Well, the shortest way I know of, is following:

psql -U {user_name} -d {database_name} -f {file_path} -h {host_name}

database_name: Which database should you insert your file data in.

file_path: Absolute path to the file through which you want to perform the importing.

host_name: The name of the host. For development purposes, it is mostly localhost.

Upon entering this command in console, you will be prompted to enter your password.

Returning a C string from a function

Your function signature needs to be:

const char * myFunction()
{
    return "My String";
}

Background:

It's so fundamental to C & C++, but little more discussion should be in order.

In C (& C++ for that matter), a string is just an array of bytes terminated with a zero byte - hence the term "string-zero" is used to represent this particular flavour of string. There are other kinds of strings, but in C (& C++), this flavour is inherently understood by the language itself. Other languages (Java, Pascal, etc.) use different methodologies to understand "my string".

If you ever use the Windows API (which is in C++), you'll see quite regularly function parameters like: "LPCSTR lpszName". The 'sz' part represents this notion of 'string-zero': an array of bytes with a null (/zero) terminator.

Clarification:

For the sake of this 'intro', I use the word 'bytes' and 'characters' interchangeably, because it's easier to learn this way. Be aware that there are other methods (wide-characters, and multi-byte character systems (mbcs)) that are used to cope with international characters. UTF-8 is an example of an mbcs. For the sake of intro, I quietly 'skip over' all of this.

Memory:

This means that a string like "my string" actually uses 9+1 (=10!) bytes. This is important to know when you finally get around to allocating strings dynamically.

So, without this 'terminating zero', you don't have a string. You have an array of characters (also called a buffer) hanging around in memory.

Longevity of data:

The use of the function this way:

const char * myFunction()
{
    return "My String";
}

int main()
{
    const char* szSomeString = myFunction(); // Fraught with problems
    printf("%s", szSomeString);
}

... will generally land you with random unhandled-exceptions/segment faults and the like, especially 'down the road'.

In short, although my answer is correct - 9 times out of 10 you'll end up with a program that crashes if you use it that way, especially if you think it's 'good practice' to do it that way. In short: It's generally not.

For example, imagine some time in the future, the string now needs to be manipulated in some way. Generally, a coder will 'take the easy path' and (try to) write code like this:

const char * myFunction(const char* name)
{
    char szBuffer[255];
    snprintf(szBuffer, sizeof(szBuffer), "Hi %s", name);
    return szBuffer;
}

That is, your program will crash because the compiler (may/may not) have released the memory used by szBuffer by the time the printf() in main() is called. (Your compiler should also warn you of such problems beforehand.)

There are two ways to return strings that won't barf so readily.

  1. returning buffers (static or dynamically allocated) that live for a while. In C++ use 'helper classes' (for example, std::string) to handle the longevity of data (which requires changing the function's return value), or
  2. pass a buffer to the function that gets filled in with information.

Note that it is impossible to use strings without using pointers in C. As I have shown, they are synonymous. Even in C++ with template classes, there are always buffers (that is, pointers) being used in the background.

So, to better answer the (now modified question). (There are sure to be a variety of 'other answers' that can be provided.)

Safer Answers:

Example 1, using statically allocated strings:

const char* calculateMonth(int month)
{
    static char* months[] = {"Jan", "Feb", "Mar" .... };
    static char badFood[] = "Unknown";
    if (month<1 || month>12)
        return badFood; // Choose whatever is appropriate for bad input. Crashing is never appropriate however.
    else
        return months[month-1];
}

int main()
{
    printf("%s", calculateMonth(2)); // Prints "Feb"
}

What the 'static' does here (many programmers do not like this type of 'allocation') is that the strings get put into the data segment of the program. That is, it's permanently allocated.

If you move over to C++ you'll use similar strategies:

class Foo
{
    char _someData[12];
public:
    const char* someFunction() const
    { // The final 'const' is to let the compiler know that nothing is changed in the class when this function is called.
        return _someData;
    }
}

... but it's probably easier to use helper classes, such as std::string, if you're writing the code for your own use (and not part of a library to be shared with others).

Example 2, using caller-defined buffers:

This is the more 'foolproof' way of passing strings around. The data returned isn't subject to manipulation by the calling party. That is, example 1 can easily be abused by a calling party and expose you to application faults. This way, it's much safer (albeit uses more lines of code):

void calculateMonth(int month, char* pszMonth, int buffersize)
{
    const char* months[] = {"Jan", "Feb", "Mar" .... }; // Allocated dynamically during the function call. (Can be inefficient with a bad compiler)
    if (!pszMonth || buffersize<1)
        return; // Bad input. Let junk deal with junk data.
    if (month<1 || month>12)
    {
        *pszMonth = '\0'; // Return an 'empty' string
        // OR: strncpy(pszMonth, "Bad Month", buffersize-1);
    }
    else
    {
        strncpy(pszMonth, months[month-1], buffersize-1);
    }
    pszMonth[buffersize-1] = '\0'; // Ensure a valid terminating zero! Many people forget this!
}

int main()
{
    char month[16]; // 16 bytes allocated here on the stack.
    calculateMonth(3, month, sizeof(month));
    printf("%s", month); // Prints "Mar"
}

There are lots of reasons why the second method is better, particularly if you're writing a library to be used by others (you don't need to lock into a particular allocation/deallocation scheme, third parties can't break your code, and you don't need to link to a specific memory management library), but like all code, it's up to you on what you like best. For that reason, most people opt for example 1 until they've been burnt so many times that they refuse to write it that way anymore ;)

Disclaimer:

I retired several years back and my C is a bit rusty now. This demo code should all compile properly with C (it is OK for any C++ compiler though).

Maximum number of records in a MySQL database table

I suggest, never delete data. Don't say if the tables is longer than 1000 truncate the end of the table. There needs to be real business logic in your plan like how long has this user been inactive. For example, if it is longer than 1 year then put them in a different table. You would have this happen weekly or monthly in a maintenance script in the middle of a slow time.

When you run into to many rows in your table then you should start sharding the tables or partitioning and put old data in old tables by year such as users_2011_jan, users_2011_feb or use numbers for the month. Then change your programming to work with this model. Maybe make a new table with less information to summarize the data in less columns and then only refer to the bigger partitioned tables when you need more information such as when the user is viewing their profile. All of this should be considered very carefully so in the future it isn't too expensive to re-factor. You could also put only the users which comes to your site all the time in one table and the users that never come in an archived set of tables.

403 - Forbidden: Access is denied. ASP.Net MVC

Are you hosting the site on iis? if so make sure the account your website runs under has access to local file system?

Straight from msdn .....

The Network Service account has Read and Execute permissions on the IIS server root folder by default. The IIS server root folder is named Wwwroot. This means that an ASP.NET application deployed inside the root folder already has Read and Execute permissions to its application folders. However, if your ASP.NET application needs to use files or folders in other locations, you must specifically enable access.

To provide access to an ASP.NET application running as Network Service, you must grant access to the Network Service account.

To grant read, write, and modify permissions to a specific file

  • In Windows Explorer, locate and select the required file.
  • Right-click the file, and then click Properties.
  • In the Properties dialog box, click the Security tab.
  • On the Security tab, examine the list of users. If the Network Service
  • account is not listed, add it.
  • In the Properties dialog box, click the Network Service user name, and in the Permissions for NETWORK SERVICE section, select the Read, Write, and Modify permissions.
  • Click Apply, and then click OK.

Click here for more

PHP DOMDocument loadHTML not encoding UTF-8 correctly

DOMDocument::loadHTML will treat your string as being in ISO-8859-1 unless you tell it otherwise. This results in UTF-8 strings being interpreted incorrectly.

If your string doesn't contain an XML encoding declaration, you can prepend one to cause the string to be treated as UTF-8:

$profile = '<p>???????????????????????9</p>';
$dom = new DOMDocument();
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $profile);
echo $dom->saveHTML();

If you cannot know if the string will contain such a declaration already, there's a workaround in SmartDOMDocument which should help you:

$profile = '<p>???????????????????????9</p>';
$dom = new DOMDocument();
$dom->loadHTML(mb_convert_encoding($profile, 'HTML-ENTITIES', 'UTF-8'));
echo $dom->saveHTML();

This is not a great workaround, but since not all characters can be represented in ISO-8859-1 (like these katana), it's the safest alternative.

How to set default values in Go structs

  1. Force a method to get the struct (the constructor way).

    From this post:

    A good design is to make your type unexported, but provide an exported constructor function like NewMyType() in which you can properly initialize your struct / type. Also return an interface type and not a concrete type, and the interface should contain everything others want to do with your value. And your concrete type must implement that interface of course.

    This can be done by simply making the type itself unexported. You can export the function NewSomething and even the fields Text and DefaultText, but just don't export the struct type something.

  2. Another way to customize it for you own module is by using a Config struct to set default values (Option 5 in the link). Not a good way though.

Matplotlib different size subplots

I used pyplot's axes object to manually adjust the sizes without using GridSpec:

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# definitions for the axes
left, width = 0.07, 0.65
bottom, height = 0.1, .8
bottom_h = left_h = left+width+0.02

rect_cones = [left, bottom, width, height]
rect_box = [left_h, bottom, 0.17, height]

fig = plt.figure()

cones = plt.axes(rect_cones)
box = plt.axes(rect_box)

cones.plot(x, y)

box.plot(y, x)

plt.show()

Proper way to restrict text input values (e.g. only numbers)

I use this one:


import { Directive, ElementRef, HostListener, Input, Output, EventEmitter } from '@angular/core';

@Directive({
    selector: '[ngModel][onlyNumber]',
    host: {
        "(input)": 'onInputChange($event)'
    }
})
export class OnlyNumberDirective {

    @Input() onlyNumber: boolean;
    @Output() ngModelChange: EventEmitter<any> = new EventEmitter()

    constructor(public el: ElementRef) {
    }

    public onInputChange($event){
        if ($event.target.value == '-') {
            return;
        }

        if ($event.target.value && $event.target.value.endsWith('.')) {
            return;
        }

        $event.target.value = this.parseNumber($event.target.value);
        $event.target.dispatchEvent(new Event('input'));
    }

    @HostListener('blur', ['$event'])
    public onBlur(event: Event) {
        if (!this.onlyNumber) {
            return;
        }

        this.el.nativeElement.value = this.parseNumber(this.el.nativeElement.value);
        this.el.nativeElement.dispatchEvent(new Event('input'));
    }

    private parseNumber(input: any): any {
        let trimmed = input.replace(/[^0-9\.-]+/g, '');
        let parsedNumber = parseFloat(trimmed);

        return !isNaN(parsedNumber) ? parsedNumber : '';
    }

}

and usage is following

<input onlyNumbers="true" ... />

the MySQL service on local computer started and then stopped

In my case, mysqld was starting and stopping with no error message. I needed to open command prompt using "Run as Administrator", and then run mysqld.

I am only doing this for temporary development. I would not recommend running MySQL as an administrator in any case.

This was the final step after the above troubleshooting.

How can I create C header files

  1. Open your favorite text editor
  2. Create a new file named whatever.h
  3. Put your function prototypes in it

DONE.

Example whatever.h

#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif

Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once but it is not guaranteed to be supported on every compiler.

Example whatever.c

#include "whatever.h"

int f(int a) { return a + 1; }

And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.

Like this:

sample.c

#include "whatever.h"

int main(int argc, char **argv)
{
    printf("%d\n", f(2)); /* prints 3 */
    return 0;
}

To compile it (if you use GCC):

$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o

To link the files to create an executable file:

$ gcc sample.o whatever.o -o sample

You can test sample:

$ ./sample
3
$

How can I add a new column and data to a datatable that already contains data?

Should it not be foreach instead of for!?

//call SQL helper class to get initial data  
DataTable dt = sql.ExecuteDataTable("sp_MyProc"); 

dt.Columns.Add("MyRow", **typeof**(System.Int32)); 

foreach(DataRow dr in dt.Rows) 
{ 
    //need to set value to MyRow column 
    dr["MyRow"] = 0;   // or set it to some other value 
} 

Use Excel pivot table as data source for another Pivot Table

As @nutsch implies, Excel won't do what you need directly, so you have to copy your data from the pivot table to somewhere else first. Rather than using copy and then paste values, however, a better way for many purposes is to create some hidden columns or a whole hidden sheet that copies values using simple formulae. The copy-paste approach isn't very useful when the original pivot table gets refreshed.

For instance, if Sheet1 contains the original pivot table, then:

  • Create Sheet2 and put =Sheet1!A1 into Sheet2!A1
  • Copy that formula around as many cells in Sheet2 as required to match the size of the original pivot table.
  • Assuming that the original pivot table could change size whenever it is refreshed, you could copy the formula in Sheet2 to cover the whole of the potential area the original pivot table could ever take. That will put lots of zeros in cells where the original cells are currently empty, but you could avoid that by using the formula =IF(Sheet1!A1="","",Sheet1!A1) instead.
  • Create your new pivot table based on a range within Sheet2, then hide Sheet2.

ModalPopupExtender OK Button click event not firing?

None of the previous answers worked for me. I called the postback of the button on the OnOkScript event.

<div>
    <cc1:ModalPopupExtender PopupControlID="Panel1" 
         ID="ModalPopupExtender1"
         runat="server" TargetControlID="LinkButton1" OkControlID="Ok" 
         OnOkScript="__doPostBack('Ok','')">
    </cc1:ModalPopupExtender>

    <asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton> 
</div>        


<asp:Panel ID="Panel1" runat="server">
    <asp:Button ID="Ok" runat="server" Text="Ok" onclick="Ok_Click" />            
</asp:Panel>   

How to get the system uptime in Windows?

I use this little PowerShell snippet:

function Get-SystemUptime {
    $operatingSystem = Get-WmiObject Win32_OperatingSystem
    "$((Get-Date) - ([Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)))"
}

which then yields something like the following:

PS> Get-SystemUptime
6.20:40:40.2625526

Differences between dependencyManagement and dependencies in Maven

In the parent POM, the main difference between the <dependencies> and <dependencyManagement> is this:

Artifacts specified in the <dependencies> section will ALWAYS be included as a dependency of the child module(s).

Artifacts specified in the <dependencyManagement> section will only be included in the child module if they were also specified in the section of the child module itself. Why is it good you ask? because you specify the version and/or scope in the parent, and you can leave them out when specifying the dependencies in the child POM. This can help you use unified versions for dependencies for child modules, without specifying the version in each child module.

Mocking member variables of a class using Mockito

You need to provide a way of accessing the member variables so you can pass in a mock (the most common ways would be a setter method or a constructor which takes a parameter).

If your code doesn't provide a way of doing this, it's incorrectly factored for TDD (Test Driven Development).

Check if a string contains a number

You could apply the function isdigit() on every character in the String. Or you could use regular expressions.

Also I found How do I find one number in a string in Python? with very suitable ways to return numbers. The solution below is from the answer in that question.

number = re.search(r'\d+', yourString).group()

Alternatively:

number = filter(str.isdigit, yourString)

For further Information take a look at the regex docu: http://docs.python.org/2/library/re.html

Edit: This Returns the actual numbers, not a boolean value, so the answers above are more correct for your case

The first method will return the first digit and subsequent consecutive digits. Thus 1.56 will be returned as 1. 10,000 will be returned as 10. 0207-100-1000 will be returned as 0207.

The second method does not work.

To extract all digits, dots and commas, and not lose non-consecutive digits, use:

re.sub('[^\d.,]' , '', yourString)

Running Python code in Vim

Plugin: jupyter-vim

So you can send lines (<leader>E), visual selection (<leader>e) to a running jupyter-client (the replacement of ipython)

enter image description here

I prefer to separate editor and interpreter (each one in its shell). Imagine you send a bad input reading command ...

What does appending "?v=1" to CSS and JavaScript URLs in link and script tags do?

Javascript files are often cached by the browser for a lot longer than you might expect.

This can often result in unexpected behaviour when you release a new version of your JS file.

Therefore, it is common practice to add a QueryString parameter to the URL for the javascript file. That way, the browser caches the Javascript file with v=1. When you release a new version of your javascript file you change the url's to v=2 and the browser will be forced to download a new copy.

how to convert integer to string?

If you really want to use String:

NSString *number = [[NSString alloc] initWithFormat:@"%d", 123];

But I would recommend using NSNumber:

NSNumber *number = [[NSNumber alloc] initWithInt:123];

Then just add it to the array.

[array addObject:number];

Don't forget to release it after that, since you created it above.

[number release];

C++ delete vector, objects, free memory

Move semantics allows for a straightforward way to release memory, by simply applying the assignment (=) operator from an empty rvalue:

std::vector<uint32_t> vec(100, 0);
std::cout << vec.capacity(); // 100

vec = vector<uint32_t>();    // Same as "vector<uint32_t>().swap(vec)";    
std::cout << vec.capacity(); // 0

It is as much efficient as the "swap()"-based method described in other answers (indeed, both are conceptually doing the same thing). When it comes to readability, however, the assignment version makes a better job at expressing the programmer's intention while being more concise.

Angular 2 Cannot find control with unspecified name attribute on formArrays

This happened to me because I left a formControlName empty (formControlName=""). Since I didn't need that extra form control, I deleted it and the error was resolved.

How do I pause my shell script for a second before continuing?

In Python (question was originally tagged Python) you need to import the time module

import time
time.sleep(1)

or

from time import sleep
sleep(1)

For shell script is is just

sleep 1

Which executes the sleep command. eg. /bin/sleep

How to uninstall a windows service and delete its files without rebooting

If in .net ( I'm not sure if it works for all windows services)

  • Stop the service (THis may be why you're having a problem.)
  • InstallUtil -u [name of executable]
  • Installutil -i [name of executable]
  • Start the service again...

Unless I'm changing the service's public interface, I often deploy upgraded versions of my services without even unistalling/reinstalling... ALl I do is stop the service, replace the files and restart the service again...

sscanf in Python

There is also the parse module.

parse() is designed to be the opposite of format() (the newer string formatting function in Python 2.6 and higher).

>>> from parse import parse
>>> parse('{} fish', '1')
>>> parse('{} fish', '1 fish')
<Result ('1',) {}>
>>> parse('{} fish', '2 fish')
<Result ('2',) {}>
>>> parse('{} fish', 'red fish')
<Result ('red',) {}>
>>> parse('{} fish', 'blue fish')
<Result ('blue',) {}>

Two Page Login with Spring Security 3.2.x

There should be three pages here:

  1. Initial login page with a form that asks for your username, but not your password.
  2. You didn't mention this one, but I'd check whether the client computer is recognized, and if not, then challenge the user with either a CAPTCHA or else a security question. Otherwise the phishing site can simply use the tendered username to query the real site for the security image, which defeats the purpose of having a security image. (A security question is probably better here since with a CAPTCHA the attacker could have humans sitting there answering the CAPTCHAs to get at the security images. Depends how paranoid you want to be.)
  3. A page after that that displays the security image and asks for the password.

I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.

I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.

You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST submission on step 1 (and 2 if applicable).

Javascript string/integer comparisons

You can use Number() function also since it converts the object argument to a number that represents the object's value.

Eg: javascript:alert( Number("2") > Number("10"))

Xcode error "Could not find Developer Disk Image"

I have also faced this issue, and I'm on Xcode 7.2.

It appeared when I downloaded iOS 9.3.

Check your Project -> Base SDK and if it isn't the same or ahead of your device version, then that's the issue.

I didn't see anything in the "Updates" section, but when I searched "Xcode" in the App Store it had an update for 7.3. Upgrading to iOS 9.3 and Xcode 7.3 requires Mac OS X v10.11 (El Capitan) for Xcode to run, and that's why auto update isn't upgrading Xcode versions.

Looping over a list in Python

You may as well use for x in values rather than for x in values[:]; the latter makes an unnecessary copy. Also, of course that code checks for a length of 2 rather than of 3...

The code only prints one item per value of x - and x is iterating over the elements of values, which are the sublists. So it will only print each sublist once.

HTML form with two submit buttons and two "target" attributes

Alternate Solution. Don't get messed up with onclick,buttons,server side and all.Just create a new form with different action like this.

<form method=post name=main onsubmit="return validate()" action="scale_test.html">
<input type=checkbox value="AC Hi-Side Pressure">AC Hi-Side Pressure<br>
<input type=checkbox value="Engine_Speed">Engine Speed<br>
<input type=submit value="Linear Scale" />
</form>
<form method=post name=main1 onsubmit="return v()" action=scale_log.html>
<input type=submit name=log id=log value="Log Scale">
</form>

Now in Javascript you can get all the elements of main form in v() with the help of getElementsByTagName(). To know whether the checkbox is checked or not

function v(){
var check = document.getElementsByTagName("input");

    for (var i=0; i < check.length; i++) {
        if (check[i].type == 'checkbox') {
            if (check[i].checked == true) {

        x[i]=check[i].value
            }
        }
    }
console.log(x);
}   

Adding an assets folder in Android Studio

You can click on the Project window, press Alt-Insert, and select Folder->Assets Folder. Android Studio will add it automatically to the correct location.

You are most likely looking at your Project with the new(ish) "Android View". Note that this is a view and not the actual folder structure on disk (which hasn't changed since the introduction of Gradle as the new build tool). You can switch to the old "Project View" by clicking on the word "Android" at the top of the Project window and selecting "Project".

Assign multiple values to array in C

If you are doing these same assignments a lot in your program and want a shortcut, the most straightforward solution might be to just add a function

static inline void set_coordinates(
        GLfloat coordinates[static 8],
        GLfloat c0, GLfloat c1, GLfloat c2, GLfloat c3,
        GLfloat c4, GLfloat c5, GLfloat c6, GLfloat c7)
{
    coordinates[0] = c0;
    coordinates[1] = c1;
    coordinates[2] = c2;
    coordinates[3] = c3;
    coordinates[4] = c4;
    coordinates[5] = c5;
    coordinates[6] = c6;
    coordinates[7] = c7;
}

and then simply call

GLfloat coordinates[8];
// ...
set_coordinates(coordinates, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f);

C++ Fatal Error LNK1120: 1 unresolved externals

Well it seems that you are missing a reference to some library. I had the similar error solved it by adding a reference to the #pragma comment(lib, "windowscodecs.lib")

"Debug only" code that should run only when "turned on"

I think it may be worth mentioning that [ConditionalAttribute] is in the System.Diagnostics; namespace. I stumbled a bit when I got:

Error 2 The type or namespace name 'ConditionalAttribute' could not be found (are you missing a using directive or an assembly reference?)

after using it for the first time (I thought it would have been in System).

HTML5 Video Autoplay not working correctly

<video width="1000px" loop="true" autoplay="autoplay" controls muted></video> worked for me