Programs & Examples On #Ie developer tools

For questions concerning Internet Explorer's built-in developer tools (HTML and CSS inspectors, JavaScript console, Profiler, Network Inspection, etc).

How to bring back "Browser mode" in IE11?

In IE11 we can change user agent to IE10, IE9 and even as windows phone. It is really good

'console' is undefined error for Internet Explorer

For IE8 or console support limited to console.log (no debug, trace, ...) you can do the following:

  • If console OR console.log undefined: Create dummy functions for console functions (trace, debug, log, ...)

    window.console = { debug : function() {}, ...};

  • Else if console.log is defined (IE8) AND console.debug (any other) is not defined: redirect all logging functions to console.log, this allows to keep those logs !

    window.console = { debug : window.console.log, ...};

Not sure about the assert support in various IE versions, but any suggestions are welcome. Also posted this answer here: How can I use console logging in Internet Explorer?

How to debug Javascript with IE 8

This won't help you step through code or break on errors, but it's a useful way to get the same debug console for your project on all browsers.

myLog = function() {
    if (!myLog._div) { myLog.createDiv(); }

    var logEntry = document.createElement('span');
    for (var i=0; i < arguments.length; i++) {
        logEntry.innerHTML += myLog.toJson(arguments[i]) + '<br />';
    }
    logEntry.innerHTML += '<br />';

    myLog._div.appendChild(logEntry);
}
myLog.createDiv = function() {
    myLog._div = document.body.appendChild(document.createElement('div'));
    var props = {
        position:'absolute', top:'10px', right:'10px', background:'#333', border:'5px solid #333', 
        color: 'white', width: '400px', height: '300px', overflow: 'auto', fontFamily: 'courier new',
        fontSize: '11px', whiteSpace: 'nowrap'
    }
    for (var key in props) { myLog._div.style[key] = props[key]; }
}
myLog.toJSON = function(obj) {
    if (typeof window.uneval == 'function') { return uneval(obj); }
    if (typeof obj == 'object') {
        if (!obj) { return 'null'; }
        var list = [];
        if (obj instanceof Array) {
            for (var i=0;i < obj.length;i++) { list.push(this.toJson(obj[i])); }
            return '[' + list.join(',') + ']';
        } else {
            for (var prop in obj) { list.push('"' + prop + '":' + this.toJson(obj[prop])); }
            return '{' + list.join(',') + '}';
        }
    } else if (typeof obj == 'string') {
        return '"' + obj.replace(/(["'])/g, '\\$1') + '"';
    } else {
        return new String(obj);
    }
}

myLog('log statement');
myLog('logging an object', { name: 'Marcus', likes: 'js' });

This is put together pretty hastily and is a bit sloppy, but it's useful nonetheless and can be improved easily!

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

I'm having a problem with your script in Firefox. When I scroll down, the script continues to add a margin to the page and I never reach the bottom of the page. This occurs because the ActionBox is still part of the page elements. I posted a demo here.

  • One solution would be to add a position: fixed to the CSS definition, but I see this won't work for you
  • Another solution would be to position the ActionBox absolutely (to the document body) and adjust the top.
  • Updated the code to fit with the solution found for others to benefit.

UPDATED:

CSS

#ActionBox {
 position: relative;
 float: right;
}

Script

var alert_top = 0;
var alert_margin_top = 0;

$(function() {
  alert_top = $("#ActionBox").offset().top;
  alert_margin_top = parseInt($("#ActionBox").css("margin-top"),10);

  $(window).scroll(function () {
    var scroll_top = $(window).scrollTop();
    if (scroll_top > alert_top) {
      $("#ActionBox").css("margin-top", ((scroll_top-alert_top)+(alert_margin_top*2)) + "px");
      console.log("Setting margin-top to " + $("#ActionBox").css("margin-top"));
    } else {
      $("#ActionBox").css("margin-top", alert_margin_top+"px");
    };
  });
});

Also it is important to add a base (10 in this case) to your parseInt(), e.g.

parseInt($("#ActionBox").css("top"),10);

How to set IE11 Document mode to edge as default?

I was having the same problem while developing my own website. While it was resident locally, resources opened as file//. For pages from the internet, including my own loaded as http://, the F12 Developer did use Edge as default, but not while they were loaded into IE11 from local files.

After following the suggestions above, I unchecked the box for "Display intranet Sites in Compatibility View".

That did the trick without adding any extra coding to my web page, or adding a multitude of pages to populate the list. Now all local files open in Edge document mode with F12.

So if you are referring to using F12 for locally hosted files, this may help.

Finding an elements XPath using IE Developer tool

If your goal is to find CSS selectors you can use MRI (once MRI is open, click any element to see various selectors for the element):

http://westciv.com/mri/

For Xpath:

http://functionaltestautomation.blogspot.com/2008/12/xpath-in-internet-explorer.html

How to automatically redirect HTTP to HTTPS on Apache servers?

Server version: Apache/2.4.29 (Ubuntu)

After long search on the web and in the official documentation of apache, the only solution that worked for me came from /usr/share/doc/apache2/README.Debian.gz

To enable SSL, type (as user root):

    a2ensite default-ssl
    a2enmod ssl

In the file /etc/apache2/sites-available/000-default.conf add the

Redirect "/" "https://sub.domain.com/"

<VirtualHost *:80>

    #ServerName www.example.com
    DocumentRoot /var/www/owncloud
    Redirect "/" "https://sub.domain.com/"

That's it.


P.S: If you want to read the manual without extracting:

gunzip -cd /usr/share/doc/apache2/README.Debian.gz

What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

I thought of just adding some points missing in above answers. This diagram taken from here clearly states the what's really going on.

enter image description here

If I state again the real purpose of

  • Split: Improves the parallel processing by distributing the processing load across different nodes (Mappers), which would save the overall processing time.

  • Combine: Shrinks the output of each Mapper. It would save the time spending for moving the data from one node to another.

  • Sort (Shuffle & Sort): Makes it easy for the run-time to schedule (spawn/start) new reducers, where while going through the sorted item list, whenever the current key is different from the previous, it can spawn a new reducer.

Count the number of occurrences of each letter in string

#include<stdio.h>

void frequency_counter(char* str)
{
    int count[256] = {0};  //partial initialization
    int i;

    for(i=0;str[i];i++)
        count[str[i]]++;

    for(i=0;str[i];i++) {
        if(count[str[i]]) {
            printf("%c %d \n",str[i],count[str[i]]);
            count[str[i]]=0;
        }
    }
}

void main()
{
    char str[] = "The quick brown fox jumped over the lazy dog.";
    frequency_counter(str);
}

How to run Gulp tasks sequentially one after the other

I generated a node/gulp app using the generator-gulp-webapp Yeoman generator. It handled the "clean conundrum" this way (translating to the original tasks mentioned in the question):

gulp.task('develop', ['clean'], function () {
  gulp.start('coffee');
});

C++ Structure Initialization

This feature is called designated initializers. It is an addition to the C99 standard. However, this feature was left out of the C++11. According to The C++ Programming Language, 4th edition, Section 44.3.3.2 (C Features Not Adopted by C++):

A few additions to C99 (compared with C89) were deliberately not adopted in C++:

[1] Variable-length arrays (VLAs); use vector or some form of dynamic array

[2] Designated initializers; use constructors

The C99 grammar has the designated initializers [See ISO/IEC 9899:2011, N1570 Committee Draft - April 12, 2011]

6.7.9 Initialization

initializer:
    assignment-expression
    { initializer-list }
    { initializer-list , }
initializer-list:
    designation_opt initializer
    initializer-list , designationopt initializer
designation:
    designator-list =
designator-list:
    designator
    designator-list designator
designator:
    [ constant-expression ]
    . identifier

On the other hand, the C++11 does not have the designated initializers [See ISO/IEC 14882:2011, N3690 Committee Draft - May 15, 2013]

8.5 Initializers

initializer:
    brace-or-equal-initializer
    ( expression-list )
brace-or-equal-initializer:
    = initializer-clause
    braced-init-list
initializer-clause:
    assignment-expression
    braced-init-list
initializer-list:
    initializer-clause ...opt
    initializer-list , initializer-clause ...opt
braced-init-list:
    { initializer-list ,opt }
    { }

In order to achieve the same effect, use constructors or initializer lists:

A beginner's guide to SQL database design

It's been a while since I read it (so, I'm not sure how much of it is still relevant), but my recollection is that Joe Celko's SQL for Smarties book provides a lot of info on writing elegant, effective, and efficient queries.

Is it possible to create static classes in PHP (like in C#)?

you can have those "static"-like classes. but i suppose, that something really important is missing: in php you don't have an app-cycle, so you won't get a real static (or singleton) in your whole application...

see Singleton in PHP

for-in statement

edit 2018: This is outdated, js and typescript now have for..of loops.
http://www.typescriptlang.org/docs/handbook/iterators-and-generators.html


The book "TypeScript Revealed" says

"You can iterate through the items in an array by using either for or for..in loops as demonstrated here:

// standard for loop
for (var i = 0; i < actors.length; i++)
{
  console.log(actors[i]);
}

// for..in loop
for (var actor in actors)
{
  console.log(actor);
}

"

Turns out, the second loop does not pass the actors in the loop. So would say this is plain wrong. Sadly it is as above, loops are untouched by typescript.

map and forEach often help me and are due to typescripts enhancements on function definitions more approachable, lke at the very moment:

this.notes = arr.map(state => new Note(state));

My wish list to TypeScript;

  1. Generic collections
  2. Iterators (IEnumerable, IEnumerator interfaces would be best)

ImportError: No module named Image

The PIL distribution is mispackaged for egg installation.

Install Pillow instead, the friendly PIL fork.

How can I remove the first line of a text file using bash/sed script?

For those who are on SunOS which is non-GNU, the following code will help:

sed '1d' test.dat > tmp.dat 

Change a column type from Date to DateTime during ROR migration

There's a change_column method, just execute it in your migration with datetime as a new type.

change_column(:my_table, :my_column, :my_new_type)

How to get current available GPUs in tensorflow?

In TensorFlow 2.0, you can use tf.config.experimental.list_physical_devices('GPU'):

import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
    print("Name:", gpu.name, "  Type:", gpu.device_type)

If you have two GPUs installed, it outputs this:

Name: /physical_device:GPU:0   Type: GPU
Name: /physical_device:GPU:1   Type: GPU

From 2.1, you can drop experimental:

gpus = tf.config.list_physical_devices('GPU')

See:

Run php function on button click

No Problem You can use onClick() function easily without using any other interference of language,

<?php
echo '<br><Button onclick="document.getElementById(';?>'modal-wrapper2'<?php echo ').style.display=';?>'block'<?php echo '" name="comment" style="width:100px; color: white;background-color: black;border-radius: 10px; padding: 4px;">Show</button>';
?>

What is the full path to the Packages folder for Sublime text 2 on Mac OS Lion

You can browse package folder below method.

  1. Use Sublime Text 2 menu : Preferences\Browse Packages
  2. In Windows 7 : C:\Users\%username%\AppData\Roaming\Sublime Text 2\Packages (equals %appdata%\Sublime Text 2\Packages)

Select unique or distinct values from a list in UNIX shell script

With AWK you can do, I find it faster than sort

 ./yourscript.ksh | awk '!a[$0]++'

How to set thousands separator in Java?

This should work (untested, based on JavaDoc):

DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US);
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();

symbols.setGroupingSeparator(' ');
formatter.setDecimalFormatSymbols(symbols);
System.out.println(formatter.format(bd.longValue()));

According to the JavaDoc, the cast in the first line should be save for most locales.

How to cherry-pick from a remote branch?

This can also be easily achieved with SourceTree:

  • checkout your master branch
  • open the "Log / History" tab
  • locate the xyz commit and right click on it
  • click on "Merge..."

done :)

Beginner Python: AttributeError: 'list' object has no attribute

Consider:

class Bike(object):
    def __init__(self, name, weight, cost):
        self.name = name
        self.weight = weight
        self.cost = cost

bikes = {
    # Bike designed for children"
    "Trike": Bike("Trike", 20, 100),      # <--
    # Bike designed for everyone"
    "Kruzer": Bike("Kruzer", 50, 165),    # <--
    }

# Markup of 20% on all sales
margin = .2
# Revenue minus cost after sale
for bike in bikes.values():
    profit = bike.cost * margin
    print(profit)

Output:

33.0
20.0

The difference is that in your bikes dictionary, you're initializing the values as lists [...]. Instead, it looks like the rest of your code wants Bike instances. So create Bike instances: Bike(...).

As for your error

AttributeError: 'list' object has no attribute 'cost'

this will occur when you try to call .cost on a list object. Pretty straightforward, but we can figure out what happened by looking at where you call .cost -- in this line:

profit = bike.cost * margin

This indicates that at least one bike (that is, a member of bikes.values() is a list). If you look at where you defined bikes you can see that the values were, in fact, lists. So this error makes sense.

But since your class has a cost attribute, it looked like you were trying to use Bike instances as values, so I made that little change:

[...] -> Bike(...)

and you're all set.

How to view unallocated free space on a hard disk through terminal

The simplest way to show unallocated free space in a single command:

$ sudo sfdisk --list-free /dev/sdX

(Add the --quiet option if you don't need the extra info about sector size, etc.)

What is the correct way to write HTML using Javascript?

document.write() will only work while the page is being originally parsed and the DOM is being created. Once the browser gets to the closing </body> tag and the DOM is ready, you can't use document.write() anymore.

I wouldn't say using document.write() is correct or incorrect, it just depends on your situation. In some cases you just need to have document.write() to accomplish the task. Look at how Google analytics gets injected into most websites.

After DOM ready, you have two ways to insert dynamic HTML (assuming we are going to insert new HTML into <div id="node-id"></div>):

  1. Using innerHTML on a node:

    var node = document.getElementById('node-id');
    node.innerHTML('<p>some dynamic html</p>');
    
  2. Using DOM methods:

    var node = document.getElementById('node-id');
    var newNode = document.createElement('p');
    newNode.appendChild(document.createTextNode('some dynamic html'));
    node.appendChild(newNode);
    

Using the DOM API methods might be the purist way to do stuff, but innerHTML has been proven to be much faster and is used under the hood in JavaScript libraries such as jQuery.

Note: The <script> will have to be inside your <body> tag for this to work.

Webpack.config how to just copy the index.html to the dist folder

To copy an already existing index.html file into the dist directory you can simply use the HtmlWebpackPlugin by specifying the source index.html as a template.

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  // ...
  plugins: [    
    new HtmlWebpackPlugin({
      template: './path/to/index.html',
    })
  ],
  // ...
};

The created dist/index.html file will be basically the same as your source file with the difference that bundled resources like .js files are injected with <script> tags by webpack. Minification and further options can be configured and are documented on github.

Convert 4 bytes to int

If you have them already in a byte[] array, you can use:

int result = ByteBuffer.wrap(bytes).getInt();

source: here

How to check if there exists a process with a given pid in Python?

I'd say use the PID for whatever purpose you're obtaining it and handle the errors gracefully. Otherwise, it's a classic race (the PID may be valid when you check it's valid, but go away an instant later)

c# regex matches example

Regex regex = new Regex("%download#(\\d+?)%", RegexOptions.SingleLine);
Matches m = regex.Matches(input);

I think will do the trick (not tested).

Adding rows dynamically with jQuery

Untested. Modify to suit:

$form = $('#my-form');

$rows = $form.find('.person-input-row');

$('button#add-new').click(function() {

    $rows.find(':first').clone().insertAfter($rows.find(':last'));

    $justInserted = $rows.find(':last');
    $justInserted.hide();
    $justInserted.find('input').val(''); // it may copy values from first one
    $justInserted.slideDown(500);


});

This is better than copying innerHTML because you will lose all attached events etc.

Send email with PHP from html form on submit with the same script

Here are the PHP mail settings I use:

//Mail sending function
$subject = $_POST['name'];
$to = $_POST['email'];
$from = "[email protected]";

//data
$msg = "Your MSG <br>\n";       

//Headers
$headers  = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "From: <".$from. ">" ;

mail($to,$subject,$msg,$headers);
echo "Mail Sent.";

Reloading .env variables without restarting server (Laravel 5, shared hosting)

It's possible that your configuration variables are cached. Verify your config/app.php as well as your .env file then try

php artisan cache:clear

on the command line.

jQuery: Can I call delay() between addClass() and such?

AFAIK the delay method only works for numeric CSS modifications.

For other purposes JavaScript comes with a setTimeout method:

window.setTimeout(function(){$("#div").removeClass("error");}, 1000);

Android: Pass data(extras) to a fragment

Two things. First I don't think you are adding the data that you want to pass to the fragment correctly. What you need to pass to the fragment is a bundle, not an intent. For example if I wanted send an int value to a fragment I would create a bundle, put the int into that bundle, and then set that bundle as an argument to be used when the fragment was created.

Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

Second to retrieve that information you need to get the arguments sent to the fragment. You then extract the value based on the key you identified it with. For example in your fragment:

Bundle bundle = this.getArguments();
if (bundle != null) {
    int i = bundle.getInt(key, defaulValue);
}

What you are getting changes depending on what you put. Also the default value is usually null but does not need to be. It depends on if you set a default value for that argument.

Lastly I do not think you can do this in onCreateView. I think you must retrieve this data within your fragment's onActivityCreated method. My reasoning is as follows. onActivityCreated runs after the underlying activity has finished its own onCreate method. If you are placing the information you wish to retrieve within the bundle durring your activity's onCreate method, it will not exist during your fragment's onCreateView. Try using this in onActivityCreated and just update your ListView contents later.

Setting a windows batch file variable to the day of the week

Rem Remove the end comma and add /A to set for this line worked for me.
set /A a=yy/100, b=a/4, c=2-a+b, e=36525*(yy+4716)/100, f=306*(mm+1)/10 

Disable all dialog boxes in Excel while running VB script?

Have you tried using the ConflictResolution:=xlLocalSessionChanges parameter in the SaveAs method?

As so:

Public Sub example()
Application.DisplayAlerts = False
Application.EnableEvents = False

For Each element In sArray
    XLSMToXLSX(element)
Next element

Application.DisplayAlerts = False
Application.EnableEvents = False
End Sub

Sub XLSMToXLSX(ByVal file As String)
    Do While WorkFile <> ""
        If Right(WorkFile, 4) <> "xlsx" Then
            Workbooks.Open Filename:=myPath & WorkFile

            Application.DisplayAlerts = False
            Application.EnableEvents = False

            ActiveWorkbook.SaveAs Filename:= _
            modifiedFileName, FileFormat:= _
            xlOpenXMLWorkbook, CreateBackup:=False, _
            ConflictResolution:=xlLocalSessionChanges

            Application.DisplayAlerts = True
            Application.EnableEvents = True

            ActiveWorkbook.Close
        End If
        WorkFile = Dir()
    Loop
End Sub

How to insert a line break before an element using CSS

Yes, totally doable but it is definitely a total hack (people may give you dirty looks for writing such code).

Here is the HTML:

<div>lorem ipdum dolor sit <span id="restart">amit e pluribus unum</span></div>

Here is the CSS:

#restart:before { content: 'hiddentext'; font-size:0; display:block; line-height:0; }

Here is the fiddle: http://jsfiddle.net/AprNY/

Difference between <? super T> and <? extends T> in Java

Imagine having this hierarchy

enter image description here

1. Extends

By writing

    List<? extends C2> list;

you are saying that list will be able to reference an object of type (for example) ArrayList whose generic type is one of the 7 subtypes of C2 (C2 included):

  1. C2: new ArrayList<C2>();, (an object that can store C2 or subtypes) or
  2. D1: new ArrayList<D1>();, (an object that can store D1 or subtypes) or
  3. D2: new ArrayList<D2>();, (an object that can store D2 or subtypes) or...

and so on. Seven different cases:

    1) new ArrayList<C2>(): can store C2 D1 D2 E1 E2 E3 E4
    2) new ArrayList<D1>(): can store    D1    E1 E2  
    3) new ArrayList<D2>(): can store       D2       E3 E4
    4) new ArrayList<E1>(): can store          E1             
    5) new ArrayList<E2>(): can store             E2             
    6) new ArrayList<E3>(): can store                E3             
    7) new ArrayList<E4>(): can store                   E4             

We have a set of "storable" types for each possible case: 7 (red) sets here graphically represented

enter image description here

As you can see, there is not a safe type that is common to every case:

  • you cannot list.add(new C2(){}); because it could be list = new ArrayList<D1>();
  • you cannot list.add(new D1(){}); because it could be list = new ArrayList<D2>();

and so on.

2. Super

By writing

    List<? super C2> list;

you are saying that list will be able to reference an object of type (for example) ArrayList whose generic type is one of the 7 supertypes of C2 (C2 included):

  • A1: new ArrayList<A1>();, (an object that can store A1 or subtypes) or
  • A2: new ArrayList<A2>();, (an object that can store A2 or subtypes) or
  • A3: new ArrayList<A3>();, (an object that can store A3 or subtypes) or...

and so on. Seven different cases:

    1) new ArrayList<A1>(): can store A1          B1 B2       C1 C2    D1 D2 E1 E2 E3 E4
    2) new ArrayList<A2>(): can store    A2          B2       C1 C2    D1 D2 E1 E2 E3 E4
    3) new ArrayList<A3>(): can store       A3          B3       C2 C3 D1 D2 E1 E2 E3 E4
    4) new ArrayList<A4>(): can store          A4       B3 B4    C2 C3 D1 D2 E1 E2 E3 E4
    5) new ArrayList<B2>(): can store                B2       C1 C2    D1 D2 E1 E2 E3 E4
    6) new ArrayList<B3>(): can store                   B3       C2 C3 D1 D2 E1 E2 E3 E4
    7) new ArrayList<C2>(): can store                            C2    D1 D2 E1 E2 E3 E4

We have a set of "storable" types for each possible case: 7 (red) sets here graphically represented

enter image description here

As you can see, here we have seven safe types that are common to every case: C2, D1, D2, E1, E2, E3, E4.

  • you can list.add(new C2(){}); because, regardless of the kind of List we're referencing, C2 is allowed
  • you can list.add(new D1(){}); because, regardless of the kind of List we're referencing, D1 is allowed

and so on. You probably noticed that these types correspond to the hierarchy starting from type C2.

Notes

Here the complete hierarchy if you wish to make some tests

interface A1{}
interface A2{}
interface A3{}
interface A4{}

interface B1 extends A1{}
interface B2 extends A1,A2{}
interface B3 extends A3,A4{}
interface B4 extends A4{}

interface C1 extends B2{}
interface C2 extends B2,B3{}
interface C3 extends B3{}

interface D1 extends C1,C2{}
interface D2 extends C2{}

interface E1 extends D1{}
interface E2 extends D1{}
interface E3 extends D2{}
interface E4 extends D2{}

How do I create executable Java program?

If you are using Eclipse , you can try the below 7 steps to get a .exe file for Windows.

step1step2step3

Now you have a JAR file. Use java -jar path/jarname.jar to execute.

enter image description here


If you want to convert this to .exe, you can try http://sourceforge.net/projects/launch4j/files/launch4j-3/

STEP5STEP6

STEP7: Give the .xml file an appropriate name and click "Save". The .xml file is standard, don't worry about it. Your executable file will now be created!

Sending message through WhatsApp

use this singleline code use to Sending message through WhatsApp

//NOTE : please use with country code first 2digits without plus signed
try {
      String mobile = "911234567890";
      String msg = "Its Working";
      startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://api.whatsapp.com/send?phone=" + mobile + "&text=" + msg)));
      }catch (Exception e){
        //whatsapp app not install
     }

Calculating average of an array list?

Using Guava, it gets syntactically simplified:

Stats.meanOf(numericList);

How can I consume a WSDL (SOAP) web service in Python?

SOAPpy is now obsolete, AFAIK, replaced by ZSL. It's a moot point, because I can't get either one to work, much less compile, on either Python 2.5 or Python 2.6

Googlemaps API Key for Localhost

If you are working on localhost, create a separate APIkey for your development and then remove restrictions on that key so that your localhost can use it. Remember to not use this key on production, so you don't expose your key to hunters online.

I had the same issue and all attempts to get the restrictions working on my localhost environment was not successful until I created a separate apikey specifically for development and then removed its restrictions. However I don't use that key on production environment, and once am done with developments, I will delete the API key immediately.

I Know this post is late, but for people that will likely face this issue in the future, this is the best route to go.

Sending JWT token in the headers with Postman

If you wish to use postman the right way is to use the headers as such

key: Authorization

value: jwt {token}

as simple as that.

How to resolve "git did not exit cleanly (exit code 128)" error on TortoiseGit?

In my case, I forgot to add git to the respository name at the end.

Create request with POST, which response codes 200 or 201 and content

I think atompub REST API is a great example of a restful service. See the snippet below from the atompub spec:

POST /edit/ HTTP/1.1
Host: example.org
User-Agent: Thingio/1.0
Authorization: Basic ZGFmZnk6c2VjZXJldA==
Content-Type: application/atom+xml;type=entry
Content-Length: nnn
Slug: First Post

<?xml version="1.0"?>
<entry xmlns="http://www.w3.org/2005/Atom">
  <title>Atom-Powered Robots Run Amok</title>
  <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
  <updated>2003-12-13T18:30:02Z</updated>
  <author><name>John Doe</name></author>
  <content>Some text.</content>
</entry>

The server signals a successful creation with a status code of 201. The response includes a Location header indicating the Member Entry URI of the Atom Entry, and a representation of that Entry in the body of the response.

HTTP/1.1 201 Created
Date: Fri, 7 Oct 2005 17:17:11 GMT
Content-Length: nnn
Content-Type: application/atom+xml;type=entry;charset="utf-8"
Location: http://example.org/edit/first-post.atom
ETag: "c180de84f991g8"  

<?xml version="1.0"?>
<entry xmlns="http://www.w3.org/2005/Atom">
  <title>Atom-Powered Robots Run Amok</title>
  <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
  <updated>2003-12-13T18:30:02Z</updated>
  <author><name>John Doe</name></author>
  <content>Some text.</content>
  <link rel="edit"
      href="http://example.org/edit/first-post.atom"/>
</entry>

The Entry created and returned by the Collection might not match the Entry POSTed by the client. A server MAY change the values of various elements in the Entry, such as the atom:id, atom:updated, and atom:author values, and MAY choose to remove or add other elements and attributes, or change element content and attribute values.

Run "mvn clean install" in Eclipse

If you want to open command prompt inside your eclipse, this can be a useful approach to link cmd with eclipse.

You can follow this link to get the steps in detail with screenshots. How to use cmd prompt inside Eclipse ?

I'm quoting the steps here:

Step 1: Setup a new External Configuration Tool

In the Eclipse tool go to Run -> External Tools -> External Tools Configurations option.

Step 2: Click New Launch Configuration option in Create, manage and run configuration screen

Step 3: New Configuration screen for configuring the command prompt

Step 4: Provide configuration details of the Command Prompt in the Main tab

Name: Give any name to your configuration (Here it is Command_Prompt)
Location: Location of the CMD.exe in your Windows
Working Directory: Any directory where you want to point the Command prompt

Step 5: Tick the check box Allocate console This will ensure the eclipse console is being used as the command prompt for any input or output.

Step 6: Click Run and you are there!! You will land up in the C: directory as a working directory

When should I use GC.SuppressFinalize()?

SupressFinalize tells the system that whatever work would have been done in the finalizer has already been done, so the finalizer doesn't need to be called. From the .NET docs:

Objects that implement the IDisposable interface can call this method from the IDisposable.Dispose method to prevent the garbage collector from calling Object.Finalize on an object that does not require it.

In general, most any Dispose() method should be able to call GC.SupressFinalize(), because it should clean up everything that would be cleaned up in the finalizer.

SupressFinalize is just something that provides an optimization that allows the system to not bother queuing the object to the finalizer thread. A properly written Dispose()/finalizer should work properly with or without a call to GC.SupressFinalize().

How to create a hash or dictionary object in JavaScript

A built-in Map type is now available in JavaScript. It can be used instead of simply using Object. It is supported by current versions of all major browsers.

Maps do not support the [subscript] notation used by Objects. That syntax implicitly casts the subscript value to a primitive string or symbol. Maps support any values as keys, so you must use the methods .get(key), .set(key, value) and .has(key).

_x000D_
_x000D_
var m = new Map();_x000D_
var key1 = 'key1';_x000D_
var key2 = {};_x000D_
var key3 = {};_x000D_
_x000D_
m.set(key1, 'value1');_x000D_
m.set(key2, 'value2');_x000D_
_x000D_
console.assert(m.has(key2), "m should contain key2.");_x000D_
console.assert(!m.has(key3), "m should not contain key3.");
_x000D_
_x000D_
_x000D_

Objects only supports primitive strings and symbols as keys, because the values are stored as properties. If you were using Object, it wouldn't be able to to distinguish key2 and key3 because their string representations would be the same:

_x000D_
_x000D_
var o = new Object();_x000D_
var key1 = 'key1';_x000D_
var key2 = {};_x000D_
var key3 = {};_x000D_
_x000D_
o[key1] = 'value1';_x000D_
o[key2] = 'value2';_x000D_
_x000D_
console.assert(o.hasOwnProperty(key2), "o should contain key2.");_x000D_
console.assert(!o.hasOwnProperty(key3), "o should not contain key3."); // Fails!
_x000D_
_x000D_
_x000D_

Related

SyntaxError: missing ) after argument list

How to reproduce this error:

SyntaxError: missing ) after argument list

This code produces the error:

<html>
<body>
<script type="text/javascript" src="jquery-2.1.0.min.js"></script>
<script type="text/javascript">
  $(document).ready(function(){

  }
</script>
</body>
</html>

If you run this and look at the error output in firebug, you get this error. The empty function passed into 'ready' is not closed. Fix it like this:

<html>
<body>
<script type="text/javascript" src="jquery-2.1.0.min.js"></script>
<script type="text/javascript">
  $(document).ready(function(){

  });      //<-- notice the right parenthesis and semicolon
</script>
</body>
</html>

And then the Javascript is interpreted correctly.

Python module for converting PDF to text

Found that solution today. Works great for me. Even rendering PDF pages to PNG images. http://www.swftools.org/gfx_tutorial.html

Validation of file extension before uploading file

This is how it is done in jquery

$("#artifact_form").submit(function(){
    return ["jpg", "jpeg", "bmp", "gif", "png"].includes(/[^.]+$/.exec($("#artifact_file_name").val())[0])
  });

Checking from shell script if a directory contains files

DIR="/some/dir"
if [ "$(ls -A $DIR)" ]; then
     echo 'There is something alive in here'
fi

Get webpage contents with Python?

Also you can use faster_than_requests package. That's very fast and simple:

import faster_than_requests as r
content = r.get2str("http://test.com/")

Look at this comparison:

enter image description here

When does SQLiteOpenHelper onCreate() / onUpgrade() run?

Recheck your query in ur DatabaseHandler/DatabaseManager class(which ever you have took)

Difference between frontend, backend, and middleware in web development

In terms of networking and security, the Backend is by far the most (should be) secure node.

The middle-end portion, usually being a web server, will be somewhat in the wild and cut off in many respects from a company's network. The middle-end node is usually placed in the DMZ and segmented from the network with firewall settings. Most of the server-side code parsing of web pages is handled on the middle-end web server.

Getting to the backend means going through the middle-end, which has a carefully crafted set of rules allowing/disallowing access to the vital nummies which are stored on the database (backend) server.

phpmailer error "Could not instantiate mail function"

The PHPMailer help docs on this specific error helped to get me on the right path.

What we found is that php.ini did not have the sendmail_path defined, so I added that with sendmail_path = /usr/sbin/sendmail -t -i;

How can I drop all the tables in a PostgreSQL database?

Rake task for Rails for destroy all tables in current database

namespace :db do
  # rake db:drop_all_tables
  task drop_all_tables: :environment do
    query = <<-QUERY
      SELECT
        table_name
      FROM
        information_schema.tables
      WHERE
        table_type = 'BASE TABLE'
      AND
        table_schema NOT IN ('pg_catalog', 'information_schema');
    QUERY

    connection = ActiveRecord::Base.connection
    results    = connection.execute query

    tables = results.map do |line|
      table_name = line['table_name']
    end.join ", "

    connection.execute "DROP TABLE IF EXISTS #{ tables } CASCADE;"
  end
end

Wampserver icon not going green fully, mysql services not starting up?

Have you tried just changing the port number of MySQL and see if it works?

  1. Right click your WAMP icon

  2. Choose MySQL, in the menu choose "Use a port other than 3306"

  3. Change port number to be "3307"

Can I disable a CSS :hover effect via JavaScript?

I used the not() CSS operator and jQuery's addClass() function. Here is an example, when you click on a list item, it won't hover anymore:

For example:

HTML

<ul class="vegies">
    <li>Onion</li>
    <li>Potato</li>
    <li>Lettuce</li>
<ul>

CSS

.vegies li:not(.no-hover):hover { color: blue; }

jQuery

$('.vegies li').click( function(){
    $(this).addClass('no-hover');
});

Where to find htdocs in XAMPP Mac

At least for macbook (os high sierra) go to terminal and type or copy and paste:

cd ~/.bitnami/stackman/machines/xampp/volumes/root/htdocs

Importing from a relative path in Python

Doing a relative import is absolulutely OK! Here's what little 'ol me does:

#first change the cwd to the script path
scriptPath = os.path.realpath(os.path.dirname(sys.argv[0]))
os.chdir(scriptPath)

#append the relative location you want to import from
sys.path.append("../common")

#import your module stored in '../common'
import common.py

Retrofit 2 - URL Query Parameter

 public interface IService { 

  String BASE_URL = "https://api.demo.com/";

  @GET("Login") //i.e https://api.demo.com/Search? 
  Call<Products> getUserDetails(@Query("email") String emailID, @Query("password") String password)

} 

It will be called this way. Considering you did the rest of the code already.

Call<Results> call = service.getUserDetails("[email protected]", "Password@123");

For example when a query is returned, it will look like this.

https://api.demo.com/[email protected]&password=Password@123

How to get CSS to select ID that begins with a string (not in Javascript)?

I'd do it like this:

[id^="product"] {
  ...
}

Ideally, use a class. This is what classes are for:

<div id="product176" class="product"></div>
<div id="product177" class="product"></div>
<div id="product178" class="product"></div>

And now the selector becomes:

.product {
  ...
}

How to make html table vertically scrollable

This is a work around.

http://jsfiddle.net/JJV59/2/

[EDIT]

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->

</head>
<body>

<table cellspacing="1" width="100%" bgcolor="#cccccc">
    <thead>
        <tr>
            <td bgcolor="#ffffff" width="70px">
            </td>
            <td class="csstablelisttd" width="70px">
                <b>Time Slot&nbsp;</b>
            </td>
            <td class="csstablelisttd">
                <b>&nbsp;Patient Name</b>
            </td>
        </tr>
    </thead>
</table>
<!-- THIS GIVES THE SCROLLER -->
<div style="height: 500px; overflow-y: auto">
    <table id="tableAppointment" cellspacing="1" width="100%" bgcolor="#cccccc">
         <tbody>
            <tr>
                <td class="csstablelisttd" valign="top" width="70px">
                    8:00AM
                </td>
                <td class="csstablelisttd" width="70px">
                    0
                </td>
                <td class="csstablelisttd">
                    <span>Name 1</span>
                </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        15
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        30
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        45
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd" valign="top" width="90px">
                        9:00AM
                    </td>
                    <td class="csstablelisttd">
                        0
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        15
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        30
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        45
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd" valign="top" width="90px">
                        10:00AM
                    </td>
                    <td class="csstablelisttd">
                        0
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        15
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        30
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        45
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd" valign="top" width="90px">
                        11:00AM
                    </td>
                    <td class="csstablelisttd">
                        0
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        15
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        30
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        45
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd" valign="top" width="90px">
                        12:00PM
                    </td>
                    <td class="csstablelisttd">
                        0
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        15
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        30
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        45
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd" valign="top" width="90px">
                        01:00PM
                    </td>
                    <td class="csstablelisttd">
                        0
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        15
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        30
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        45
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd" valign="top" width="90px">
                        02:00PM
                    </td>
                    <td class="csstablelisttd">
                        0
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        15
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        30
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        45
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd" valign="top" width="90px">
                        03:00PM
                    </td>
                    <td class="csstablelisttd">
                        0
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        15
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        30
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        45
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd" valign="top" width="90px">
                        04:00PM
                    </td>
                    <td class="csstablelisttd">
                        0
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        15
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        30
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        45
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd" valign="top" width="90px">
                        05:00PM
                    </td>
                    <td class="csstablelisttd">
                        0
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        15
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        30
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        45
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd" valign="top" width="90px">
                        06:00PM
                    </td>
                    <td class="csstablelisttd">
                        0
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        15
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        30
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        45
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd" valign="top" width="90px">
                        07:00PM
                    </td>
                    <td class="csstablelisttd">
                        0
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        15
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        30
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd">
                    </td>
                    <td class="csstablelisttd">
                        45
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
                <tr>
                    <td class="csstablelisttd" valign="top" width="90px">
                        08:00PM
                    </td>
                    <td class="csstablelisttd">
                        0
                    </td>
                    <td class="csstablelisttd">
                        <span></span>
                    </td>
                </tr>
            </tbody>
        </table>    
    </div>

</body>
</html>

Can you autoplay HTML5 videos on the iPad?

Let video muted first to ensure autoplay in ios, then unmute it if you want.

<video autoplay loop muted playsinline>
  <source src="video.mp4?123" type="video/mp4">
</video>

<script type="text/javascript">
$(function () {
  if (!navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
    $("video").prop('muted', false);
  }
});
</script>

Bad operand type for unary +: 'str'

The code works for me. (after adding missing except clause / import statements)

Did you put \ in the original code?

urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' \
              + stock + '/chartdata;type=quote;range=5d/csv'

If you omit it, it could be a cause of the exception:

>>> stock = 'GOOG'
>>> urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'
>>> + stock + '/chartdata;type=quote;range=5d/csv'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'

BTW, string(e) should be str(e).

Attach the Source in Eclipse of a jar

  1. Download JDEclipse from http://java-decompiler.github.io/
  2. Follow the installation steps
  3. If you still didn't find the source, right click on the jar file and select "Attach Library Source" option from the project folder, as you can see below.

Drop down option location

javascript scroll event for iPhone/iPad?

For iOS you need to use the touchmove event as well as the scroll event like this:

document.addEventListener("touchmove", ScrollStart, false);
document.addEventListener("scroll", Scroll, false);

function ScrollStart() {
    //start of scroll event for iOS
}

function Scroll() {
    //end of scroll event for iOS
    //and
    //start/end of scroll event for other browsers
}

Given final block not properly padded

If you try to decrypt PKCS5-padded data with the wrong key, and then unpad it (which is done by the Cipher class automatically), you most likely will get the BadPaddingException (with probably of slightly less than 255/256, around 99.61%), because the padding has a special structure which is validated during unpad and very few keys would produce a valid padding.

So, if you get this exception, catch it and treat it as "wrong key".

This also can happen when you provide a wrong password, which then is used to get the key from a keystore, or which is converted into a key using a key generation function.

Of course, bad padding can also happen if your data is corrupted in transport.

That said, there are some security remarks about your scheme:

  • For password-based encryption, you should use a SecretKeyFactory and PBEKeySpec instead of using a SecureRandom with KeyGenerator. The reason is that the SecureRandom could be a different algorithm on each Java implementation, giving you a different key. The SecretKeyFactory does the key derivation in a defined manner (and a manner which is deemed secure, if you select the right algorithm).

  • Don't use ECB-mode. It encrypts each block independently, which means that identical plain text blocks also give always identical ciphertext blocks.

    Preferably use a secure mode of operation, like CBC (Cipher block chaining) or CTR (Counter). Alternatively, use a mode which also includes authentication, like GCM (Galois-Counter mode) or CCM (Counter with CBC-MAC), see next point.

  • You normally don't want only confidentiality, but also authentication, which makes sure the message is not tampered with. (This also prevents chosen-ciphertext attacks on your cipher, i.e. helps for confidentiality.) So, add a MAC (message authentication code) to your message, or use a cipher mode which includes authentication (see previous point).

  • DES has an effective key size of only 56 bits. This key space is quite small, it can be brute-forced in some hours by a dedicated attacker. If you generate your key by a password, this will get even faster. Also, DES has a block size of only 64 bits, which adds some more weaknesses in chaining modes. Use a modern algorithm like AES instead, which has a block size of 128 bits, and a key size of 128 bits (for the standard variant).

Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

As an complement to Stefan Steiger answer: (as it doesn't look nice as a comment)

Extending String prototype:

String.prototype.b64encode = function() { 
    return btoa(unescape(encodeURIComponent(this))); 
};
String.prototype.b64decode = function() { 
    return decodeURIComponent(escape(atob(this))); 
};

Usage:

var str = "äöüÄÖÜçéèñ";
var encoded = str.b64encode();
console.log( encoded.b64decode() );

NOTE:

As stated in the comments, using unescape is not recommended as it may be removed in the future:

Warning: Although unescape() is not strictly deprecated (as in "removed from the Web standards"), it is defined in Annex B of the ECMA-262 standard, whose introduction states: … All of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification.

Note: Do not use unescape to decode URIs, use decodeURI or decodeURIComponent instead.

Why am I getting AttributeError: Object has no attribute

If you’re using python 3+ this may also occur if you’re using private variables that start with double underscore, e.g., self.__yourvariable. Just something to take note of for some of you who may run into this issue.

yii2 redirect in controller action does not work?

I struggled with redirect not working for very long, none of what mentioned above was working for me, until I tried this:

Change:

return $this->redirect('site/secure');

to:

return $this->redirect(['site/secure']);

In other words, needed to enclose it within [] brackets! I am using PHP 7, might be the reason why?

What is the equivalent of Java's System.out.println() in Javascript?

There isn't one, at least, not unless you are using a "developer" tool of some kind in your browser, e.g. Firebug in Firefox or the Developer tools in Safari. Then you can usually use console.log.

If I'm doing something in, say, an iOS device, I might add a <div id="debug" /> and then log to it.

Pass multiple optional parameters to a C# function

C# 4.0 also supports optional parameters, which could be useful in some other situations. See this article.

Sample random rows in dataframe

Write one! Wrapping JC's answer gives me:

randomRows = function(df,n){
   return(df[sample(nrow(df),n),])
}

Now make it better by checking first if n<=nrow(df) and stopping with an error.

EXTRACT() Hour in 24 Hour format

select to_char(tran_datetime,'HH24') from test;

TO_CHAR(tran_datetime,'HH24')
------------------
16      

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

I really appreciate @raykrow's answer when one has this problem only in a test file! That is where I encountered it.

As it is often helpful to have another way to do something as a backup, I wanted to mention this technique that also works (instead of importing RouterTestingModule):

import { MockComponent } from 'ng2-mock-component';
. . .
TestBed.configureTestingModule({
  declarations: [
    MockComponent({
      selector: 'a',
      inputs: [ 'routerLink', 'routerLinkActiveOptions' ]
    }),
    . . .
  ]

(Typically, one would use routerLink on an <a> element but adjust the selector accordingly for other components.)

The second reason I wanted to mention this alternate solution is that, though it served me well in a number of spec files, I ran into a problem with it in one case:

Error: Template parse errors:
    More than one component matched on this element.
    Make sure that only one component's selector can match a given element.
    Conflicting components: ButtonComponent,Mock

I could not quite figure out how this mock and my ButtonComponent were using the same selector, so searching for an alternate approach led me here to @raykrow's solution.

How to declare a type as nullable in TypeScript?

Union type is in my mind best option in this case:

interface Employee{
   id: number;
   name: string;
   salary: number | null;
}

// Both cases are valid
let employe1: Employee = { id: 1, name: 'John', salary: 100 };
let employe2: Employee = { id: 1, name: 'John', salary: null };

EDIT : For this to work as expected, you should enable the strictNullChecks in tsconfig.

Finding square root without using sqrt function?

//long division method.
#include<iostream>
using namespace std;
int main() {
int n, i = 1, divisor, dividend, j = 1, digit;
cin >> n;
while (i * i < n) {
    i = i + 1;
}
i = i - 1;
cout << i << '.';

divisor  = 2 * i;
dividend = n - (i * i );
while( j <= 5) {
    dividend = dividend * 100;
    digit = 0;
    while ((divisor * 10 + digit) * digit < dividend) {
        digit = digit + 1;
    }
    digit = digit  - 1;
    cout << digit;
    dividend = dividend - ((divisor * 10 + digit) * digit);
    divisor = divisor * 10 + 2*digit;
    j = j + 1;
}
cout << endl;
return 0;
}

What is your single most favorite command-line trick using Bash?

I often have aliases for vi, ls, etc. but sometimes you want to escape the alias. Just add a back slash to the command in front:

Eg:

$ alias vi=vim
$ # To escape the alias for vi:
$ \vi # This doesn't open VIM

Cool, isn't it?

How do I delete specific characters from a particular String in Java?

To remove the last character do as Mark Byers said

s = s.substring(0, s.length() - 1);

Additionally, another way to remove the characters you don't want would be to use the .replace(oldCharacter, newCharacter) method.

as in:

s = s.replace(",","");

and

s = s.replace(".","");

How to retry image pull in a kubernetes Pods?

Usually in case of "ImagePullBackOff" it's retried after few seconds/minutes. In case you want to try again manually you can delete the old pod and recreate the pod. The one line command to delete and recreate the pod would be:

kubectl replace --force -f <yml_file_describing_pod>

document.all vs. document.getElementById

document.all is very old, you don't have to use it anymore.

To quote Nicholas Zakas:

For instance, when the DOM was young, not all browsers supported getElementById(), and so there was a lot of code that looked like this:

if(document.getElementById){  //DOM
    element = document.getElementById(id);
} else if (document.all) {  //IE
    element = document.all[id];
} else if (document.layers){  //Netscape < 6
    element = document.layers[id];
}

Getting first and last day of the current month

string firstdayofyear = new DateTime(DateTime.Now.Year, 1, 1).ToString("MM-dd-yyyy");
string lastdayofyear = new DateTime(DateTime.Now.Year, 12, 31).ToString("MM-dd-yyyy");
string firstdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("MM-dd-yyyy");
string lastdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1).ToString("MM-dd-yyyy");

Database cluster and load balancing

Database clustering is a bit of an ambiguous term, some vendors consider a cluster having two or more servers share the same storage, some others call a cluster a set of replicated servers.

Replication defines the method by which a set of servers remain synchronized without having to share the storage being able to be geographically disperse, there are two main ways of going about it:

  • master-master (or multi-master) replication: Any server can update the database. It is usually taken care of by a different module within the database (or a whole different software running on top of them in some cases).

    Downside is that it is very hard to do well, and some systems lose ACID properties when in this mode of replication.

    Upside is that it is flexible and you can support the failure of any server while still having the database updated.

  • master-slave replication: There is only a single copy of authoritative data, which is the pushed to the slave servers.

    Downside is that it is less fault tolerant, if the master dies, there are no further changes in the slaves.

    Upside is that it is easier to do than multi-master and it usually preserve ACID properties.

Load balancing is a different concept, it consists distributing the queries sent to those servers so the load is as evenly distributed as possible. It is usually done at the application layer (or with a connection pool). The only direct relation between replication and load balancing is that you need some replication to be able to load balance, else you'd have a single server.

When is each sorting algorithm used?

Quicksort is usually the fastest on average, but It has some pretty nasty worst-case behaviors. So if you have to guarantee no bad data gives you O(N^2), you should avoid it.

Merge-sort uses extra memory, but is particularly suitable for external sorting (i.e. huge files that don't fit into memory).

Heap-sort can sort in-place and doesn't have the worst case quadratic behavior, but on average is slower than quicksort in most cases.

Where only integers in a restricted range are involved, you can use some kind of radix sort to make it very fast.

In 99% of the cases, you'll be fine with the library sorts, which are usually based on quicksort.

Handling InterruptedException in Java

As it happens I was just reading about this this morning on my way to work in Java Concurrency In Practice by Brian Goetz. Basically he says you should do one of three things

  1. Propagate the InterruptedException - Declare your method to throw the checked InterruptedException so that your caller has to deal with it.

  2. Restore the Interrupt - Sometimes you cannot throw InterruptedException. In these cases you should catch the InterruptedException and restore the interrupt status by calling the interrupt() method on the currentThread so the code higher up the call stack can see that an interrupt was issued, and quickly return from the method. Note: this is only applicable when your method has "try" or "best effort" semantics, i. e. nothing critical would happen if the method doesn't accomplish its goal. For example, log() or sendMetric() may be such method, or boolean tryTransferMoney(), but not void transferMoney(). See here for more details.

  3. Ignore the interruption within method, but restore the status upon exit - e. g. via Guava's Uninterruptibles. Uninterruptibles take over the boilerplate code like in the Noncancelable Task example in JCIP § 7.1.3.

How can I check what version/edition of Visual Studio is installed programmatically?

Run the path in cmd C:\Program Files (x86)\Microsoft Visual Studio\Installer>vswhere.exe

Permission denied for relation

Connect to the right database first, then run:

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO jerry;

What is the difference between substr and substring?

let str = "Hello World"

console.log(str.substring(1, 3))  // el -> Excludes the last index
console.log(str.substr(1, 3))  // ell -> Includes the last index

How to define servlet filter order of execution using annotations in WAR

You can indeed not define the filter execution order using @WebFilter annotation. However, to minimize the web.xml usage, it's sufficient to annotate all filters with just a filterName so that you don't need the <filter> definition, but just a <filter-mapping> definition in the desired order.

For example,

@WebFilter(filterName="filter1")
public class Filter1 implements Filter {}

@WebFilter(filterName="filter2")
public class Filter2 implements Filter {}

with in web.xml just this:

<filter-mapping>
    <filter-name>filter1</filter-name>
    <url-pattern>/url1/*</url-pattern>
</filter-mapping>
<filter-mapping>
    <filter-name>filter2</filter-name>
    <url-pattern>/url2/*</url-pattern>
</filter-mapping>

If you'd like to keep the URL pattern in @WebFilter, then you can just do like so,

@WebFilter(filterName="filter1", urlPatterns="/url1/*")
public class Filter1 implements Filter {}

@WebFilter(filterName="filter2", urlPatterns="/url2/*")
public class Filter2 implements Filter {}

but you should still keep the <url-pattern> in web.xml, because it's required as per XSD, although it can be empty:

<filter-mapping>
    <filter-name>filter1</filter-name>
    <url-pattern />
</filter-mapping>
<filter-mapping>
    <filter-name>filter2</filter-name>
    <url-pattern />
</filter-mapping>

Regardless of the approach, this all will fail in Tomcat until version 7.0.28 because it chokes on presence of <filter-mapping> without <filter>. See also Using Tomcat, @WebFilter doesn't work with <filter-mapping> inside web.xml

How to disable text selection highlighting

If you want to disable selection and highlighting for the whole page you can easily do this with CSS:

* {
    -webkit-touch-callout: none; /* iOS Safari */
      -webkit-user-select: none; /* Safari */
       -khtml-user-select: none; /* Konqueror HTML */
         -moz-user-select: none; /* Firefox */
          -ms-user-select: none; /* Internet Explorer/Edge */
              user-select: none; /* Non-prefixed version, currently
                                    supported by Chrome and Opera */
}

Determine the number of lines within a text file

count the carriage returns/line feeds. I believe in unicode they are still 0x000D and 0x000A respectively. that way you can be as efficient or as inefficient as you want, and decide if you have to deal with both characters or not

How do you remove a specific revision in the git history?

I also landed in a similar situation. Use interactive rebase using the command below and while selecting, drop 3rd commit.

git rebase -i remote/branch

How to skip the first n rows in sql query

Do you want something like in LINQ skip 5 and take 10?

SELECT TOP(10) * FROM MY_TABLE  
WHERE ID not in (SELECT TOP(5) ID From My_TABLE);

This approach will work in any SQL version.

Can jQuery get all CSS styles associated with an element?

A couple years late, but here is a solution that retrieves both inline styling and external styling:

function css(a) {
    var sheets = document.styleSheets, o = {};
    for (var i in sheets) {
        var rules = sheets[i].rules || sheets[i].cssRules;
        for (var r in rules) {
            if (a.is(rules[r].selectorText)) {
                o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
            }
        }
    }
    return o;
}

function css2json(css) {
    var s = {};
    if (!css) return s;
    if (css instanceof CSSStyleDeclaration) {
        for (var i in css) {
            if ((css[i]).toLowerCase) {
                s[(css[i]).toLowerCase()] = (css[css[i]]);
            }
        }
    } else if (typeof css == "string") {
        css = css.split("; ");
        for (var i in css) {
            var l = css[i].split(": ");
            s[l[0].toLowerCase()] = (l[1]);
        }
    }
    return s;
}

Pass a jQuery object into css() and it will return an object, which you can then plug back into jQuery's $().css(), ex:

var style = css($("#elementToGetAllCSS"));
$("#elementToPutStyleInto").css(style);

:)

Getting the first character of a string with $str[0]

$str = 'abcdef';
echo $str[0];                 // a

Excel "External table is not in the expected format."

I had this same issue(Using the ACE.OLEDB) and what resolved it for me was this link:

http://support.microsoft.com/kb/2459087

The gist of it is that installing multiple office versions and various office sdk's, assemblies, etc. had led to the ACEOleDB.dll reference in the registry pointing to the OFFICE12 folder instead of OFFICE14 in

C:\Program Files\Common Files\Microsoft Shared\OFFICE14\ACEOLEDB.DLL

From the link:

Alternatively, you can modify the registry key changing the dll path to match that of your Access version.

Access 2007 should use OFFICE12, Access 2010 - OFFICE14 and Access 2013 - OFFICE15

(OS: 64bit Office: 64bit) or (OS: 32bit Office: 32bit)

Key: HKCR\CLSID{3BE786A0-0366-4F5C-9434-25CF162E475E}\InprocServer32\

Value Name: (Default)

Value Data: C:\Program Files\Common Files\Microsoft Shared\OFFICE14\ACEOLEDB.DLL

(OS: 64bit Office: 32bit)

Key: HKCR\Wow6432Node\CLSID{3BE786A0-0366-4F5C-9434-25CF162E475E}\InprocServer32\

Value Name: (Default)

Value Data: C:\Program Files (x86)\Common Files\Microsoft Shared\OFFICE14\ACEOLEDB.DLL

Changing line colors with ggplot()

color and fill are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:

d + scale_color_manual(values=c("#CC6666", "#9999CC"))

is what you want.

Why is php not running?

To answer the original question "Why is php not running?" The file your browser is asking for must have the .php extension. If the file has the .html extension, php will not be executed.

Scatter plot and Color mapping in Python

To add to wflynny's answer above, you can find the available colormaps here

Example:

import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.jet)

or alternatively,

plt.scatter(x, y, c=t, cmap='jet')

PostgreSQL wildcard LIKE for any of a list of words

One 'elegant' solution would be to use full text search: http://www.postgresql.org/docs/9.0/interactive/textsearch.html. Then you would use full text search queries.

compare two files in UNIX

Well, you can just sort the files first, and diff the sorted files.

sort file1 > file1.sorted
sort file2 > file2.sorted
diff file1.sorted file2.sorted

You can also filter the output to report lines in file2 which are absent from file1:

diff -u file1.sorted file2.sorted | grep "^+" 

As indicated in comments, you in fact do not need to sort the files. Instead, you can use a process substitution and say:

diff <(sort file1) <(sort file2)

Possible to access MVC ViewBag object from Javascript file?

In controllers action add:

 public ActionResult Index()
        {
            try
            {
                int a, b, c;
                a = 2; b = 2;
                c = a / b;
                ViewBag.ShowMessage = false;
            }
            catch (Exception e)
            {
                ViewBag.ShowMessage = true;
                ViewBag.data = e.Message.ToString();
            }
            return View();    // return View();

        }

in Index.cshtml
Place at the bottom:

<input type="hidden" value="@ViewBag.data" id="hdnFlag" />

@if (ViewBag.ShowMessage)
{
    <script type="text/javascript">

        var h1 = document.getElementById('hdnFlag');

        alert(h1.value);

    </script>
    <div class="message-box">Some Message here</div>
}

How to store .pdf files into MySQL as BLOBs using PHP?

EDITED TO ADD: The following code is outdated and won't work in PHP 7. See the note towards the bottom of the answer for more details.


Assuming a table structure of an integer ID and a blob DATA column, and assuming MySQL functions are being used to interface with the database, you could probably do something like this:

$result = mysql_query 'INSERT INTO table (
    data
) VALUES (
    \'' . mysql_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf')) . '\'
);';

A word of warning though, storing blobs in databases is generally not considered to be the best idea as it can cause table bloat and has a number of other problems associated with it. A better approach would be to move the file somewhere in the filesystem where it can be retrieved, and store the path to the file in the database instead of the file itself.

Also, using mysql_* function calls is discouraged as those methods are effectively deprecated and aren't really built with versions of MySQL newer than 4.x in mind. You should switch to mysqli or PDO instead.

UPDATE: mysql_* functions are deprecated in PHP 5.x and are REMOVED COMPLETELY IN PHP 7! You now have no choice but to switch to a more modern Database Abstraction (MySQLI, PDO). I've decided to leave the original answer above intact for historical reasons but don't actually use it

Here's how to do it with mysqli in procedural mode:

$result = mysqli_query ($db, 'INSERT INTO table (
    data
) VALUES (
    \'' . mysqli_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf'), $db) . '\'
);');

The ideal way of doing it is with MySQLI/PDO prepared statements.

What are the ways to sum matrix elements in MATLAB?

For very large matrices using sum(sum(A)) can be faster than sum(A(:)):

>> A = rand(20000);
>> tic; B=sum(A(:)); toc; tic; C=sum(sum(A)); toc
Elapsed time is 0.407980 seconds.
Elapsed time is 0.322624 seconds.

Edit and Continue: "Changes are not allowed when..."

That happens when the debugger hasn't hit a breakpoint or you haven't hit Break All (pause). It couldn't be that simple could it?

Auto-scaling input[type=text] to width of value?

try canvas measureText solution

css:

    input{
        min-width:10px!important;
        max-width:99.99%!important;
        transition: width 0.1s;
        border-width:1px;
    }

javascript:

function getWidthOfInput(input){
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    var text = input.value.length ? input.value : input.placeholder;
    var style = window.getComputedStyle(input);
    ctx.lineWidth = 1;
    ctx.font = style.font;
    var text_width = ctx.measureText(text).width;
    return text_width;
}

function resizable (el, factor) {
    function resize() {
        var width = getWidthOfInput(el);
        el.style.width = width + 'px';
    }
    var e = 'keyup,keypress,focus,blur,change'.split(',');
    for (var i in e){
        el.addEventListener(e[i],resize,false);
    }
    resize();
}

$( "input" ).each( function(i){
    resizable(this);
});

Using continue in a switch statement

This might be a megabit to late but you can use continue 2.

Some php builds / configs will output this warning:

PHP Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?

For example:

$i = 1;

while ($i <= 10) {
    $mod = $i % 4;
    echo "\r\n out $i";
    $i++;
    switch($mod)
    {
        case 0:
            break;
        case 2:
            continue;
            break;
        default:
            continue 2;
            break;
    }
    echo " is even";
}

This will output:

out 1
out 2 is even
out 3
out 4 is even
out 5
out 6 is even
out 7
out 8 is even
out 9
out 10 is even

Tested with PHP 5.5 and higher.

C++ Vector of pointers

I am not sure what the last line means. Does it mean, I read the file, create multiple Movie objects. Then make a vector of pointers where each element (pointer) points to one of those Movie objects?

I would guess this is what is intended. The intent is probably that you read the data for one movie, allocate an object with new, fill the object in with the data, and then push the address of the data onto the vector (probably not the best design, but most likely what's intended anyway).

Regular expression for first and last name

This regex work for me (was using in Angular 8) :

([a-zA-Z',.-]+( [a-zA-Z',.-]+)*){2,30}

enter image description here

It will be invalid if there is:-

  1. Any whitespace start or end of the name
  2. Got symbols e.g. @
  3. Less than 2 or more than 30

Example invalid First Name (whitespace)

enter image description here

Example valid First Name :

enter image description here

MomentJS getting JavaScript Date in UTC

A timestamp is a point in time. Typically this can be represented by a number of milliseconds past an epoc (the Unix Epoc of Jan 1 1970 12AM UTC). The format of that point in time depends on the time zone. While it is the same point in time, the "hours value" is not the same among time zones and one must take into account the offset from the UTC.

Here's some code to illustrate. A point is time is captured in three different ways.

var moment = require( 'moment' );

var localDate = new Date();
var localMoment = moment();
var utcMoment = moment.utc();
var utcDate = new Date( utcMoment.format() );

//These are all the same
console.log( 'localData unix = ' + localDate.valueOf() );
console.log( 'localMoment unix = ' + localMoment.valueOf() );
console.log( 'utcMoment unix = ' + utcMoment.valueOf() );

//These formats are different
console.log( 'localDate = ' + localDate );
console.log( 'localMoment string = ' + localMoment.format() );
console.log( 'utcMoment string = ' + utcMoment.format() );
console.log( 'utcDate  = ' + utcDate );

//One to show conversion
console.log( 'localDate as UTC format = ' + moment.utc( localDate ).format() );
console.log( 'localDate as UTC unix = ' + moment.utc( localDate ).valueOf() );

Which outputs this:

localData unix = 1415806206570
localMoment unix = 1415806206570
utcMoment unix = 1415806206570
localDate = Wed Nov 12 2014 10:30:06 GMT-0500 (EST)
localMoment string = 2014-11-12T10:30:06-05:00
utcMoment string = 2014-11-12T15:30:06+00:00
utcDate  = Wed Nov 12 2014 10:30:06 GMT-0500 (EST)
localDate as UTC format = 2014-11-12T15:30:06+00:00
localDate as UTC unix = 1415806206570

In terms of milliseconds, each are the same. It is the exact same point in time (though in some runs, the later millisecond is one higher).

As far as format, each can be represented in a particular timezone. And the formatting of that timezone'd string looks different, for the exact same point in time!

Are you going to compare these time values? Just convert to milliseconds. One value of milliseconds is always less than, equal to or greater than another millisecond value.

Do you want to compare specific 'hour' or 'day' values and worried they "came from" different timezones? Convert to UTC first using moment.utc( existingDate ), and then do operations. Examples of those conversions, when coming out of the DB, are the last console.log calls in the example.

SQL is null and = null

In SQL, a comparison between a null value and any other value (including another null) using a comparison operator (eg =, !=, <, etc) will result in a null, which is considered as false for the purposes of a where clause (strictly speaking, it's "not true", rather than "false", but the effect is the same).

The reasoning is that a null means "unknown", so the result of any comparison to a null is also "unknown". So you'll get no hit on rows by coding where my_column = null.

SQL provides the special syntax for testing if a column is null, via is null and is not null, which is a special condition to test for a null (or not a null).

Here's some SQL showing a variety of conditions and and their effect as per above.

create table t (x int, y int);
insert into t values (null, null), (null, 1), (1, 1);

select 'x = null' as test , x, y from t where x = null
union all
select 'x != null', x, y from t where x != null
union all
select 'not (x = null)', x, y from t where not (x = null)
union all
select 'x = y', x, y from t where x = y
union all
select 'not (x = y)', x, y from t where not (x = y);

returns only 1 row (as expected):

TEST    X   Y
x = y   1   1

See this running on SQLFiddle

how to use JSON.stringify and json_decode() properly

jsonText = $_REQUEST['myJSON'];

$decodedText = html_entity_decode($jsonText);

$myArray = json_decode($decodedText, true);`

ADB error: cannot connect to daemon

If nothing works Restart your PC . Restarting my computer does the trick

Disable scrolling in an iPhone web application?

'self.webView.scrollView.bounces = NO;'

Just add this one line in the 'viewDidLoad' of the mainViewController.m file of your application. you can open it in the Xcode and add it .

This should make the page without any rubberband bounces still enabling the scroll in the app view.

Importing xsd into wsdl

You have a couple of problems here.

First, the XSD has an issue where an element is both named or referenced; in your case should be referenced.

Change:

<xsd:element name="stock" ref="Stock" minOccurs="1" maxOccurs="unbounded"/> 

To:

<xsd:element name="stock" type="Stock" minOccurs="1" maxOccurs="unbounded"/> 

And:

  • Remove the declaration of the global element Stock
  • Create a complex type declaration for a type named Stock

So:

<xsd:element name="Stock">
    <xsd:complexType>

To:

<xsd:complexType name="Stock">

Make sure you fix the xml closing tags.

The second problem is that the correct way to reference an external XSD is to use XSD schema with import/include within a wsdl:types element. wsdl:import is reserved to referencing other WSDL files. More information is available by going through the WS-I specification, section WSDL and Schema Import. Based on WS-I, your case would be:

INCORRECT: (the way you showed it)

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <import namespace="http://stock.com/schemas/services/stock" location="Stock.xsd" />
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

CORRECT:

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <types>
        <schema xmlns="http://www.w3.org/2001/XMLSchema">
            <import namespace="http://stock.com/schemas/services/stock" schemaLocation="Stock.xsd" />             
        </schema>
    </types>
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

SOME processors may support both syntaxes. The XSD you put out shows issues, make sure you first validate the XSD.

It would be better if you go the WS-I way when it comes to WSDL authoring.

Other issues may be related to the use of relative vs. absolute URIs in locating external content.

What is the reason for a red exclamation mark next to my project in Eclipse?

There is a Problems view (try Window->Show View) which shows this kind of thing.

It's usually missing Jars (eg your project configuration references a jar that isn't there), and that kind of thing, in the case of JDT, but obviously these days Eclipse can be used in so many ways, it could be anything.

Rails DateTime.now without Time

You can use just:

Date.current

How to get file URL using Storage facade in laravel 5?

First get file url/link then path, as below:

$url = Storage::disk('public')->url($filename);
$path = public_path($url);

How do you select a particular option in a SELECT element in jQuery?

Using jquery-2.1.4, I found the following answer to work for me:

$('#MySelectionBox').val(123).change();

If you have a string value try the following:

$('#MySelectionBox').val("extra thing").change();

Other examples did not work for me so that's why I'm adding this answer.

I found the original answer at: https://forum.jquery.com/topic/how-to-dynamically-select-option-in-dropdown-menu

How to implement Android Pull-to-Refresh

The easiest way i think is as provided by the android support library:

android.support.v4.widget.SwipeRefreshLayout;

once that is imported then you can have your layout defined as follows:

  <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/refresh"
        android:layout_height="match_parent"
        android:layout_width="match_parent">
    <android.support.v7.widget.RecyclerView
        xmlns:recycler_view="http://schemas.android.com/apk/res-auto"
        android:id="@android:id/list"
        android:theme="@style/Theme.AppCompat.Light"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/button_material_light"
        >

    </android.support.v7.widget.RecyclerView>
</android.support.v4.widget.SwipeRefreshLayout>

I assume that you use recycler view instead of listview. However, listview still works so you just need to replace recyclerview with listview and update the references in the java code (Fragment).

In your activity fragment, you first implement the interface, SwipeRefreshLayout.OnRefreshListener: i,e

public class MySwipeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
private SwipeRefreshLayout swipeRefreshLayout;

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_item, container, false);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh);
        swipeRefreshLayout.setOnRefreshListener(this);
}


 @Override
  public void onRefresh(){
     swipeRefreshLayout.setRefreshing(true);
     refreshList();
  }
  refreshList(){
    //do processing to get new data and set your listview's adapter, maybe  reinitialise the loaders you may be using or so
   //when your data has finished loading, cset the refresh state of the view to false
   swipeRefreshLayout.setRefreshing(false);

   }
}

Hope this helps the masses

jQuery Uncaught TypeError: Cannot read property 'fn' of undefined (anonymous function)

I fixed it by added the jquery.slim.min.js after the jquery.min.js, as the Solution Sequence.

Problem Sequence

<script src="./vendor/jquery/jquery.min.js"></script>
<script src="./vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

Solution Sequence

<script src="./vendor/jquery/jquery.min.js"></script>
<script src="./vendor/jquery/jquery.slim.min.js"></script>
<script src="./vendor/jquery-easing/jquery.easing.min.js"></script>

Blurring an image via CSS?

With CSS3 we can easily adjust an image. But remember this does not change the image. It only displays the adjusted image.

See the following code for more details.

To make an image gray:

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

To give a sepia look:

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

To adjust brightness:

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

To adjust contrast:

img {
 -webkit-filter: contrast(200%);
}

To Blur an image:

img {
 -webkit-filter: blur(10px);
}

You should also do it for different browser. That is include all css statements

  filter: grayscale(100%);
 -webkit-filter: grayscale(100%);
 -moz-filter: grayscale(100%);

To use multiple

 filter: blur(5px) grayscale(1);

Codepen Demo

Converting a Uniform Distribution to a Normal Distribution

It seems incredible that I could add something to this after eight years, but for the case of Java I would like to point readers to the Random.nextGaussian() method, which generates a Gaussian distribution with mean 0.0 and standard deviation 1.0 for you.

A simple addition and/or multiplication will change the mean and standard deviation to your needs.

What is the best way to filter a Java Collection?

Let’s look at how to filter a built-in JDK List and a MutableList using Eclipse Collections.

List<Integer> jdkList = Arrays.asList(1, 2, 3, 4, 5);
MutableList<Integer> ecList = Lists.mutable.with(1, 2, 3, 4, 5);

If you wanted to filter the numbers less than 3, you would expect the following outputs.

List<Integer> selected = Lists.mutable.with(1, 2);
List<Integer> rejected = Lists.mutable.with(3, 4, 5);

Here’s how you can filter using a Java 8 lambda as the Predicate.

Assert.assertEquals(selected, Iterate.select(jdkList, each -> each < 3));
Assert.assertEquals(rejected, Iterate.reject(jdkList, each -> each < 3));

Assert.assertEquals(selected, ecList.select(each -> each < 3));
Assert.assertEquals(rejected, ecList.reject(each -> each < 3));

Here’s how you can filter using an anonymous inner class as the Predicate.

Predicate<Integer> lessThan3 = new Predicate<Integer>()
{
    public boolean accept(Integer each)
    {
        return each < 3;
    }
};

Assert.assertEquals(selected, Iterate.select(jdkList, lessThan3));
Assert.assertEquals(selected, ecList.select(lessThan3));

Here are some alternatives to filtering JDK lists and Eclipse Collections MutableLists using the Predicates factory.

Assert.assertEquals(selected, Iterate.select(jdkList, Predicates.lessThan(3)));
Assert.assertEquals(selected, ecList.select(Predicates.lessThan(3)));

Here is a version that doesn't allocate an object for the predicate, by using the Predicates2 factory instead with the selectWith method that takes a Predicate2.

Assert.assertEquals(
    selected, ecList.selectWith(Predicates2.<Integer>lessThan(), 3));

Sometimes you want to filter on a negative condition. There is a special method in Eclipse Collections for that called reject.

Assert.assertEquals(rejected, Iterate.reject(jdkList, lessThan3));
Assert.assertEquals(rejected, ecList.reject(lessThan3));

The method partition will return two collections, containing the elements selected by and rejected by the Predicate.

PartitionIterable<Integer> jdkPartitioned = Iterate.partition(jdkList, lessThan3);
Assert.assertEquals(selected, jdkPartitioned.getSelected());
Assert.assertEquals(rejected, jdkPartitioned.getRejected());

PartitionList<Integer> ecPartitioned = gscList.partition(lessThan3);
Assert.assertEquals(selected, ecPartitioned.getSelected());
Assert.assertEquals(rejected, ecPartitioned.getRejected());

Note: I am a committer for Eclipse Collections.

Is there an addHeaderView equivalent for RecyclerView?

First - extends RecyclerView.Adapter<RecyclerView.ViewHolder>

public class MenuAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

After - Override the method getItemViewTpe ***More Important

@Override
public int getItemViewType(int position) {
    return position;
}

method onCreateViewHolder

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.menu_item, parent, false);
    View header = LayoutInflater.from(parent.getContext()).inflate(R.layout.menu_header_item, parent, false);
    Log.d("onCreateViewHolder", String.valueOf(viewType));

    if (viewType == 0) {
        return new MenuLeftHeaderViewHolder(header, onClickListener);
    } else {
        return new MenuLeftViewHolder(view, onClickListener);
    }
}

method onBindViewHolder

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    if (position == 0) {
        MenuHeaderViewHolder menuHeaderViewHolder = (MenuHeaderViewHolder) holder;
        menuHeaderViewHolder.mTitle.setText(sMenuTitles[position]);
        menuHeaderViewHolder.mImage.setImageResource(sMenuImages[position]);
    } else {
        MenuViewHolder menuLeftViewHolder = (MenuLeftViewHolder) holder;
        menuViewHolder.mTitle.setText(sMenuTitles[position]);
        menuViewHolder.mImage.setImageResource(sMenuImages[position]);
    }
}

in finish implements the ViewHolders class static

public static class MenuViewHolder extends RecyclerView.ViewHolder 

public static class MenuLeftHeaderViewHolder extends RecyclerView.ViewHolder 

How to get a value from a cell of a dataframe?

It doesn't need to be complicated:

val = df.loc[df.wd==1, 'col_name'].values[0]

How do I exit the Vim editor?

Before you enter a command, hit the Esc key. After you enter it, hit the Return to confirm.

Esc finishes the current command and switches Vim to normal mode. Now if you press :, the : will appear at the bottom of the screen. This confirms that you're actually typing a command and not editing the file.

Most commands have abbreviations, with optional part enclosed in brackets: c[ommand].

Commands marked with '*' are Vim-only (not implemented in Vi).

Safe-quit (fails if there are unsaved changes):

  • :q[uit] Quit the current window. Quit Vim if this is the last window. This fails when changes have been made in current buffer.
  • :qa[ll]* Quit all windows and Vim, unless there are some buffers which have been changed.

Prompt-quit (prompts if there are unsaved changes)

  • :conf[irm] q[uit]* Quit, but give prompt when there are some buffers which have been changed.
  • :conf[irm] xa[ll]* Write all changed buffers and exit Vim. Bring up a prompt when some buffers cannot be written.

Write (save) changes and quit:

  • :wq Write the current file (even if it was not changed) and quit. Writing fails when the file is read-only or the buffer does not have a name. :wqa[ll]* for all windows.
  • :wq! The same, but writes even read-only files. :wqa[ll]!* for all windows.
  • :x[it], ZZ(with details). Write the file only if it was changed and quit, :xa[ll]* for all windows.

Discard changes and quit:

  • :q[uit]! ZQ* Quit without writing, also when visible buffers have changes. Does not exit when there are changed hidden buffers.
  • :qa[ll]!*, :quita[ll][!]* Quit Vim, all changes to the buffers (including hidden) are lost.

Press Return to confirm the command.

This answer doesn't reference all Vim write and quit commands and arguments. Indeed, they are referenced in the Vim documentation.

Vim has extensive built-in help, type Esc:helpReturn to open it.

This answer was inspired by the other one, originally authored by @dirvine and edited by other SO users. I've included more information from Vim reference, SO comments and some other sources. Differences for Vi and Vim are reflected too.

Two-dimensional array in Swift

Make it Generic Swift 4

struct Matrix<T> {
    let rows: Int, columns: Int
    var grid: [T]
    init(rows: Int, columns: Int,defaultValue: T) {
        self.rows = rows
        self.columns = columns
        grid = Array(repeating: defaultValue, count: rows * columns) as! [T]
    }
    func indexIsValid(row: Int, column: Int) -> Bool {
        return row >= 0 && row < rows && column >= 0 && column < columns
    }
    subscript(row: Int, column: Int) -> T {
        get {
            assert(indexIsValid(row: row, column: column), "Index out of range")
            return grid[(row * columns) + column]
        }
        set {
            assert(indexIsValid(row: row, column: column), "Index out of range")
            grid[(row * columns) + column] = newValue
        }
    }
}


var matrix:Matrix<Bool> = Matrix(rows: 1000, columns: 1000,defaultValue:false)

matrix[0,10] = true


print(matrix[0,10])

Spring Boot: Cannot access REST Controller on localhost (404)

I had this issue and what you need to do is fix your packages. If you downloaded this project from http://start.spring.io/ then you have your main class in some package. For example if the package for the main class is: "com.example" then and your controller must be in package: "com.example.controller". Hope this helps.

JavaScriptSerializer.Deserialize - how to change field names

Json.NET will do what you want (disclaimer: I'm the author of the package). It supports reading DataContract/DataMember attributes as well as its own to change the property names. Also there is the StringEnumConverter class for serializing enum values as the name rather than the number.

How to install VS2015 Community Edition offline

If you are a MSDN subscriber follow the steps below:

  1. Go to msdn.microsoft.com and sign in.

  2. Go to Programs->Subscriptions->Overview

  3. Click on Subscriber Access

  4. Click on Product Keys ( Claim key as needed)

  5. Select your Visual Studio Preference.

  6. click the EXE drop down list, and select DVD. This will change it to an .ISO image.By default the web installer is selected,

  7. Click green download button(approximately 7.12Gb)

note: I used a Virtual-CloneDrive-5.5 to mount this ISO and install

Maven plugins can not be found in IntelliJ

If an artefact is not resolvable Go in the ditectory of your .m2/repository and check that you DON'T have that kind of file :

build-helper-maven-plugin-1.10.pom.lastUpdated

If you don't have any artefact in the folder, just deleted it, and try again to re-import in IntelliJ.

the content of those file is like :

#NOTE: This is an Aether internal implementation file, its format can be changed without prior notice.
#Fri Mar 10 10:36:12 CET 2017
@default-central-https\://repo.maven.apache.org/maven2/.lastUpdated=1489138572430
https\://repo.maven.apache.org/maven2/.error=Could not transfer artifact org.codehaus.mojo\:build-helper-maven-plugin\:pom\:1.10 from/to central (https\://repo.maven.apache.org/maven2)\: connect timed out

Without the *.lastUpdated file, IntelliJ (or Eclipse by the way) is enable to reload what is missing.

Open Cygwin at a specific folder

I made a .reg file that puts an "Open Cygwin Here" option in the right-click context menu. It depends on the Cygwin "chere" package, which you can install using apt-cyg if you didn't install it in the initial setup.

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\Background\shell\cygwin_bash]
@="Open Cygwin Here"

[HKEY_CLASSES_ROOT\Directory\Background\shell\cygwin_bash\command]
@="C:\\cygwin\\bin\\mintty.exe -e /bin/xhere /bin/bash.exe"

How do I turn off the output from tar commands on Unix?

Just drop the option v.

-v is for verbose. If you don't use it then it won't display:

tar -zxf tmp.tar.gz -C ~/tmp1

How do you add a scroll bar to a div?

If you want to add a scroll bar using jquery the following will work. If your div had a id of 'mydiv' you could us the following jquery id selector with css property:

jQuery('#mydiv').css("overflow-y", "scroll");

How to pass multiple parameters in json format to a web service using jquery?

i have same issue and resolved by

 data: "Id1=" + id1 + "&Id2=" + id2

/bin/sh: pushd: not found

here is a method to point

sh -> bash

run this command on terminal

sudo dpkg-reconfigure dash

After this you should see

ls -l /bin/sh

point to /bin/bash (and not to /bin/dash)

Reference

Running multiple async tasks and waiting for them all to complete

You could create many tasks like:

List<Task> TaskList = new List<Task>();
foreach(...)
{
   var LastTask = new Task(SomeFunction);
   LastTask.Start();
   TaskList.Add(LastTask);
}

Task.WaitAll(TaskList.ToArray());

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

Expanding on C. Dragon 76's popular answer by making his code into an extension that overloads the default Replace method.

public static class StringExtensions
{
    public static string Replace(this string str, string oldValue, string newValue, StringComparison comparison)
    {
        StringBuilder sb = new StringBuilder();

        int previousIndex = 0;
        int index = str.IndexOf(oldValue, comparison);
        while (index != -1)
        {
            sb.Append(str.Substring(previousIndex, index - previousIndex));
            sb.Append(newValue);
            index += oldValue.Length;

            previousIndex = index;
            index = str.IndexOf(oldValue, index, comparison);
        }
        sb.Append(str.Substring(previousIndex));
        return sb.ToString();
     }
}

What is python's site-packages directory?

site-packages is the target directory of manually built Python packages. When you build and install Python packages from source (using distutils, probably by executing python setup.py install), you will find the installed modules in site-packages by default.

There are standard locations:

  • Unix (pure)1: prefix/lib/pythonX.Y/site-packages
  • Unix (non-pure): exec-prefix/lib/pythonX.Y/site-packages
  • Windows: prefix\Lib\site-packages

1 Pure means that the module uses only Python code. Non-pure can contain C/C++ code as well.

site-packages is by default part of the Python search path, so modules installed there can be imported easily afterwards.


Useful reading

Export from pandas to_excel without row names (index)?

Example: index = False

import pandas as pd

writer = pd.ExcelWriter("dataframe.xlsx", engine='xlsxwriter')
dataframe.to_excel(writer,sheet_name = dataframe, index=False)
writer.save() 

How to start IIS Express Manually

Or you simply manage it like full IIS by using Jexus Manager for IIS Express, an open source project I work on

https://jexusmanager.com

Jexus Manager for IIS Express

Start a site and the process will be launched for you.

OSX - How to auto Close Terminal window after the "exit" command executed.

If this is a Mac you type 'exit' then press return.

Why is my xlabel cut off in my matplotlib plot?

You can also set custom padding as defaults in your $HOME/.matplotlib/matplotlib_rc as follows. In the example below I have modified both the bottom and left out-of-the-box padding:

# The figure subplot parameters.  All dimensions are a fraction of the
# figure width or height
figure.subplot.left  : 0.1 #left side of the subplots of the figure
#figure.subplot.right : 0.9 
figure.subplot.bottom : 0.15
...

How to remove specific session in asp.net?

There are many ways to nullify session in ASP.NET. Session in essence is a cookie, set on client's browser and in ASP.NET, its name is usually ASP.NET_SessionId. So, theoretically if you delete that cookie (which in terms of browser means that you set its expiration date to some date in past, because cookies can't be deleted by developers), then you loose the session in server. Another way as you said is to use Session.Clear() method. But the best way is to set another irrelevant object (usually null value) in the session in correspondance to a key. For example, to nullify Session["FirstName"], simply set it to Session["FirstName"] = null.

JSON Java 8 LocalDateTime format in Spring Boot

I am using Spring Boot 2.1.8. I have imported

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-json</artifactId>
</dependency>

which includes the jackson-datatype-jsr310.

Then, I had to add these annotations

@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonProperty("date")
LocalDateTime getDate();

and it works. The JSON looks like this:

"date": "2020-03-09 17:55:00"

System.drawing namespace not found under console application

For,Adding System.Drawing Follow some steps: Firstly, right click on the solution and click on add Reference. Secondly, Select the .NET Folder. And then double click on the Using.System.Drawing;

RadioGroup: How to check programmatically

try this if you want your radio button to be checked based on value of some variable e.g. "genderStr" then you can use following code snippet

    if(genderStr.equals("Male"))
       genderRG.check(R.id.maleRB);
    else 
       genderRG.check(R.id.femaleRB);

Passing by reference in C

In C, Pass-by-reference is simulated by passing the address of a variable (a pointer) and dereferencing that address within the function to read or write the actual variable. This will be referred to as "C style pass-by-reference."

Source: www-cs-students.stanford.edu

How to do a SOAP Web Service call from Java class?

Or just use Apache CXF's wsdl2java to generate objects you can use.

It is included in the binary package you can download from their website. You can simply run a command like this:

$ ./wsdl2java -p com.mynamespace.for.the.api.objects -autoNameResolution http://www.someurl.com/DefaultWebService?wsdl

It uses the wsdl to generate objects, which you can use like this (object names are also grabbed from the wsdl, so yours will be different a little):

DefaultWebService defaultWebService = new DefaultWebService();
String res = defaultWebService.getDefaultWebServiceHttpSoap11Endpoint().login("webservice","dadsadasdasd");
System.out.println(res);

There is even a Maven plug-in which generates the sources: https://cxf.apache.org/docs/maven-cxf-codegen-plugin-wsdl-to-java.html

Note: If you generate sources using CXF and IDEA, you might want to look at this: https://stackoverflow.com/a/46812593/840315

Failed to resolve: com.android.support:appcompat-v7:27.+ (Dependency Error)

If you are using Android Studio 3.0 or above make sure your project build.gradle should have content similar to-

buildscript {                 
    repositories {
        google()
        jcenter()
    }
    dependencies {            
        classpath 'com.android.tools.build:gradle:3.0.1'

    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

Note- position really matters add google() before jcenter()

And for below Android Studio 3.0 and starting from support libraries 26.+ your project build.gradle must look like this-

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

check these links below for more details-

1- Building Android Apps

2- Add Build Dependencies

3- Configure Your Build

Change a Nullable column to NOT NULL with Default Value

You may have to first update all the records that are null to the default value then use the alter table statement.

Update dbo.TableName
Set
Created="01/01/2000"
where Created is NULL

Regex: Check if string contains at least one digit

This:

\d+

should work

Edit, no clue why I added the "+", without it works just as fine.

\d

How to use jQuery to select a dropdown option?

I prefer nth-child() to eq() as it uses 1-based indexing rather than 0-based, which is slightly easier on my brain.

//selects the 2nd option
$('select>option:nth-child(2)').attr('selected', true);

pip install mysql-python fails with EnvironmentError: mysql_config not found

If you are on MAC Install this globally

brew install mysql

then export path like this

export PATH=$PATH:/usr/local/mysql/bin

Than globally or in your venv whatever you like

pip install MySQL-Python

Note: globally for python3 as Mac can have both python2 & 3

pip3 install MySQL-Python

Using CSS to affect div style inside iframe

Apparently it can be done via jQuery:

$('iframe').load( function() {
    $('iframe').contents().find("head")
      .append($("<style type='text/css'>  .my-class{display:none;}  </style>"));
});

https://stackoverflow.com/a/13959836/1625795

Most efficient way to concatenate strings?

There are 6 types of string concatenations:

  1. Using the plus (+) symbol.
  2. Using string.Concat().
  3. Using string.Join().
  4. Using string.Format().
  5. Using string.Append().
  6. Using StringBuilder.

In an experiment, it has been proved that string.Concat() is the best way to approach if the words are less than 1000(approximately) and if the words are more than 1000 then StringBuilder should be used.

For more information, check this site.

string.Join() vs string.Concat()

The string.Concat method here is equivalent to the string.Join method invocation with an empty separator. Appending an empty string is fast, but not doing so is even faster, so the string.Concat method would be superior here.

Transfer data between iOS and Android via Bluetooth?

This question has been asked many times on this site and the definitive answer is: NO, you can't connect an Android phone to an iPhone over Bluetooth, and YES Apple has restrictions that prevent this.

Some possible alternatives:

  1. Bonjour over WiFi, as you mentioned. However, I couldn't find a comprehensive tutorial for it.
  2. Some internet based sync service, like Dropbox, Google Drive, Amazon S3. These usually have libraries for several platforms.
  3. Direct TCP/IP communication over sockets. (How to write a small (socket) server in iOS)
  4. Bluetooth Low Energy will be possible once the issues on the Android side are solved (Communicating between iOS and Android with Bluetooth LE)

Coolest alternative: use the Bump API. It has iOS and Android support and really easy to integrate. For small payloads this can be the most convenient solution.

Details on why you can't connect an arbitrary device to the iPhone. iOS allows only some bluetooth profiles to be used without the Made For iPhone (MFi) certification (HPF, A2DP, MAP...). The Serial Port Profile that you would require to implement the communication is bound to MFi membership. Membership to this program provides you to the MFi authentication module that has to be added to your hardware and takes care of authenticating the device towards the iPhone. Android phones don't have this module, so even though the physical connection may be possible to build up, the authentication step will fail. iPhone to iPhone communication is possible as both ends are able to authenticate themselves.

"Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page

If your API code is running on a node.js server then you need to focus your attention there, not in Apache or NGINX. Mikel is right, changing the API URL to HTTPS is the answer but if your API is calling a node.js server, it better be set up for HTTPS! And of course, the node.js server can be on any unused port, it doesn't have to be port 443.

Can't connect to Postgresql on port 5432

You probably need to either open up the port to access it in your LAN (or outside of it) or bind the network address to the port (make PostgreSQL listen on your LAN instead of just on localhost)

jQuery Validate Plugin - Trigger validation of single field

in case u wanna do the validation for "some elements" (not all element) on your form.You can use this method:

$('input[name="element-one"], input[name="element-two"], input[name="element-three"]').valid();

Hope it help everybody :)

EDITED

What is The difference between ListBox and ListView

A ListView is basically like a ListBox (and inherits from it), but it also has a View property. This property allows you to specify a predefined way of displaying the items. The only predefined view in the BCL (Base Class Library) is GridView, but you can easily create your own.

Another difference is the default selection mode: it's Single for a ListBox, but Extended for a ListView

MySQL user DB does not have password columns - Installing MySQL on OSX

For this problem, I used a simple and rude method, rename the field name to password, the reason for this is that I use the mac navicat premium software in the visual operation error: Unknown column 'password' in 'field List ', the software itself uses password so that I can not easily operate. Therefore, I root into the database command line, run

Use mysql;

And then modify the field name:

ALTER TABLE user CHANGE authentication_string password text;

After all normal.

Export data from R to Excel

I have been trying out the different packages including the function:

install.packages ("prettyR") 

library (prettyR)

delimit.table (Corrvar,"Name the csv.csv") ## Corrvar is a name of an object from an output I had on scaled variables to run a regression.

However I tried this same code for an output from another analysis (occupancy models model selection output) and it did not work. And after many attempts and exploration I:

  • copied the output from R (Ctrl+c)
  • in Excel sheet I pasted it (Ctrl+V)
  • Select the first column where the data is
  • In the "Data" vignette, click on "Text to column"

  • Select Delimited option, click next

  • Tick space box in "Separator", click next

  • Click Finalize (End)

Your output now should be in a form you can manipulate easy in excel. So perhaps not the fanciest option but it does the trick if you just want to explore your data in another way.

PS. If the labels in excel are not the exact one it is because Im translating the lables from my spanish excel.

In Django, how do I check if a user is in a certain group?

I have done it the following way. Seems inefficient but I had no other way in my mind:

@login_required
def list_track(request):

usergroup = request.user.groups.values_list('name', flat=True).first()
if usergroup in 'appAdmin':
    tracks = QuestionTrack.objects.order_by('pk')
    return render(request, 'cmit/appadmin/list_track.html', {'tracks': tracks})

else:
    return HttpResponseRedirect('/cmit/loggedin')

How can I verify if one list is a subset of another?

The performant function Python provides for this is set.issubset. It does have a few restrictions that make it unclear if it's the answer to your question, however.

A list may contain items multiple times and has a specific order. A set does not. Additionally, sets only work on hashable objects.

Are you asking about subset or subsequence (which means you'll want a string search algorithm)? Will either of the lists be the same for many tests? What are the datatypes contained in the list? And for that matter, does it need to be a list?

Your other post intersect a dict and list made the types clearer and did get a recommendation to use dictionary key views for their set-like functionality. In that case it was known to work because dictionary keys behave like a set (so much so that before we had sets in Python we used dictionaries). One wonders how the issue got less specific in three hours.

Insert line break inside placeholder attribute of a textarea?

very simple

  var position = your break position;
    var breakLine = "&#13;&#10;";//in html 
    var output = [value.slice(0, position), breakLine, value.slice(position)].join('');
    return output;

value represent the original string

How do I float a div to the center?

Try margin: 0 auto, the div will need a fixed with.

'MOD' is not a recognized built-in function name

If using JDBC driver you may use function escape sequence like this:

select {fn MOD(5, 2)}
#Result 1

select  mod(5, 2)
#SQL Error [195] [S00010]: 'mod' is not a recognized built-in function name.

How to find which columns contain any NaN value in Pandas dataframe

This worked for me,

1. For getting Columns having at least 1 null value. (column names)

data.columns[data.isnull().any()]

2. For getting Columns with count, with having at least 1 null value.

data[data.columns[data.isnull().any()]].isnull().sum()

[Optional] 3. For getting percentage of the null count.

data[data.columns[data.isnull().any()]].isnull().sum() * 100 / data.shape[0]

Is there an auto increment in sqlite?

SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto incrementing it.

The keyword AUTOINCREMENT can be used with INTEGER field only. Syntax:

The basic usage of AUTOINCREMENT keyword is as follows:

CREATE TABLE table_name(
   column1 INTEGER AUTOINCREMENT,
   column2 datatype,
   column3 datatype,
   .....
   columnN datatype,
);

For Example See Below: Consider COMPANY table to be created as follows:

sqlite> CREATE TABLE TB_COMPANY_INFO(
   ID INTEGER PRIMARY KEY   AUTOINCREMENT,
   NAME           TEXT      NOT NULL,
   AGE            INT       NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL
);

Now, insert following records into table TB_COMPANY_INFO:

INSERT INTO TB_COMPANY_INFO (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'MANOJ KUMAR', 40, 'Meerut,UP,INDIA', 200000.00 );

Now Select the record

SELECT *FROM TB_COMPANY_INFO
ID      NAME            AGE     ADDRESS             SALARY
1       Manoj Kumar     40      Meerut,UP,INDIA     200000.00

Shell script to set environment variables

Run the script as source= to run in debug mode as well.

source= ./myscript.sh

Exploitable PHP functions

What about dangerous syntactic elements?

The "variable variable" ($$var) will find a variable in the current scope by the name of $var. If used wrong, the remote user can modify or read any variable in the current scope. Basically a weaker eval.

Ex: you write some code $$uservar = 1;, then the remote user sets $uservar to "admin", causing $admin to be set to 1 in the current scope.

Auto margins don't center image in page

Under some circumstances (such as earlier versions of IE, Gecko, Webkit) and inheritance, elements with position:relative; will prevent margin:0 auto; from working, even if top, right, bottom, and left aren't set.

Setting the element to position:static; (the default) may fix it under these circumstances. Generally, block level elements with a specified width will respect margin:0 auto; using either relative or static positioning.

Split and join C# string

You can use string.Split and string.Join:

string theString = "Some Very Large String Here";
var array = theString.Split(' ');
string firstElem = array.First();
string restOfArray = string.Join(" ", array.Skip(1));

If you know you always only want to split off the first element, you can use:

var array = theString.Split(' ', 2);

This makes it so you don't have to join:

string restOfArray = array[1];

How to set the env variable for PHP?

Try display phpinfo() by file and check this var.

Save array in mysql database

Use the PHP function serialize() to convert arrays to strings. These strings can easily be stored in MySQL database. Using unserialize() they can be converted to arrays again if needed.

execute function after complete page load

window.onload = () => {
  // run in onload
  setTimeout(() => {
    // onload finished.
    // and execute some code here like stat performance.
  }, 10)
}

What is an uber jar?

Über is the German word for above or over (it's actually cognate with the English over).

Hence, in this context, an uber-jar is an "over-jar", one level up from a simple JAR (a), defined as one that contains both your package and all its dependencies in one single JAR file. The name can be thought to come from the same stable as ultrageek, superman, hyperspace, and metadata, which all have similar meanings of "beyond the normal".

The advantage is that you can distribute your uber-jar and not care at all whether or not dependencies are installed at the destination, as your uber-jar actually has no dependencies.

All the dependencies of your own stuff within the uber-jar are also within that uber-jar. As are all dependencies of those dependencies. And so on.


(a) I probably shouldn't have to explain what a JAR is to a Java developer but I'll include it for completeness. It's a Java archive, basically a single file that typically contains a number of Java class files along with associated metadata and resources.

How do you round a number to two decimal places in C#?

Wikipedia has a nice page on rounding in general.

All .NET (managed) languages can use any of the common language run time's (the CLR) rounding mechanisms. For example, the Math.Round() (as mentioned above) method allows the developer to specify the type of rounding (Round-to-even or Away-from-zero). The Convert.ToInt32() method and its variations use round-to-even. The Ceiling() and Floor() methods are related.

You can round with custom numeric formatting as well.

Note that Decimal.Round() uses a different method than Math.Round();

Here is a useful post on the banker's rounding algorithm. See one of Raymond's humorous posts here about rounding...

How to write a file or data to an S3 object using boto3

You may use the below code to write, for example an image to S3 in 2019. To be able to connect to S3 you will have to install AWS CLI using command pip install awscli, then enter few credentials using command aws configure:

import urllib3
import uuid
from pathlib import Path
from io import BytesIO
from errors import custom_exceptions as cex

BUCKET_NAME = "xxx.yyy.zzz"
POSTERS_BASE_PATH = "assets/wallcontent"
CLOUDFRONT_BASE_URL = "https://xxx.cloudfront.net/"


class S3(object):
    def __init__(self):
        self.client = boto3.client('s3')
        self.bucket_name = BUCKET_NAME
        self.posters_base_path = POSTERS_BASE_PATH

    def __download_image(self, url):
        manager = urllib3.PoolManager()
        try:
            res = manager.request('GET', url)
        except Exception:
            print("Could not download the image from URL: ", url)
            raise cex.ImageDownloadFailed
        return BytesIO(res.data)  # any file-like object that implements read()

    def upload_image(self, url):
        try:
            image_file = self.__download_image(url)
        except cex.ImageDownloadFailed:
            raise cex.ImageUploadFailed

        extension = Path(url).suffix
        id = uuid.uuid1().hex + extension
        final_path = self.posters_base_path + "/" + id
        try:
            self.client.upload_fileobj(image_file,
                                       self.bucket_name,
                                       final_path
                                       )
        except Exception:
            print("Image Upload Error for URL: ", url)
            raise cex.ImageUploadFailed

        return CLOUDFRONT_BASE_URL + id

Datatype for storing ip address in SQL Server

For people using .NET can use IPAddress class to parse IPv4/IPv6 string and store it as a VARBINARY(16). Can use the same class to convert byte[] to string. If want to convert the VARBINARY in SQL:

--SELECT 
--  dbo.varbinaryToIpString(CAST(0x7F000001 AS VARBINARY(4))) IPv4,
--  dbo.varbinaryToIpString(CAST(0x20010DB885A3000000008A2E03707334 AS VARBINARY(16))) IPv6

--ALTER 
CREATE
FUNCTION dbo.varbinaryToIpString
(
    @varbinaryValue VARBINARY(16)
)
RETURNS VARCHAR(39)
AS
BEGIN
    IF @varbinaryValue IS NULL
        RETURN NULL
    IF DATALENGTH(@varbinaryValue) = 4
    BEGIN
        RETURN 
            CONVERT(VARCHAR(3), CONVERT(INT, SUBSTRING(@varbinaryValue, 1, 1))) + '.' +
            CONVERT(VARCHAR(3), CONVERT(INT, SUBSTRING(@varbinaryValue, 2, 1))) + '.' +
            CONVERT(VARCHAR(3), CONVERT(INT, SUBSTRING(@varbinaryValue, 3, 1))) + '.' +
            CONVERT(VARCHAR(3), CONVERT(INT, SUBSTRING(@varbinaryValue, 4, 1)))
    END
    IF DATALENGTH(@varbinaryValue) = 16
    BEGIN
        RETURN 
            sys.fn_varbintohexsubstring(0, @varbinaryValue,  1, 2) + ':' +
            sys.fn_varbintohexsubstring(0, @varbinaryValue,  3, 2) + ':' +
            sys.fn_varbintohexsubstring(0, @varbinaryValue,  5, 2) + ':' +
            sys.fn_varbintohexsubstring(0, @varbinaryValue,  7, 2) + ':' +
            sys.fn_varbintohexsubstring(0, @varbinaryValue,  9, 2) + ':' +
            sys.fn_varbintohexsubstring(0, @varbinaryValue, 11, 2) + ':' +
            sys.fn_varbintohexsubstring(0, @varbinaryValue, 13, 2) + ':' +
            sys.fn_varbintohexsubstring(0, @varbinaryValue, 15, 2)
    END

    RETURN 'Invalid'
END

Best practices for SQL varchar column length

Whenever I set up a new SQL table I feel the same way about 2^n being more "even"... but to sum up the answers here, there is no significant impact on storage space simply by defining varchar(2^n) or even varchar(MAX).

That said, you should still anticipate the potential implications on storage and performance when setting a high varchar() limit. For example, let's say you create a varchar(MAX) column to hold product descriptions with full-text indexing. If 99% of descriptions are only 500 characters long, and then suddenly you get somebody who replaces said descriptions with wikipedia articles, you may notice unanticipated significant storage and performance hits.

Another thing to consider from Bill Karwin:

There's one possible performance impact: in MySQL, temporary tables and MEMORY tables store a VARCHAR column as a fixed-length column, padded out to its maximum length. If you design VARCHAR columns much larger than the greatest size you need, you will consume more memory than you have to. This affects cache efficiency, sorting speed, etc.

Basically, just come up with reasonable business constraints and error on a slightly larger size. As @onedaywhen pointed out, family names in UK are usually between 1-35 characters. If you decide to make it varchar(64), you're not really going to hurt anything... unless you're storing this guy's family name that's said to be up to 666 characters long. In that case, maybe varchar(1028) makes more sense.

And in case it's helpful, here's what varchar 2^5 through 2^10 might look like if filled:

varchar(32)     Lorem ipsum dolor sit amet amet.

varchar(64)     Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie

varchar(128)    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas

varchar(256)    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
                velit metus, sit amet tristique purus condimentum eleifend. Quis
                que mollis magna vel massa malesuada bibendum. Proinde tincidunt

varchar(512)    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
                velit metus, sit amet tristique purus condimentum eleifend. Quis
                que mollis magna vel massa malesuada bibendum. Proinde tincidunt
                dolor tellus, sit amet porta neque varius vitae. Seduse molestie
                lacus id lacinia tempus. Vestibulum accumsan facilisis lorem, et
                mollis diam pretium gravida. In facilisis vitae tortor id vulput
                ate. Proin ornare arcu in sollicitudin pharetra. Crasti molestie

varchar(1024)   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
                velit metus, sit amet tristique purus condimentum eleifend. Quis
                que mollis magna vel massa malesuada bibendum. Proinde tincidunt
                dolor tellus, sit amet porta neque varius vitae. Seduse molestie
                lacus id lacinia tempus. Vestibulum accumsan facilisis lorem, et
                mollis diam pretium gravida. In facilisis vitae tortor id vulput
                ate. Proin ornare arcu in sollicitudin pharetra. Crasti molestie
                dapibus leo lobortis eleifend. Vivamus vitae diam turpis. Vivamu
                nec tristique magna, vel tincidunt diam. Maecenas elementum semi
                quam. In ut est porttitor, sagittis nulla id, fermentum turpist.
                Curabitur pretium nibh a imperdiet cursus. Sed at vulputate este
                proin fermentum pretium justo, ac malesuada eros et Pellentesque
                vulputate hendrerit molestie. Aenean imperdiet a enim at finibus
                fusce ut ullamcorper risus, a cursus massa. Nunc non dapibus vel
                Lorem ipsum dolor sit amet, consectetur Praesent ut ultrices sit

Get item in the list in Scala?

Use parentheses:

data(2)

But you don't really want to do that with lists very often, since linked lists take time to traverse. If you want to index into a collection, use Vector (immutable) or ArrayBuffer (mutable) or possibly Array (which is just a Java array, except again you index into it with (i) instead of [i]).

Android: Go back to previous activity

Got the same problem and

finish();  OR super.onBackPressed();

worked fine for me, both worked same, but no luck with return

Validate fields after user has left a field

If you use bootstrap 3 and lesscss you can enable on blur validation with the following less snippet:

:focus ~ .form-control-feedback.glyphicon-ok {
  display:none;
}

:focus ~ .form-control-feedback.glyphicon-remove {
  display:none;
}

.has-feedback > :focus {
  & {
    .form-control-focus();
  }
}

PHP: Split a string in to an array foreach char

You can access a string using [], as you do for arrays:

$stringLength = strlen($str);
for ($i = 0; $i < $stringLength; $i++)
    $char = $str[$i];

Redirect within component Angular 2

This worked for me Angular cli 6.x:

import {Router} from '@angular/router';

constructor(private artistService: ArtistService, private router: Router) { }

  selectRow(id: number): void{
       this.router.navigate([`./artist-detail/${id}`]);

  }

How to change values in a tuple?

based on Jon's Idea and dear Trufa

def modifyTuple(tup, oldval, newval):
    lst=list(tup)
    for i in range(tup.count(oldval)):
        index = lst.index(oldval)
        lst[index]=newval

    return tuple(lst)

print modTupByIndex((1, 1, 3), 1, "a")

it changes all of your old values occurrences

Change the URL in the browser without loading the new page using JavaScript

jQuery has a great plugin for changing browsers' URL, called jQuery-pusher.

JavaScript pushState and jQuery could be used together, like:

history.pushState(null, null, $(this).attr('href'));

Example:

$('a').click(function (event) {

  // Prevent default click action
  event.preventDefault();     

  // Detect if pushState is available
  if(history.pushState) {
    history.pushState(null, null, $(this).attr('href'));
  }
  return false;
});

Using only JavaScript history.pushState(), which changes the referrer, that gets used in the HTTP header for XMLHttpRequest objects created after you change the state.

Example:

window.history.pushState("object", "Your New Title", "/new-url");

The pushState() method:

pushState() takes three parameters: a state object, a title (which is currently ignored), and (optionally) a URL. Let's examine each of these three parameters in more detail:

  1. state object — The state object is a JavaScript object which is associated with the new history entry created by pushState(). Whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object.

    The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restarts her browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to pushState(), the method will throw an exception. If you need more space than this, you're encouraged to use sessionStorage and/or localStorage.

  2. title — Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state to which you're moving.

  3. URL — The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts her browser. The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception. This parameter is optional; if it isn't specified, it's set to the document's current URL.

$_SERVER['HTTP_REFERER'] missing

Referer is not a compulsory header. It may or may not be there or could be modified/fictitious. Rely on it at your own risk. Anyways, you should wrap your call so you do not get an undefined index error:

$server = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : "";

How To limit the number of characters in JTextField?

I have solved this problem by using the following code segment:

private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {
    boolean max = jTextField1.getText().length() > 4;
    if ( max ){
        evt.consume();
    }        
}