Programs & Examples On #Ctype

php & mysql query not echoing in html with tags?

I can spot a few different problems with this. However, in the interest of time, try this chunk of code instead:

<?php require 'db.php'; ?>  <?php if (isset($_POST['search'])) {     $limit = $_POST['limit'];     $country = $_POST['country'];     $state = $_POST['state'];     $city = $_POST['city'];     $data = mysqli_query(         $link,         "SELECT * FROM proxies WHERE country = '{$country}' AND state = '{$state}' AND city = '{$city}' LIMIT {$limit}"     );     while ($assoc = mysqli_fetch_assoc($data)) {         $proxy = $assoc['proxy'];         ?>             <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"                 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">             <html xmlns="http://www.w3.org/1999/xhtml">                 <head>                     <title>Sock5Proxies</title>                     <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />                     <link href="./style.css" rel="stylesheet" type="text/css" />                     <link href="./buttons.css" rel="stylesheet" type="text/css" />                 </head>                 <body>                     <center>                         <h1>Sock5Proxies</h1>                     </center>                     <div id="wrapper">                         <div id="header">                             <ul id="nav">                                 <li class="active"><a href="index.html"><span></span>Home</a></li>                                 <li><a href="leads.html"><span></span>Leads</a></li>                                 <li><a href="payout.php"><span></span>Pay out</a></li>                                 <li><a href="contact.html"><span></span>Contact</a></li>                                 <li><a href="logout.php"><span></span>Logout</a></li>                             </ul>                         </div>                         <div id="content">                             <div id="center">                                 <table cellpadding="0" cellspacing="0" style="width:690px">                                     <thead>                                     <tr>                                         <th width="75" class="first">Proxy</th>                                         <th width="50" class="last">Status</th>                                     </tr>                                     </thead>                                     <tbody>                                     <tr class="rowB">                                         <td class="first"> <?php echo $proxy ?> </td>                                         <td class="last">Check</td>                                     </tr>                                     </tbody>                                 </table>                             </div>                         </div>                         <div id="footer"></div>                         <span id="about">Version 1.0</span>                     </div>                 </body>             </html>         <?php     } } ?> <html> <form action="" method="POST">     <input type="text" name="limit" placeholder="10" /><br>     <input type="text" name="country" placeholder="Country" /><br>     <input type="text" name="state" placeholder="State" /><br>     <input type="text" name="city" placeholder="City" /><br>     <input type="submit" name="search" value="Search" /><br> </form> </html> 

DevTools failed to load SourceMap: Could not load content for chrome-extension

I appreciate this is part of your extensions, but I see this message in all sorts of places these days, and I hate it: how I fixed it (EDIT: this fix seems to massively speed up the browser too) was by adding a dead file

  1. physically create the file it wants\ where it wants, as a blank file (EG: "popper.min.js.map")

  2. put this in the blank file

    {
     "version": 1,
     "mappings": "",
     "sources": [],
     "names": [],
     "file": "popper.min.js"
    }
    
  3. make sure that "file": "*******" in the content of the blank file MATCHES the name of your file ******.map (minus the word ".map")

(EDIT: I suspect you could physically add this dead file method to the addon yourself)

How can I execute a python script from an html button?

Since you asked for a way to complete this within an HTML page I am answering this. I feel there is no need to mention the severe warnings and implications that would go along with this .. I trust you know the security of your .py script better than I do :-)

I would use the .ajax() function in the jQuery library. This will allow you to call your Python script as long as the script is in the publicly accessible html directory ... That said this is the part where I tell you to heed security precautions ...

<!DOCTYPE html>
<html>
  <head>    
  </head>
  <body>
    <input type="button" id='script' name="scriptbutton" value=" Run Script " onclick="goPython()">

    <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

    <script>
        function goPython(){
            $.ajax({
              url: "MYSCRIPT.py",
             context: document.body
            }).done(function() {
             alert('finished python script');;
            });
        }
    </script>
  </body>
</html>

In addition .. It's worth noting that your script is going to have to have proper permissions for, say, the www-data user to be able to run it ... A chmod, and/or a chown may be necessary.

Failed to load resource: the server responded with a status of 404 (Not Found) css

Use the following Code:-

../css/main.css

Note: The "../" is shorthand for "The containing directory", or "Up one directory".

If you don't know the previous folder this will be very helpful..

Can't install laravel installer via composer

zip extension is missing, You can avoid this error by simple running below command, It will take version by default

sudo apt-get install php-zip

In case you need any specific version, You need to mention a specific version of your php, Suppose I need to install X version of php-zip then the command will be.

sudo apt-get install phpX-zip  

Replace X with your required version, In my case, it is X = 7.3

Django - Reverse for '' not found. '' is not a valid view function or pattern name

In my case, what I did was a mistake in the url tag in the respective template. So, in my url tag I had something like

{% url 'polls:details' question.id %}

while in the views, I had written something like:

def details(request, question_id): code here

So, the first thing you might wanna check is whether things are spelled as they shoould be. The next thing then you can do is as the people above have suggested.

PHP7 : install ext-dom issue

For CentOS, RHEL, Fedora:

$ yum search php-xml
============================================================================================================ N/S matched: php-xml ============================================================================================================
php-xml.x86_64 : A module for PHP applications which use XML
php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php-xmlseclibs.noarch : PHP library for XML Security
php54-php-xml.x86_64 : A module for PHP applications which use XML
php54-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php55-php-xml.x86_64 : A module for PHP applications which use XML
php55-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php56-php-xml.x86_64 : A module for PHP applications which use XML
php56-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php70-php-xml.x86_64 : A module for PHP applications which use XML
php70-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php71-php-xml.x86_64 : A module for PHP applications which use XML
php71-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php72-php-xml.x86_64 : A module for PHP applications which use XML
php72-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php73-php-xml.x86_64 : A module for PHP applications which use XML
php73-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol

Then select the php-xml version matching your php version:

# php -v
PHP 7.2.11 (cli) (built: Oct 10 2018 10:00:29) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies

# sudo yum install -y php72-php-xml.x86_64

How to post a file from a form with Axios

Sample application using Vue. Requires a backend server running on localhost to process the request:

var app = new Vue({
  el: "#app",
  data: {
    file: ''
  },
  methods: {
    submitFile() {
      let formData = new FormData();
      formData.append('file', this.file);
      console.log('>> formData >> ', formData);

      // You should have a server side REST API 
      axios.post('http://localhost:8080/restapi/fileupload',
          formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }
        ).then(function () {
          console.log('SUCCESS!!');
        })
        .catch(function () {
          console.log('FAILURE!!');
        });
    },
    handleFileUpload() {
      this.file = this.$refs.file.files[0];
      console.log('>>>> 1st element in files array >>>> ', this.file);
    }
  }
});

https://codepen.io/pmarimuthu/pen/MqqaOE

laravel 5.4 upload image

i think better to do this

    if ( $request->hasFile('file')){
        if ($request->file('file')->isValid()){
            $file = $request->file('file');
            $name = $file->getClientOriginalName();
            $file->move('images' , $name);
            $inputs = $request->all();
            $inputs['path'] = $name;
        }
    }
    Post::create($inputs);

actually images is folder that laravel make it automatic and file is name of the input and here we store name of the image in our path column in the table and store image in public/images directory

Laravel: PDOException: could not find driver

First check php -m
.If you don't see mysql driver install mysql sudo apt-cache search php-mysql
Your results will be similar to:

php-mysql - MySQL module for PHP [default]


install php- mysql Driver

sudo apt-get install php7.1-mysql

Chrome violation : [Violation] Handler took 83ms of runtime

Perhaps a little off topic, just be informed that these kind of messages can also be seen when you are debugging your code with a breakpoint inside an async function like setTimeout like below:

[Violation] 'setTimeout' handler took 43129ms

That number (43129ms) depends on how long you stop in your async function

`col-xs-*` not working in Bootstrap 4

I just wondered, why col-xs-6 did not work for me but then I found the answer in the Bootstrap 4 documentation. The class prefix for extra small devices is now col- while in the previous versions it was col-xs.

https://getbootstrap.com/docs/4.1/layout/grid/#grid-options

Bootstrap 4 dropped all col-xs-* classes, so use col-* instead. For example col-xs-6 replaced by col-6.

Bootstrap 4 responsive tables won't take up 100% width

None of these answers are working (date today 9th Dec 2018). The correct resolution here is to add .table-responsive-sm to your table:

<table class='table table-responsive-sm'>
[Your table]
</table>

This applies the responsiveness aspect only to the SM view (mobile). So in mobile view you get the scrolling as desired and in larger views the table is not responsive and thus displayed full width, as desired.

Docs: https://getbootstrap.com/docs/4.0/content/tables/#breakpoint-specific

Vue v-on:click does not work on component

A bit verbose but this is how I do it:

@click="$emit('click', $event)"

UPDATE: Example added by @sparkyspider

<div-container @click="doSomething"></div-container>

In div-container component...

<template>
  <div @click="$emit('click', $event);">The inner div</div>
</template>

Bootstrap footer at the bottom of the page

Use this stylesheet:

_x000D_
_x000D_
/* Sticky footer styles_x000D_
-------------------------------------------------- */_x000D_
html {_x000D_
  position: relative;_x000D_
  min-height: 100%;_x000D_
}_x000D_
body {_x000D_
  /* Margin bottom by footer height */_x000D_
  margin-bottom: 60px;_x000D_
}_x000D_
.footer {_x000D_
  position: absolute;_x000D_
  bottom: 0;_x000D_
  width: 100%;_x000D_
  /* Set the fixed height of the footer here */_x000D_
  height: 60px;_x000D_
  line-height: 60px; /* Vertically center the text there */_x000D_
  background-color: #f5f5f5;_x000D_
}_x000D_
_x000D_
_x000D_
/* Custom page CSS_x000D_
-------------------------------------------------- */_x000D_
/* Not required for template or sticky footer method. */_x000D_
_x000D_
body > .container {_x000D_
  padding: 60px 15px 0;_x000D_
}_x000D_
_x000D_
.footer > .container {_x000D_
  padding-right: 15px;_x000D_
  padding-left: 15px;_x000D_
}_x000D_
_x000D_
code {_x000D_
  font-size: 80%;_x000D_
}
_x000D_
_x000D_
_x000D_

Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator)

The livereload plugin fails to serve cordova.js file and serves // mock cordova file during development.

FIX: You need go to node_modules/@ionic/app-scripts/dist/dev-server/serve-config.js

and replace

exports.ANDROID_PLATFORM_PATH = path.join('platforms', 'android', 'assets', 'www');

to

exports.ANDROID_PLATFORM_PATH = path.join('platforms', 'android', 'app', 'src', 'main', 'assets', 'www');

Angular 2 : No NgModule metadata found

After upgrading to Angular 6, I encountered the "ERROR in No NgModule metadata found for 'AppModule'." with the angular-bootstrap-md package, which requires a tsconfig.json "include" as follows:

"include": ["node_modules/angular-bootstrap-md/**/*.ts", "src/**/*.ts"],

After days of troubleshooting and hair pulling, the solution was to arrange the list so that the app.module.ts was located first, under "src/**/*.ts". An Angular bug, perhaps?

"include": ["src/**/*.ts","node_modules/angular-bootstrap-md/**/*.ts" ],

I genuinely hope this helps somebody, as I tried everything in this posting and nothing helped. After this change, everything compiles and works beautifully, as expected.

Extension gd is missing from your system - laravel composer Update

Before installing the missing dependency, you need to check which version of PHP is installed on your system.

php -v
PHP 7.2.10-0ubuntu0.18.04.1 (cli) (built: Sep 13 2018 13:45:02) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.2.10-0ubuntu0.18.04.1, Copyright (c) 1999-2018, by Zend Technologies

In this case it's php7.2. apt search php7.2 returns all the available PHP extensions.

apt search php7.2
Sorting... Done
Full Text Search... Done
libapache2-mod-php7.2/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  server-side, HTML-embedded scripting language (Apache 2 module)

libphp7.2-embed/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  HTML-embedded scripting language (Embedded SAPI library)

php-all-dev/bionic,bionic 1:60ubuntu1 all
  package depending on all supported PHP development packages

php7.2/bionic-updates,bionic-updates,bionic-security,bionic-security 7.2.10-0ubuntu0.18.04.1 all
  server-side, HTML-embedded scripting language (metapackage)

php7.2-bcmath/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  Bcmath module for PHP

php7.2-bz2/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  bzip2 module for PHP

php7.2-cgi/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  server-side, HTML-embedded scripting language (CGI binary)

php7.2-cli/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed,automatic]
  command-line interpreter for the PHP scripting language

php7.2-common/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed,automatic]
  documentation, examples and common module for PHP

php7.2-curl/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed]
  CURL module for PHP

php7.2-dba/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  DBA module for PHP

php7.2-dev/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  Files for PHP7.2 module development

php7.2-enchant/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  Enchant module for PHP

php7.2-fpm/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed]
  server-side, HTML-embedded scripting language (FPM-CGI binary)

php7.2-gd/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed]
  GD module for PHP

php7.2-gmp/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  GMP module for PHP

php7.2-imap/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  IMAP module for PHP

php7.2-interbase/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  Interbase module for PHP

php7.2-intl/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  Internationalisation module for PHP

php7.2-json/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed,automatic]
  JSON module for PHP

php7.2-ldap/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  LDAP module for PHP

php7.2-mbstring/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed,automatic]
  MBSTRING module for PHP

php7.2-mysql/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  MySQL module for PHP

php7.2-odbc/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  ODBC module for PHP

php7.2-opcache/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed,automatic]
  Zend OpCache module for PHP

php7.2-pgsql/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  PostgreSQL module for PHP

php7.2-phpdbg/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  server-side, HTML-embedded scripting language (PHPDBG binary)

php7.2-pspell/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  pspell module for PHP

php7.2-readline/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed,automatic]
  readline module for PHP

php7.2-recode/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  recode module for PHP

php7.2-snmp/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  SNMP module for PHP

php7.2-soap/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  SOAP module for PHP

php7.2-sqlite3/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed]
  SQLite3 module for PHP

php7.2-sybase/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  Sybase module for PHP

php7.2-tidy/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  tidy module for PHP

php7.2-xml/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed]
  DOM, SimpleXML, WDDX, XML, and XSL module for PHP

php7.2-xmlrpc/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  XMLRPC-EPI module for PHP

php7.2-xsl/bionic-updates,bionic-updates,bionic-security,bionic-security 7.2.10-0ubuntu0.18.04.1 all
  XSL module for PHP (dummy)

php7.2-zip/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  Zip module for PHP

You can now proceed to installing the missing dependency by running:

sudo apt install php7.2-gd

why $(window).load() is not working in jQuery?

in jquery-3.1.1

_x000D_
_x000D_
$("#id").load(function(){_x000D_
//code goes here});
_x000D_
_x000D_
_x000D_

will not work because load function is no more work

Angular 2 / 4 / 5 - Set base href dynamically

If you are using Angular CLI 6, you can use the deployUrl/baseHref options in angular.json (projects > xxx > architect > build > configurations > production). In this way, you can easily specify the baseUrl per project.

Check that your settings are correct by looking at the index.html of the built app.

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

"Object doesn't support property or method 'find'" in IE

As mentioned array.find() is not supported in IE.

However you can read about a Polyfill here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find#Polyfill

This method has been added to the ECMAScript 2015 specification and may not be available in all JavaScript implementations yet. However, you can polyfill Array.prototype.find with the following snippet:

Code:

// https://tc39.github.io/ecma262/#sec-array.prototype.find
if (!Array.prototype.find) {
  Object.defineProperty(Array.prototype, 'find', {
    value: function(predicate) {
     // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If IsCallable(predicate) is false, throw a TypeError exception.
      if (typeof predicate !== 'function') {
        throw new TypeError('predicate must be a function');
      }

      // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
      var thisArg = arguments[1];

      // 5. Let k be 0.
      var k = 0;

      // 6. Repeat, while k < len
      while (k < len) {
        // a. Let Pk be ! ToString(k).
        // b. Let kValue be ? Get(O, Pk).
        // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
        // d. If testResult is true, return kValue.
        var kValue = o[k];
        if (predicate.call(thisArg, kValue, k, o)) {
          return kValue;
        }
        // e. Increase k by 1.
        k++;
      }

      // 7. Return undefined.
      return undefined;
    }
  });
}

This page didn't load Google Maps correctly. See the JavaScript console for technical details

Google recently changed the terms of use of its Google Maps APIs; if you were already using them on a website (different from localhost) prior to June 22nd, 2016, nothing will change for you; otherwise, you will get the aforementioned issue and need an API key in order to fix your error. The free API key is valid up to 25,000 map loads per day.

In this article you will find everything you may need to know regarding the topic, including a tutorial to fix your error:

Google Maps API error: MissingKeyMapError [SOLVED]

Also, remember to replace YOUR_API_KEY with your actual API key!

PHP: Inserting Values from the Form into MySQL

The following code just declares a string variable that contains a MySQL query:

$sql = "INSERT INTO users (username, password, email)
    VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";

It does not execute the query. In order to do that you need to use some functions but let me explain something else first.

NEVER TRUST USER INPUT: You should never append user input (such as form input from $_GET or $_POST) directly to your query. Someone can carefully manipulate the input in such a way so that it can cause great damage to your database. That's called SQL Injection. You can read more about it here

To protect your script from such an attack you must use Prepared Statements. More on prepared statements here

Include prepared statements to your code like this:

$sql = "INSERT INTO users (username, password, email)
    VALUES (?,?,?)";

Notice how the ? are used as placeholders for the values. Next you should prepare the statement using mysqli_prepare:

$stmt = mysqli_prepare($sql);

Then start binding the input variables to the prepared statement:

$stmt->bind_param("sss", $_POST['username'], $_POST['email'], $_POST['password']);

And finally execute the prepared statements. (This is where the actual insertion takes place)

$stmt->execute();

NOTE Although not part of the question, I strongly advice you to never store passwords in clear text. Instead you should use password_hash to store a hash of the password

getting error while updating Composer

After installing packages from given answers, i still get some errors then i install following package and it works fine:

  • php-xml

for specific version:

  • php7.0-xml

command for php 7.0

sudo apt-get install php7.0-xml

in some cases you also needs a package php7.0-common . install it same as above command.

Vue is not defined

try to fix type="JavaScript" to type="text/javascript" in you vue.js srcipt tag, or just remove it. Modern browsers will take script tag as javascript as default.

how to find array size in angularjs

Just use the length property of a JavaScript array like so:

$scope.names.length

Also, I don't see a starting <script> tag in your code.

If you want the length inside your view, do it like so:

{{ names.length }}

PHP 7 simpleXML

For Alpine (in docker), you can use apk add php7-simplexml.

If that doesn't work for you, you can run apk add --no-cache php7-simplexml. This is in case you aren't updating the package index first.

Angular 2 / 4 / 5 not working in IE11

What worked for me is I followed the following steps to improve my application perfomance in IE 11 1.) In Index.html file, add the following CDN's

<script src="https://npmcdn.com/[email protected] 
 beta.17/es6/dev/src/testing/shims_for_IE.js"></script>
<script 
src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.2.201711092/classList.min.js"></script>

2.) In polyfills.ts file and add the following import:

import 'core-js/client/shim';

Forward X11 failed: Network error: Connection refused

PuTTY can't find where your X server is, because you didn't tell it. (ssh on Linux doesn't have this problem because it runs under X so it just uses that one.) Fill in the blank box after "X display location" with your Xming server's address.

Alternatively, try MobaXterm. It has an X server builtin.

How to import jquery using ES6 syntax?

The accepted answer did not work for me
note : using rollup js dont know if this answer belongs here
after
npm i --save jquery
in custom.js

import {$, jQuery} from 'jquery';

or

import {jQuery as $} from 'jquery';

i was getting error : Module ...node_modules/jquery/dist/jquery.js does not export jQuery
or
Module ...node_modules/jquery/dist/jquery.js does not export $
rollup.config.js

export default {
    entry: 'source/custom',
    dest: 'dist/custom.min.js',
    plugins: [
        inject({
            include: '**/*.js',
            exclude: 'node_modules/**',
            jQuery: 'jquery',
            // $: 'jquery'
        }),
        nodeResolve({
            jsnext: true,
        }),
        babel(),
        // uglify({}, minify),
    ],
    external: [],
    format: 'iife', //'cjs'
    moduleName: 'mycustom',
};

instead of rollup inject, tried

commonjs({
   namedExports: {
     // left-hand side can be an absolute path, a path
     // relative to the current directory, or the name
     // of a module in node_modules
     // 'node_modules/jquery/dist/jquery.js': [ '$' ]
     // 'node_modules/jquery/dist/jquery.js': [ 'jQuery' ]
        'jQuery': [ '$' ]
},
format: 'cjs' //'iife'
};

package.json

  "devDependencies": {
    "babel-cli": "^6.10.1",
    "babel-core": "^6.10.4",
    "babel-eslint": "6.1.0",
    "babel-loader": "^6.2.4",
    "babel-plugin-external-helpers": "6.18.0",
    "babel-preset-es2015": "^6.9.0",
    "babel-register": "6.9.0",
    "eslint": "2.12.0",
    "eslint-config-airbnb-base": "3.0.1",
    "eslint-plugin-import": "1.8.1",
    "rollup": "0.33.0",
    "rollup-plugin-babel": "2.6.1",
    "rollup-plugin-commonjs": "3.1.0",
    "rollup-plugin-inject": "^2.0.0",
    "rollup-plugin-node-resolve": "2.0.0",
    "rollup-plugin-uglify": "1.0.1",
    "uglify-js": "2.7.0"
  },
  "scripts": {
    "build": "rollup -c",
  },

This worked :
removed the rollup inject and commonjs plugins

import * as jQuery from 'jquery';

then in custom.js

$(function () {
        console.log('Hello jQuery');
});

How can I set the font-family & font-size inside of a div?

You need a semicolon after font-family: Arial, Helvetica, sans-serif. This will make your updated code the following:

<!DOCTYPE>
<html>
    <head>
        <title>DIV Font</title>

        <style>
            .my_text
            {
                font-family:    Arial, Helvetica, sans-serif;
                font-size:      40px;
                font-weight:    bold;
            }
        </style>
    </head>

    <body>
        <div class="my_text">some text</div>
    </body>
</html>

Passing string parameter in JavaScript function

document.write(`<td width='74'><button id='button' type='button' onclick='myfunction(\``+ name + `\`)'>click</button></td>`)

Better to use `` than "". This is a more dynamic answer.

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

I am new to spring spent an hour trying to figure this out.

go to --- > application.properties

add these :

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

Node Multer unexpected field

The <NAME> you use in multer's upload.single(<NAME>) function must be the same as the one you use in <input type="file" name="<NAME>" ...>.

So you need to change

var type = upload.single('file')

to

var type = upload.single('recfile')

in you app.js

Hope this helps.

Unexpected token < in first line of HTML

Your page references a Javascript file at /Client/public/core.js.

This file probably can't be found, producing either the website's frontpage or an HTML error page instead. This is a pretty common issue for eg. websites running on an Apache server where paths are redirected by default to index.php.

If that's the case, make sure you replace /Client/public/core.js in your script tag <script type="text/javascript" src="/Client/public/core.js"></script> with the correct file path or put the missing file core.js at location /Client/public/ to fix your error!

If you do already find a file named core.js at /Client/public/ and the browser still produces a HTML page instead, check the permissions for folder and file. Either of these might be lacking the proper permissions.

How to display Woocommerce product price by ID number on a custom page?

In woocommerce,

Get regular price :

$price = get_post_meta( get_the_ID(), '_regular_price', true);
// $price will return regular price

Get sale price:

$sale = get_post_meta( get_the_ID(), '_sale_price', true);
// $sale will return sale price

BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

You guys copied the wrong code.

Go into the "/build" folder and grab the jquery.datetimepicker.full.js or jquery.datetimepicker.full.min.js if you want the minified version. It should fix it! :)

what is <meta charset="utf-8">?

That meta tag basically specifies which character set a website is written with.

Here is a definition of UTF-8:

UTF-8 (U from Universal Character Set + Transformation Format—8-bit) is a character encoding capable of encoding all possible characters (called code points) in Unicode. The encoding is variable-length and uses 8-bit code units.

Netbeans 8.0.2 The module has not been deployed

UPDATE: this was solved by rebooting but there was another error when running app. This time tomcat woudnt start. To solve this (bugs with latest apache and netbeans versions) follow: Error starting Tomcat from NetBeans - '127.0.0.1*' is not recognized as an internal or external command

No log4j2 configuration file found. Using default configuration: logging only errors to the console

Tested with: log4j-ap 2.13.2, log4j-core 2.13.2.

  1. Keep XML file directly under below folder structure. src/main/java
  2. In the POM:
    <build>   
 <resources>       
             <resource>
                <filtering>false</filtering>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>             
            </resource>
 </resources>  
</build>
  1. Clean and build.

HTML img align="middle" doesn't align an image

Try this:

style="margin: auto"

How can I validate google reCAPTCHA v2 using javascript/jQuery?

I used Palek's solution inside a Bootstrap validator and it works. I'd have added a comment to his but I don'y have the rep;). Simplified version:

        $('#form').validator().on('submit', function (e) {
           var response = grecaptcha.getResponse();
           //recaptcha failed validation
           if(response.length == 0) {
               e.preventDefault();
               $('#recaptcha-error').show();
           }
           //recaptcha passed validation
           else {
               $('#recaptcha-error').hide();
           }
           if (e.isDefaultPrevented()) {
              return false;
           } else {
              return true;
           }
       });

How can I run a html file from terminal?

Skip reading the html and use curl to POST whatever form data you want to submit to the server.

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

If you are running server already, don't forget to use http:// in the API call. This might cause a serious trouble.

Position buttons next to each other in the center of page

jsfiddle: http://jsfiddle.net/mgtoz4d3/

I added a container which contains both buttons. Try this:

CSS:

#button1{
    width: 300px;
    height: 40px;
}
#button2{
    width: 300px;
    height: 40px;
}
#container{
    text-align: center;
}

HTML:

<img src="kingstonunilogo.jpg" alt="uni logo" style="width:180px;height:160px">
<br><br>
<div id="container">
    <button type="button home-button" id="button1" >Home</button>
    <button type="button contact-button" id="button2">Contact Us</button>
</div>

Simple Popup by using Angular JS

If you are using bootstrap.js then the below code might be useful. This is very simple. Dont have to write anything in js to invoke the pop-up.

Source :http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

</div>

</body>
</html>

How to read files from resources folder in Scala?

For Scala 2.11, if getLines doesn't do exactly what you want you can also copy the a file out of the jar to the local file system.

Here's a snippit that reads a binary google .p12 format API key from /resources, writes it to /tmp, and then uses the file path string as an input to a spark-google-spreadsheets write.

In the world of sbt-native-packager and sbt-assembly, copying to local is also useful with scalatest binary file tests. Just pop them out of resources to local, run the tests, and then delete.

import java.io.{File, FileOutputStream}
import java.nio.file.{Files, Paths}

def resourceToLocal(resourcePath: String) = {
  val outPath = "/tmp/" + resourcePath
  if (!Files.exists(Paths.get(outPath))) {
    val resourceFileStream = getClass.getResourceAsStream(s"/${resourcePath}")
    val fos = new FileOutputStream(outPath)
    fos.write(
      Stream.continually(resourceFileStream.read).takeWhile(-1 !=).map(_.toByte).toArray
    )
    fos.close()
  }
  outPath
}

val filePathFromResourcesDirectory = "google-docs-key.p12"
val serviceAccountId = "[something]@drive-integration-[something].iam.gserviceaccount.com"
val googleSheetId = "1nC8Y3a8cvtXhhrpZCNAsP4MBHRm5Uee4xX-rCW3CW_4"
val tabName = "Favorite Cities"

import spark.implicits
val df = Seq(("Brooklyn", "New York"), 
          ("New York City", "New York"), 
          ("San Francisco", "California")).
          toDF("City", "State")

df.write.
  format("com.github.potix2.spark.google.spreadsheets").
  option("serviceAccountId", serviceAccountId).
  option("credentialPath", resourceToLocal(filePathFromResourcesDirectory)).
  save(s"${googleSheetId}/${tabName}")

Error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

It's actually a simple answer.

Your function is returning a string rather than the div node. appendChild can only append a node.

For example, if you try to appendChild the string:

var z = '<p>test satu dua tiga</p>'; // is a string 
document.body.appendChild(z);

The above code will never work. What will work is:

var z = document.createElement('p'); // is a node
z.innerHTML = 'test satu dua tiga';
document.body.appendChild(z);

Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing

Refer to this thread or this thread, for customized installation of libffi, it is difficult for Python3.7 to find the library location of libffi. An alternative method is to set the CONFIGURE_LDFLAGS variable in the Makefile, for example CONFIGURE_LDFLAGS="-L/path/to/libffi-3.2.1/lib64".

Change Button color onClick

Using jquery, try this. if your button id is say id= clickme

$("clickme").on('çlick', function(){

$(this).css('background-color', 'grey'); .......

How to solve Notice: Undefined index: id in C:\xampp\htdocs\invmgt\manufactured_goods\change.php on line 21

Simply add this

$id = ''; 
if( isset( $_GET['id'])) {
    $id = $_GET['id']; 
} 

How to include js and CSS in JSP with spring MVC

Put your style.css directly into the webapp/css folder, not into the WEB-INF folder.

Then add the following code into your spring-dispatcher-servlet.xml

<mvc:resources mapping="/css/**" location="/css/" />

and then add following code into your jsp page

<link rel="stylesheet" type="text/css" href="css/style.css"/>

I hope it will work.

Angularjs: Error: [ng:areq] Argument 'HomeController' is not a function, got undefined

Happened to me few times whenever I miss "," between list of injections and function

app.controller('commonCtrl', ['$scope', '$filter',function($scope,$filter) {

}]);

How do I set response headers in Flask?

This work for me

from flask import Flask
from flask import Response

app = Flask(__name__)

@app.route("/")
def home():
    return Response(headers={'Access-Control-Allow-Origin':'*'})

if __name__ == "__main__":
    app.run()

Multipart File upload Spring Boot

You can simply use a controller method like this:

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> uploadFile(
    @RequestParam("file") MultipartFile file) {

  try {
    // Handle the received file here
    // ...
  }
  catch (Exception e) {
    return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
  }

  return new ResponseEntity<>(HttpStatus.OK);
} // method uploadFile

Without any additional configurations for Spring Boot.

Using the following html form client side:

<html>
<body>
  <form action="/uploadFile" method="POST" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="Upload"> 
  </form>
</body>
</html>

If you want to set limits on files size you can do it in the application.properties:

# File size limit
multipart.maxFileSize = 3Mb

# Total request size for a multipart/form-data
multipart.maxRequestSize = 20Mb

Moreover to send the file with Ajax take a look here: http://blog.netgloo.com/2015/02/08/spring-boot-file-upload-with-ajax/

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

Use this way instead of your way.

    addslashes(trim($_POST['username']));

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

The question is a bit old but I just solved a very similar problem. We have several intranet sites here including the one I'm responsible for, and the others require compatibility mode or they break. For that reason, site rules default IE to compatibility mode on intranet sites. I am upgrading my own stuff and no longer need it; in fact, some of the features I'm trying to use don't look right in compat mode. I'm using the meta IE-Edge tag like you are.

IE assumes websites without the fully-qualified address are intranet, and acts accordingly. With that in mind I just altered the bindings in IIS to only listen to the fully-qualified address, then set up a dummy website that listened for the unqualified address. The second one redirects all traffic to the fully-qualified address, making IE believe it's an external site. The site renders correctly with or without the Compatibility Mode on Intranet Sites box checked.

Controller not a function, got undefined, while defining controllers globally

I had this error because I didn't understand the difference between angular.module('myApp', []) and angular.module('myApp').

This creates the module 'myApp' and overwrites any existing module named 'myApp':

angular.module('myApp', [])

This retrieves an existing module 'myApp':

angular.module('myApp')

I had been overwriting my module in another file, using the first call above which created another module instead of retrieving as I expected.

More detail here: https://docs.angularjs.org/guide/module

Flask Value error view function did not return a response

The following does not return a response:

You must return anything like return afunction() or return 'a string'.

This can solve the issue

Why is it that "No HTTP resource was found that matches the request URI" here?

Your problems have nothing to do with POST/GET but only with how you specify parameters in RouteAttribute. To ensure this, I added support for both verbs in my samples.

Let's go back to two very simple working examples.

[Route("api/deliveryitems/{anyString}")]
[HttpGet, HttpPost]
public HttpResponseMessage GetDeliveryItemsOne(string anyString)
{
    return Request.CreateResponse<string>(HttpStatusCode.OK, anyString);
}

And

[Route("api/deliveryitems")]
[HttpGet, HttpPost]
public HttpResponseMessage GetDeliveryItemsTwo(string anyString = "default")
{
    return Request.CreateResponse<string>(HttpStatusCode.OK, anyString);
}

The first sample says that the "anyString" is a path segment parameter (part of the URL).

First sample example URL is:

  • localhost:xxx/api/deliveryItems/dkjd;dslkf;dfk;kkklm;oeop
    • returns "dkjd;dslkf;dfk;kkklm;oeop"

The second sample says that the "anyString" is a query string parameter (optional here since a default value has been provided, but you can make it non-optional by simply removing the default value).

Second sample examples URL are:

  • localhost:xxx/api/deliveryItems?anyString=dkjd;dslkf;dfk;kkklm;oeop
    • returns "dkjd;dslkf;dfk;kkklm;oeop"
  • localhost:xxx/api/deliveryItems
    • returns "default"

Of course, you can make it even more complex, like with this third sample:

[Route("api/deliveryitems")]
[HttpGet, HttpPost]
public HttpResponseMessage GetDeliveryItemsThree(string anyString, string anotherString = "anotherDefault")
{
    return Request.CreateResponse<string>(HttpStatusCode.OK, anyString + "||" + anotherString);
}

Third sample examples URL are:

  • localhost:xxx/api/deliveryItems?anyString=dkjd;dslkf;dfk;kkklm;oeop
    • returns "dkjd;dslkf;dfk;kkklm;oeop||anotherDefault"
  • localhost:xxx/api/deliveryItems
    • returns "No HTTP resource was found that matches the request URI ..." (parameter anyString is mandatory)
  • localhost:xxx/api/deliveryItems?anotherString=bluberb&anyString=dkjd;dslkf;dfk;kkklm;oeop
    • returns "dkjd;dslkf;dfk;kkklm;oeop||bluberb"
    • note that the parameters have been reversed, which does not matter, this is not possible with "URL-style" of first example

When should you use path segment or query parameters? Some advice has already been given here: REST API Best practices: Where to put parameters?

ReferenceError: document is not defined (in plain JavaScript)

This happened with me because I was using Next JS which has server side rendering. When you are using server side rendering there is no browser. Hence, there will not be any variable window or document. Hence this error shows up.

Work around :

If you are using Next JS you can use the dynamic rendering to prevent server side rendering for the component.

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(() => import('../components/List'), {
  ssr: false
})

export default () => <DynamicComponentWithNoSSR />

If you are using any other server side rendering library. Then add the code that you want to run at the client side in componentDidMount. If you are using React Hooks then use useEffects in the place of componentsDidMount.

import React, {useState, useEffects} from 'react';

const DynamicComponentWithNoSSR = <>Some JSX</>

export default function App(){

[a,setA] = useState();
useEffect(() => {
    setA(<DynamicComponentWithNoSSR/>)
  });


return (<>{a}<>)
}

References :

  1. https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr
  2. https://reactjs.org/docs/hooks-effect.html

How to select the rows with maximum values in each group with dplyr?

More generally, I think you might want to get "top" of the rows that are sorted within a given group.

For the case of where a single value is max'd out, you have essentially sorted by only one column. However, it's often useful to hierarchically sort by multiple columns (for example: a date column and a time-of-day column).

# Answering the question of getting row with max "value".
df %>% 
  # Within each grouping of A and B values.
  group_by( A, B) %>% 
  # Sort rows in descending order by "value" column.
  arrange( desc(value) ) %>% 
  # Pick the top 1 value
  slice(1) %>% 
  # Remember to ungroup in case you want to do further work without grouping.
  ungroup()

# Answering an extension of the question of 
# getting row with the max value of the lowest "C".
df %>% 
  # Within each grouping of A and B values.
  group_by( A, B) %>% 
  # Sort rows in ascending order by C, and then within that by 
  # descending order by "value" column.
  arrange( C, desc(value) ) %>% 
  # Pick the one top row based on the sort
  slice(1) %>% 
  # Remember to ungroup in case you want to do further work without grouping.
  ungroup()

Angular bootstrap datepicker date format does not format ng-model value

I ran into the same problem and after a couple of hours of logging and investigating, I fixed it.

It turned out that for the first time the value is set in a date picker, $viewValue is a string so the dateFilter displays it as is. All I did is parse it into a Date object.

Search for that block in ui-bootstrap-tpls file

  ngModel.$render = function() {
    var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : '';
    element.val(date);

    updateCalendar();
  };

and replace it by:

  ngModel.$render = function() {
    ngModel.$viewValue = new Date(ngModel.$viewValue);
    var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : '';
    element.val(date);

    updateCalendar();
  };

Hopefully this will help :)

iFrame Height Auto (CSS)

You should note that div tag behaves like nothing and just let you to put something in it. It means that if you insert a paragraph with 100 lines of text within a div tag, it shows all the text but its height won't change to contain all the text.

So you have to use a CSS & HTML trick to handle this issue. This trick is very simple. you must use an empty div tag with class="clear" and then you will have to add this class to your CSS. Also note that your have #wrap in your CSS file but you don't have any tag with this id. In summary you have to change you code to something like below:

HTML Code:

    <!-- Change "id" from "container" to "wrap" -->
    <div id="wrap">    
        <div id="header">
        </div>

        <div id="navigation"> 
            <a href="/" class="navigation">home</a>
            <a href="about.php" class="navigation">about</a>
            <a href="fanlisting.php" class="navigation">fanlisting</a>
            <a href="reasons.php" class="navigation">100 reasons</a>
            <a href="letter.php" class="navigation">letter</a>
        </div>
        <div id="content" >
            <h1>Update Information</h1>
            <iframe name="frame" id="frame" src="http://website.org/update.php" allowtransparency="true" frameborder="0"></iframe>

            <!-- Add this line -->
            <div class="clear"></div>
        </div>
        <div id="footer">
        </div>

        <!-- Add this line -->
        <div class="clear"></div>
    </div>

And also add this line to your CSS file:

.clear{ display: block; clear: both;}

How do you find out the type of an object (in Swift)?

If you get an "always true/fails" warning you may need to cast to Any before using is

(foo as Any) is SomeClass

justify-content property isn't working

I was having a lot of problems with justify-content, and I figured out the problem was "margin: 0 auto"

The auto part overrides the justify-content so its always displayed according to the margin and not to the justify-content.

How do I print the type or class of a variable in Swift?

As of Xcode 6.3 with Swift 1.2, you can simply convert type values into the full demangled String.

toString(Int)                   // "Swift.Int"
toString(Int.Type)              // "Swift.Int.Type"
toString((10).dynamicType)      // "Swift.Int"
println(Bool.self)              // "Swift.Bool"
println([UTF8].self)            // "Swift.Array<Swift.UTF8>"
println((Int, String).self)     // "(Swift.Int, Swift.String)"
println((String?()).dynamicType)// "Swift.Optional<Swift.String>"
println(NSDate)                 // "NSDate"
println(NSDate.Type)            // "NSDate.Type"
println(WKWebView)              // "WKWebView"
toString(MyClass)               // "[Module Name].MyClass"
toString(MyClass().dynamicType) // "[Module Name].MyClass"

Use HTML5 to resize an image before upload

if any interested I've made a typescript version:

interface IResizeImageOptions {
  maxSize: number;
  file: File;
}
const resizeImage = (settings: IResizeImageOptions) => {
  const file = settings.file;
  const maxSize = settings.maxSize;
  const reader = new FileReader();
  const image = new Image();
  const canvas = document.createElement('canvas');
  const dataURItoBlob = (dataURI: string) => {
    const bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
        atob(dataURI.split(',')[1]) :
        unescape(dataURI.split(',')[1]);
    const mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
    const max = bytes.length;
    const ia = new Uint8Array(max);
    for (var i = 0; i < max; i++) ia[i] = bytes.charCodeAt(i);
    return new Blob([ia], {type:mime});
  };
  const resize = () => {
    let width = image.width;
    let height = image.height;

    if (width > height) {
        if (width > maxSize) {
            height *= maxSize / width;
            width = maxSize;
        }
    } else {
        if (height > maxSize) {
            width *= maxSize / height;
            height = maxSize;
        }
    }

    canvas.width = width;
    canvas.height = height;
    canvas.getContext('2d').drawImage(image, 0, 0, width, height);
    let dataUrl = canvas.toDataURL('image/jpeg');
    return dataURItoBlob(dataUrl);
  };

  return new Promise((ok, no) => {
      if (!file.type.match(/image.*/)) {
        no(new Error("Not an image"));
        return;
      }

      reader.onload = (readerEvent: any) => {
        image.onload = () => ok(resize());
        image.src = readerEvent.target.result;
      };
      reader.readAsDataURL(file);
  })    
};

and here's the javascript result:

var resizeImage = function (settings) {
    var file = settings.file;
    var maxSize = settings.maxSize;
    var reader = new FileReader();
    var image = new Image();
    var canvas = document.createElement('canvas');
    var dataURItoBlob = function (dataURI) {
        var bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
            atob(dataURI.split(',')[1]) :
            unescape(dataURI.split(',')[1]);
        var mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
        var max = bytes.length;
        var ia = new Uint8Array(max);
        for (var i = 0; i < max; i++)
            ia[i] = bytes.charCodeAt(i);
        return new Blob([ia], { type: mime });
    };
    var resize = function () {
        var width = image.width;
        var height = image.height;
        if (width > height) {
            if (width > maxSize) {
                height *= maxSize / width;
                width = maxSize;
            }
        } else {
            if (height > maxSize) {
                width *= maxSize / height;
                height = maxSize;
            }
        }
        canvas.width = width;
        canvas.height = height;
        canvas.getContext('2d').drawImage(image, 0, 0, width, height);
        var dataUrl = canvas.toDataURL('image/jpeg');
        return dataURItoBlob(dataUrl);
    };
    return new Promise(function (ok, no) {
        if (!file.type.match(/image.*/)) {
            no(new Error("Not an image"));
            return;
        }
        reader.onload = function (readerEvent) {
            image.onload = function () { return ok(resize()); };
            image.src = readerEvent.target.result;
        };
        reader.readAsDataURL(file);
    });
};

usage is like:

resizeImage({
    file: $image.files[0],
    maxSize: 500
}).then(function (resizedImage) {
    console.log("upload resized image")
}).catch(function (err) {
    console.error(err);
});

or (async/await):

const config = {
    file: $image.files[0],
    maxSize: 500
};
const resizedImage = await resizeImage(config)
console.log("upload resized image")

Bootstrap Modal before form Submit

I noticed some of the answers were not triggering the HTML5 required attribute (as stuff was being executed on the action of clicking rather than the action of form send, causing to bypass it when the inputs were empty):

  1. Have a <form id='xform'></form> with some inputs with the required attribute and place a <input type='submit'> at the end.
  2. A confirmation input where typing "ok" is expected <input type='text' name='xconf' value='' required>
  3. Add a modal_1_confirm to your html (to confirm the form of sending).
  4. (on modal_1_confirm) add the id modal_1_accept to the accept button.
  5. Add a second modal_2_errMsg to your html (to display form validation errors).
  6. (on modal_2_errMsg) add the id modal_2_accept to the accept button.
  7. (on modal_2_errMsg) add the id m2_Txt to the displayed text holder.
  8. The JS to intercept before the form is sent:

    $("#xform").submit(function(e){
        var msg, conf, preventSend;
    
        if($("#xform").attr("data-send")!=="ready"){
            msg="Error."; //default error msg
            preventSend=false;
    
            conf=$("[name='xconf']").val().toLowerCase().replace(/^"|"$/g, "");
    
            if(conf===""){
                msg="The field is empty.";
                preventSend=true;
            }else if(conf!=="ok"){
                msg="You didn't write \"ok\" correctly.";
                preventSend=true;
            }
    
            if(preventSend){ //validation failed, show the error
                $("#m2_Txt").html(msg); //displayed text on modal_2_errMsg
                $("#modal_2_errMsg").modal("show");
            }else{ //validation passed, now let's confirm the action
                $("#modal_1_confirm").modal("show");
            }
    
            e.preventDefault();
            return false;
        }
    });
    

`9. Also some stuff when clicking the Buttons from the modals:

$("#modal_1_accept").click(function(){
    $("#modal_1_confirm").modal("hide");
    $("#xform").attr("data-send", "ready").submit();
});

$("#modal_2_accept").click(function(){
    $("#modal_2_errMsg").modal("hide");
});

Important Note: So just be careful if you add an extra way to show the modal, as simply clicking the accept button $("#modal_1_accept") will assume the validation passed and it will add the "ready" attribute:

  • The reasoning for this is that $("#modal_1_confirm").modal("show"); is shown only when it passed the validation, so clicking $("#modal_1_accept") should be unreachable without first getting the form validated.

Node/Express file upload

const http          = require('http');
const fs            = require('fs');

// https://www.npmjs.com/package/formidable
const formidable    = require('formidable');

// https://stackoverflow.com/questions/31317007/get-full-file-path-in-node-js
const path          = require('path');

router.post('/upload', (req, res) => {
    console.log(req.files);

    let oldpath = req.files.fileUploaded.path;

    // https://stackoverflow.com/questions/31317007/get-full-file-path-in-node-js       
    let newpath = path.resolve( `./${req.files.fileUploaded.name}` );

    // copy
    // https://stackoverflow.com/questions/43206198/what-does-the-exdev-cross-device-link-not-permitted-error-mean
    fs.copyFile( oldpath, newpath, (err) => {

        if (err) throw err;

        // delete
        fs.unlink( oldpath, (err) => {

            if (err) throw err;

            console.log('Success uploaded")
        } );                

    } );

});

Form Submission without page refresh

<script type="text/javascript">
    var frm = $('#myform');
    frm.submit(function (ev) {
        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function (data) {
                alert('ok');
            }
        });

        ev.preventDefault();
    });
</script>

<form id="myform" action="/your_url" method="post">
    ...
</form>

The CSRF token is invalid. Please try to resubmit the form

In my case I got a trouble with the maxSize annotation in the entity, so I increased it from 2048 to 20048.

 /**
 * @Assert\File(
 *     maxSize = "20048k",
 *     mimeTypes = {"application/pdf", "application/x-pdf"},
 *     mimeTypesMessage = "Please upload a valid PDF"
 * )
 */
private $file;

hope this answer helps!

How can I change the width and height of slides on Slick Carousel?

You could also use this:

$('.slider').slick({
   //other settings ................
   respondTo: 'slider', //makes the slider to change width depending on the container it is in
   adaptiveHeight: true //makes the height change depending on the height of the element inside
})

org.hibernate.MappingException: Unknown entity: annotations.Users

Problem occurs because of the entry mapping class="annotations.Users" in hibernate.cfg.xml remove that line then it will be work.

I had the same issue. When I removed the above line then it was working fine for me.

File uploading with Express 4.0: req.files undefined

Here is what i found googling around:

var fileupload = require("express-fileupload");
app.use(fileupload());

Which is pretty simple mechanism for uploads

app.post("/upload", function(req, res)
{
    var file;

    if(!req.files)
    {
        res.send("File was not found");
        return;
    }

    file = req.files.FormFieldName;  // here is the field name of the form

    res.send("File Uploaded");


});

AngularJS : Factory and Service?

$provide service

They are technically the same thing, it's actually a different notation of using the provider function of the $provide service.

  • If you're using a class: you could use the service notation.
  • If you're using an object: you could use the factory notation.

The only difference between the service and the factory notation is that the service is new-ed and the factory is not. But for everything else they both look, smell and behave the same. Again, it's just a shorthand for the $provide.provider function.

// Factory

angular.module('myApp').factory('myFactory', function() {

  var _myPrivateValue = 123;

  return {
    privateValue: function() { return _myPrivateValue; }
  };

});

// Service

function MyService() {
  this._myPrivateValue = 123;
}

MyService.prototype.privateValue = function() {
  return this._myPrivateValue;
};

angular.module('myApp').service('MyService', MyService);

Create a simple Login page using eclipse and mysql

You Can simply Use One Jsp Page To accomplish the task.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
   <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <%
        String username=request.getParameter("user_name");
        String password=request.getParameter("password");
        String role=request.getParameter("role");
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
            Statement st=con.createStatement();
            String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
            ResultSet rs=st.executeQuery(query);
            while(rs.next())
            {
                session.setAttribute( "user_name",rs.getString(2));
                session.setMaxInactiveInterval(3000);
                response.sendRedirect("homepage.jsp");
            }
            %>



        <%}
        catch(Exception e)
        {
            out.println(e);
        }
    %>

</body>

I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

Other persons that are using mapping classes for Hibernate, make sure that have addressed correctly to model package in sessionFactory bean declaration in the following part:

<property name="packagesToScan" value="com.mblog.model"></property>

The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

I found solution. It works fine when I throw away next line from form:

enctype="multipart/form-data"

And now it pass all parameters at request ok:

 <form action="/registration" method="post">
   <%-- error messages --%>
   <div class="form-group">
    <c:forEach items="${registrationErrors}" var="error">
    <p class="error">${error}</p>
     </c:forEach>
   </div>

how to change text box value with jQuery?

Use ready event of document :

$(document).ready(function(){ /* the click code */ });

And it is better to use bind method for event handeling. because you don't want to call click action in every load of page

  $(':submit').bind('click' , function () { /* ... */ });

How do I change the select box arrow

Working with just one selector:

select {
    width: 268px;
    padding: 5px;
    font-size: 16px;
    line-height: 1;
    border: 0;
    border-radius: 5px;
    height: 34px;
    background: url(http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png) no-repeat right #ddd;
    -webkit-appearance: none;
    background-position-x: 244px;
}

fiddler

CSS how to make scrollable list

Another solution would be as below where the list is placed under a drop-down button.

  <button class="btn dropdown-toggle btn-primary btn-sm" data-toggle="dropdown"
    >Markets<span class="caret"></span></button>

    <ul class="dropdown-menu", style="height:40%; overflow:hidden; overflow-y:scroll;">
      {{ form.markets }}
    </ul>

Using Spring RestTemplate in generic method with generic parameter

I am using org.springframework.core.ResolvableType for a ListResultEntity :

    ResolvableType resolvableType = ResolvableType.forClassWithGenerics(ListResultEntity.class, itemClass);
    ParameterizedTypeReference<ListResultEntity<T>> typeRef = ParameterizedTypeReference.forType(resolvableType.getType());

So in your case:

public <T> ResponseWrapper<T> makeRequest(URI uri, Class<T> clazz) {
   ResponseEntity<ResponseWrapper<T>> response = template.exchange(
        uri,
        HttpMethod.POST,
        null,
        ParameterizedTypeReference.forType(ResolvableType.forClassWithGenerics(ResponseWrapper.class, clazz)));
    return response;
}

This only makes use of spring and of course requires some knowledge about the returned types (but should even work for things like Wrapper>> as long as you provide the classes as varargs )

How to Import Excel file into mysql Database from PHP

You are probably having a problem with the sort of CSV file that you have.

Open the CSV file with a text editor, check that all the separations are done with the comma, and not semicolon and try the script again. It should work fine.

Bootstrap 3 .img-responsive images are not responsive inside fieldset in FireFox

This looks like a Bootstrap issue...

Currently, here's a workaround : add .col-xs-12 to your responsive image.

Bootply

Posting raw image data as multipart/form-data in curl

In case anyone had the same problem: check this as @PravinS suggested. I used the exact same code as shown there and it worked for me perfectly.

This is the relevant part of the server code that helped:

if (isset($_POST['btnUpload']))
{
$url = "URL_PATH of upload.php"; // e.g. http://localhost/myuploader/upload.php // request URL
$filename = $_FILES['file']['name'];
$filedata = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
if ($filedata != '')
{
    $headers = array("Content-Type:multipart/form-data"); // cURL headers for file uploading
    $postfields = array("filedata" => "@$filedata", "filename" => $filename);
    $ch = curl_init();
    $options = array(
        CURLOPT_URL => $url,
        CURLOPT_HEADER => true,
        CURLOPT_POST => 1,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => $postfields,
        CURLOPT_INFILESIZE => $filesize,
        CURLOPT_RETURNTRANSFER => true
    ); // cURL options
    curl_setopt_array($ch, $options);
    curl_exec($ch);
    if(!curl_errno($ch))
    {
        $info = curl_getinfo($ch);
        if ($info['http_code'] == 200)
            $errmsg = "File uploaded successfully";
    }
    else
    {
        $errmsg = curl_error($ch);
    }
    curl_close($ch);
}
else
{
    $errmsg = "Please select the file";
}
}

html form should look something like:

<form action="uploadpost.php" method="post" name="frmUpload" enctype="multipart/form-data">
<tr>
  <td>Upload</td>
  <td align="center">:</td>
  <td><input name="file" type="file" id="file"/></td>
</tr>
<tr>
  <td>&nbsp;</td>
  <td align="center">&nbsp;</td>
  <td><input name="btnUpload" type="submit" value="Upload" /></td>
</tr>

Angularjs action on click of button

The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.

Instead you could try the following approach. Change your markup to the following:

<div ng-controller="myAppController" style="text-align:center">
  <p style="font-size:28px;">Enter Quantity:
      <input type="text" ng-model="quantity"/>
  </p>
  <button ng-click="calculateQuantity()">Calculate</button>
  <h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>

Next, update your controller:

myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantity=1;
  $scope.quantityResult = 0;

  $scope.calculateQuantity = function() {
    $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  };
});

Here's a JSBin example that demonstrates the above approach.

The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.

This would involve updating the template to add an ng-change on the input, and an ng-if on the result:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>

and

<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

In the controller add:

$scope.showQuantityResult = false;

$scope.calculateQuantity = function() {
  $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  $scope.showQuantityResult = true;
};

$scope.hideQuantityResult = function() {
  $scope.showQuantityResult = false;
}; 

These updates can be seen in this JSBin demo.

Error in your SQL syntax; check the manual that corresponds to your MySQL server version

Use ` backticks for MYSQL reserved words...

table name "table" is reserved word for MYSQL...

so your query should be as follows...

$sql="INSERT INTO `table` (`username`, `password`)
VALUES
('$_POST[username]','$_POST[password]')";

How to Call a JS function using OnClick event

You are attempting to attach an event listener function before the element is loaded. Place fun() inside an onload event listener function. Call f1() within this function, as the onclick attribute will be ignored.

function f1() {
    alert("f1 called");
    //form validation that recalls the page showing with supplied inputs.    
}
window.onload = function() {
    document.getElementById("Save").onclick = function fun() {
        alert("hello");
        f1();
        //validation code to see State field is mandatory.  
    }
}

JSFiddle

insert data into database using servlet and jsp in eclipse

Remove conn.commit from Register.java

In your jsp change action to :<form name="registrationform" action="Register" method="post">

Simple PHP calculator

<?php 
$result = "";
class calculator
{
    var $a;
    var $b;

    function checkopration($oprator)
    {
        switch($oprator)
        {
            case '+':
            return $this->a + $this->b;
            break;

            case '-':
            return $this->a - $this->b;
            break;

            case '*':
            return $this->a * $this->b;
            break;

            case '/':
            return $this->a / $this->b;
            break;

            default:
            return "Sorry No command found";
        }   
    }
    function getresult($a, $b, $c)
    {
        $this->a = $a;
        $this->b = $b;
        return $this->checkopration($c);
    }
}

$cal = new calculator();
if(isset($_POST['submit']))
{   
    $result = $cal->getresult($_POST['n1'],$_POST['n2'],$_POST['op']);
}
?>

<form method="post">
<table align="center">
    <tr>
        <td><strong><?php echo $result; ?><strong></td>
    </tr>
    <tr>
        <td>Enter 1st Number</td>
        <td><input type="text" name="n1"></td>
    </tr>

    <tr>
        <td>Enter 2nd Number</td>
        <td><input type="text" name="n2"></td>
    </tr>

    <tr>
        <td>Select Oprator</td>
        <td><select name="op">
            <option value="+">+</option>
            <option value="-">-</option>
            <option value="*">*</option>
            <option value="/">/</option>
        </select></td>
    </tr>

    <tr>
        <td></td>
        <td><input type="submit" name="submit" value="                =                "></td>
    </tr>

</table>
</form>

How to target the href to div

if you use

angularjs

you have just to write the right css in order to frame you div html code

<div 
style="height:51px;width:111px;margin-left:203px;" 
ng-click="nextDetail()">
</div>


JS Code(in your controller):

$scope.nextDetail = function()
{
....
}

jQuery AJAX single file upload

A. Grab file data from the file field

The first thing to do is bind a function to the change event on your file field and a function for grabbing the file data:

// Variable to store your files
var files;

// Add events
$('input[type=file]').on('change', prepareUpload);

// Grab the files and set them to our variable
function prepareUpload(event)
{
  files = event.target.files;
}

This saves the file data to a file variable for later use.

B. Handle the file upload on submit

When the form is submitted you need to handle the file upload in its own AJAX request. Add the following binding and function:

$('form').on('submit', uploadFiles);

// Catch the form submit and upload the files
function uploadFiles(event)
{
  event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening

// START A LOADING SPINNER HERE

// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
    data.append(key, value);
});

$.ajax({
    url: 'submit.php?files',
    type: 'POST',
    data: data,
    cache: false,
    dataType: 'json',
    processData: false, // Don't process the files
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            // Success so call function to process the form
            submitForm(event, data);
        }
        else
        {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
        // STOP LOADING SPINNER
    }
});
}

What this function does is create a new formData object and appends each file to it. It then passes that data as a request to the server. 2 attributes need to be set to false:

  • processData - Because jQuery will convert the files arrays into strings and the server can't pick it up.
  • contentType - Set this to false because jQuery defaults to application/x-www-form-urlencoded and doesn't send the files. Also setting it to multipart/form-data doesn't seem to work either.

C. Upload the files

Quick and dirty php script to upload the files and pass back some info:

<?php // You need to add server side validation and better error handling here

$data = array();

if(isset($_GET['files']))
{  
$error = false;
$files = array();

$uploaddir = './uploads/';
foreach($_FILES as $file)
{
    if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
    {
        $files[] = $uploaddir .$file['name'];
    }
    else
    {
        $error = true;
    }
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
    $data = array('success' => 'Form was submitted', 'formData' => $_POST);
}

echo json_encode($data);

?>

IMP: Don't use this, write your own.

D. Handle the form submit

The success method of the upload function passes the data sent back from the server to the submit function. You can then pass that to the server as part of your post:

function submitForm(event, data)
{
  // Create a jQuery object from the form
$form = $(event.target);

// Serialize the form data
var formData = $form.serialize();

// You should sterilise the file names
$.each(data.files, function(key, value)
{
    formData = formData + '&filenames[]=' + value;
});

$.ajax({
    url: 'submit.php',
    type: 'POST',
    data: formData,
    cache: false,
    dataType: 'json',
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            // Success so call function to process the form
            console.log('SUCCESS: ' + data.success);
        }
        else
        {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
    },
    complete: function()
    {
        // STOP LOADING SPINNER
    }
});
}

Final note

This script is an example only, you'll need to handle both server and client side validation and some way to notify users that the file upload is happening. I made a project for it on Github if you want to see it working.

Referenced From

Uncaught ReferenceError: $ is not defined error in jQuery

Change the order you're including your scripts (jQuery first):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="./javascript.js"></script>
<script
    src="http://maps.googleapis.com/maps/api/js?key=YOUR_APIKEY&sensor=false">
</script>

Send FormData and String Data Together Through JQuery AJAX?

For Multiple file input : Try this code :

 <form name="form" id="form" method="post" enctype="multipart/form-data">
    <input type="file" name="file[]">
    <input type="file" name="file[]" >
    <input type="text" name="name" id="name">
    <input type="text" name="name1" id="name1">
    <input type="button" name="submit" value="upload" id="upload">
 </form>


 $('#upload').on('click', function() {
  var fd = new FormData();
    var c=0;
    var file_data;
    $('input[type="file"]').each(function(){
        file_data = $('input[type="file"]')[c].files; // for multiple files

     for(var i = 0;i<file_data.length;i++){
         fd.append("file_"+c, file_data[i]);
     }
    c++;
 }); 
     var other_data = $('form').serializeArray();
     $.each(other_data,function(key,input){
         fd.append(input.name,input.value);
     });
     $.ajax({
         url: 'work.php',
         data: fd,
         contentType: false,
         processData: false,
         type: 'POST',
         success: function(data){
             console.log(data);
         }
     });
 });

How to use FormData for AJAX file upload?

$(document).ready(function () {
    $(".submit_btn").click(function (event) {
        event.preventDefault();
        var form = $('#fileUploadForm')[0];
        var data = new FormData(form);
        data.append("CustomField", "This is some extra data, testing");
        $("#btnSubmit").prop("disabled", true);
        $.ajax({
            type: "POST",
            enctype: 'multipart/form-data',
            url: "upload.php",
            data: data,
            processData: false,
            contentType: false,
            cache: false,
            timeout: 600000,
            success: function (data) {
                console.log();
            },
        });
    });
});

how to set the background image fit to browser using html

Try This Code: It may help you

<html>
    <head>
<style>
    body
        {
            background:url('images/top-left.jpg') no-repeat center center fixed;
            background-size: cover;
            -webkit-background-size: cover;
            -moz-background-size: cover;
            -o-background-size: cover;
            margin: 0;
            padding: 0;
        }

    </style>
</head>
    <body>
    <form action="LoginCheck.jsp"method="post">
    </br>Username:<input type="text" name="username">
    </br>Password:<input type="password" name="password">
    </br>
    <input type="submit" value="Submit">
    </form>
    </center> 
    </body>


</html>

no operator "<<" matches these operands

You're not including the standard <string> header.

You got [un]lucky that some of its pertinent definitions were accidentally made available by the other standard headers that you did include ... but operator<< was not.

Bootstrap 3 - jumbotron background image effect

After inspecting the sample website you provided, I found that the author might achieve the effect by using a library called Stellar.js, take a look at the library site, cheers!

How to add an image in the title bar using html?

Try the following:

<link rel="icon" type="image/png" href="img/iconimg.png" />

NB: The href is the directory to your image example. Your image is in a folder called "img" and your image name is "iconimg" and if it is a png use .png, if it is a jpg then .jpg. Remember to do this in the head of your file and not in the body.

Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

Please set your form action attribute as below it will solve your problem.

<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">

jQuery code:

$(document).ready(function () {
    $("#addProductForm").submit(function (event) {

        //disable the default form submission
        event.preventDefault();
        //grab all form data  
        var formData = $(this).serialize();

        $.ajax({
            url: 'addProduct.php',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function () {
                alert('Form Submitted!');
            },
            error: function(){
                alert("error in ajax form submission");
            }
        });

        return false;
    });
});

Iterating through a List Object in JSP

you can read empList directly in forEach tag.Try this

 <table>
       <c:forEach items="${sessionScope.empList}" var="employee">
            <tr>
                <td>Employee ID: <c:out value="${employee.eid}"/></td>
                <td>Employee Pass: <c:out value="${employee.ename}"/></td>  
            </tr>
        </c:forEach>
    </table>

how to fetch data from database in Hibernate

Let me quote this:

Hibernate created a new language named Hibernate Query Language (HQL), the syntax is quite similar to database SQL language. The main difference between is HQL uses class name instead of table name, and property names instead of column name.

As far as I can see you are using the table name.

So it should be like this:

Query query = session.createQuery("from Employee");

Cloudfront custom-origin distribution returns 502 "ERROR The request could not be satisfied." for some URLs

I just went through troubleshooting this issue, and in my case it indeed was related to redirects, but not related to incorrect settings in my CloudFront Origin or Behavior. This will happen if your origin server is still redirecting to origin URLs, and not what you have set up for your cloudfront URLs. Seems this is very common if you forget to change configs. For example lets say if you have www.yoursite.com CNAME to your cloudfront distribution, with an origin of www.yoursiteorigin.com. Obviously people will come to www.yoursite.com. But if your code tries to redirect to any page on www.yoursiteorigin.com you WILL get this error.

For me, my origin was still doing the http->https redirects to my origin URLs and not my Cloudfront URLs.

Bootstrap 3 Carousel Not Working

There are just two minor things here.

The first is in the following carousel indicator list items:

<li data-target="carousel" data-slide-to="0"></li>

You need to pass the data-target attribute a selector which means the ID must be prefixed with #. So change them to the following:

<li data-target="#carousel" data-slide-to="0"></li>

Secondly, you need to give the carousel a starting point so both the carousel indicator items and the carousel inner items must have one active class. Like this:

<ol class="carousel-indicators">
    <li data-target="#carousel" data-slide-to="0" class="active"></li>
    <!-- Other Items -->
</ol>
<div class="carousel-inner">
    <div class="item active">
        <img src="https://picsum.photos/1500/600?image=1" alt="Slide 1" />
    </div>
    <!-- Other Items -->
</div>

Working Demo in Fiddle

Creating SVG elements dynamically with javascript inside HTML

To facilitate svg editing you can use an intermediate function:

function getNode(n, v) {
  n = document.createElementNS("http://www.w3.org/2000/svg", n);
  for (var p in v)
    n.setAttributeNS(null, p, v[p]);
  return n
}

Now you can write:

svg.appendChild( getNode('rect', { width:200, height:20, fill:'#ff0000' }) );

Example (with an improved getNode function allowing camelcase for property with dash, eg strokeWidth > stroke-width):

_x000D_
_x000D_
function getNode(n, v) {_x000D_
  n = document.createElementNS("http://www.w3.org/2000/svg", n);_x000D_
  for (var p in v)_x000D_
    n.setAttributeNS(null, p.replace(/[A-Z]/g, function(m, p, o, s) { return "-" + m.toLowerCase(); }), v[p]);_x000D_
  return n_x000D_
}_x000D_
_x000D_
var svg = getNode("svg");_x000D_
document.body.appendChild(svg);_x000D_
_x000D_
var r = getNode('rect', { x: 10, y: 10, width: 100, height: 20, fill:'#ff00ff' });_x000D_
svg.appendChild(r);_x000D_
_x000D_
var r = getNode('rect', { x: 20, y: 40, width: 100, height: 40, rx: 8, ry: 8, fill: 'pink', stroke:'purple', strokeWidth:7 });_x000D_
svg.appendChild(r);
_x000D_
_x000D_
_x000D_

nodejs send html file to client

Try your code like this:

var app = express();
app.get('/test', function(req, res) {
    res.sendFile('views/test.html', {root: __dirname })
});
  1. Use res.sendFile instead of reading the file manually so express can handle setting the content-type properly for you.

  2. You don't need the app.engine line, as that is handled internally by express.

send checkbox value in PHP form

if(isset($_POST["newsletter"]) && $_POST["newsletter"] == "newsletter"){
    //checked
}

Javascript getElementsByName.value not working

document.getElementsByName("name") will get several elements called by same name . document.getElementsByName("name")[Number] will get one of them. document.getElementsByName("name")[Number].value will get the value of paticular element.

The key of this question is this:
The name of elements is not unique, it is usually used for several input elements in the form.
On the other hand, the id of the element is unique, which is the only definition for a particular element in a html file.

Javascript Date Validation ( DD/MM/YYYY) & Age Checking

with leading zero for day and month

var pattern =/^(0[1-9]|1[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/([0-9]{4})$/;

and with both leading zero/without leading zero for day and month

var pattern =/^(0?[1-9]|1[0-9]|2[0-9]|3[0-1])\/(0?[1-9]|1[0-2])\/([0-9]{4})$/;

How to export the Html Tables data into PDF using Jspdf

I Used Datatable JS plugin for my purpose of exporting an html table data into various formats. With my experience it was very quick, easy to use and configure with minimal coding.

Below is a sample jquery call using datatable plugin, #example is your table id

$(document).ready(function() {
    $('#example').DataTable( {
        dom: 'Bfrtip',
        buttons: [
            'copyHtml5',
            'excelHtml5',
            'csvHtml5',
            'pdfHtml5'
        ]
    } );
} );

Please find the complete example in below datatable reference link :

https://datatables.net/extensions/buttons/examples/html5/simple.html

This is how it looks after configuration( from reference site) : enter image description here

You need to have following library references in your html ( some can be found in the above reference link)

jquery-1.12.3.js
jquery.dataTables.min.js
dataTables.buttons.min.js
jszip.min.js
pdfmake.min.js
vfs_fonts.js
buttons.html5.min.js

How to use BeanUtils.copyProperties?

As you can see in the below source code, BeanUtils.copyProperties internally uses reflection and there's additional internal cache lookup steps as well which is going to add cost wrt performance

 private static void copyProperties(Object source, Object target, @Nullable Class<?> editable,
                @Nullable String... ignoreProperties) throws BeansException {

            Assert.notNull(source, "Source must not be null");
            Assert.notNull(target, "Target must not be null");

            Class<?> actualEditable = target.getClass();
            if (editable != null) {
                if (!editable.isInstance(target)) {
                    throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
                            "] not assignable to Editable class [" + editable.getName() + "]");
                }
                actualEditable = editable;
            }
            **PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);**
            List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);

            for (PropertyDescriptor targetPd : targetPds) {
                Method writeMethod = targetPd.getWriteMethod();
                if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
                    PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                    if (sourcePd != null) {
                        Method readMethod = sourcePd.getReadMethod();
                        if (readMethod != null &&
                                ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
                            try {
                                if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                                    readMethod.setAccessible(true);
                                }
                                Object value = readMethod.invoke(source);
                                if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                    writeMethod.setAccessible(true);
                                }
                                writeMethod.invoke(target, value);
                            }
                            catch (Throwable ex) {
                                throw new FatalBeanException(
                                        "Could not copy property '" + targetPd.getName() + "' from source to target", ex);
                            }
                        }
                    }
                }
            }
        }

So it's better to use plain setters given the cost reflection

In bootstrap how to add borders to rows without adding up?

you can add the 1px border to just the sides and bottom of each row. the first value is the top border, the second is the right border, the third is the bottom border, and the fourth is the left border.

div.row {
  border: 0px 1px 1px 1px solid;
}

How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

how to get value of selected item in autocomplete

To answer the question more generally, the answer is:

select: function( event , ui ) {
    alert( "You selected: " + ui.item.label );
}

Complete example :

_x000D_
_x000D_
$('#test').each(function(i, el) {_x000D_
    var that = $(el);_x000D_
    that.autocomplete({_x000D_
        source: ['apple','banana','orange'],_x000D_
        select: function( event , ui ) {_x000D_
            alert( "You selected: " + ui.item.label );_x000D_
        }_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>_x000D_
_x000D_
Type a fruit here: <input type="text" id="test" />
_x000D_
_x000D_
_x000D_

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

How to upload files on server folder using jsp

You cannot upload like this.

http://grand-shopping.com/<"some folder">

You need a physical path exactly like in your local

C:/Users/puneet verma/Downloads/

What you can do is create some local path where your server is working. Hence you can store and retrieve the file. If you bought some domain from any websites there will be path to upload the files. You create these variable as static constant and use it based on the server you are working (Local/Website).

Ajax Upload image

HTML Code

<div class="rCol"> 
     <div id ="prv" style="height:auto; width:auto; float:left; margin-bottom: 28px; margin-left: 200px;"></div>
       </div>
    <div class="rCol" style="clear:both;">

    <label > Upload Photo : </label> 
    <input type="file" id="file" name='file' onChange=" return submitForm();">
    <input type="hidden" id="filecount" value='0'>

Here is Ajax Code:

function submitForm() {

    var fcnt = $('#filecount').val();
    var fname = $('#filename').val();
    var imgclean = $('#file');
    if(fcnt<=5)
    {
    data = new FormData();
    data.append('file', $('#file')[0].files[0]);

    var imgname  =  $('input[type=file]').val();
     var size  =  $('#file')[0].files[0].size;

    var ext =  imgname.substr( (imgname.lastIndexOf('.') +1) );
    if(ext=='jpg' || ext=='jpeg' || ext=='png' || ext=='gif' || ext=='PNG' || ext=='JPG' || ext=='JPEG')
    {
     if(size<=1000000)
     {
    $.ajax({
      url: "<?php echo base_url() ?>/upload.php",
      type: "POST",
      data: data,
      enctype: 'multipart/form-data',
      processData: false,  // tell jQuery not to process the data
      contentType: false   // tell jQuery not to set contentType
    }).done(function(data) {
       if(data!='FILE_SIZE_ERROR' || data!='FILE_TYPE_ERROR' )
       {
        fcnt = parseInt(fcnt)+1;
        $('#filecount').val(fcnt);
        var img = '<div class="dialog" id ="img_'+fcnt+'" ><img src="<?php echo base_url() ?>/local_cdn/'+data+'"><a href="#" id="rmv_'+fcnt+'" onclick="return removeit('+fcnt+')" class="close-classic"></a></div><input type="hidden" id="name_'+fcnt+'" value="'+data+'">';
        $('#prv').append(img);
        if(fname!=='')
        {
          fname = fname+','+data;
        }else
        {
          fname = data;
        }
         $('#filename').val(fname);
          imgclean.replaceWith( imgclean = imgclean.clone( true ) );
       }
       else
       {
         imgclean.replaceWith( imgclean = imgclean.clone( true ) );
         alert('SORRY SIZE AND TYPE ISSUE');
       }

    });
    return false;
  }//end size
  else
  {
      imgclean.replaceWith( imgclean = imgclean.clone( true ) );//Its for reset the value of file type
    alert('Sorry File size exceeding from 1 Mb');
  }
  }//end FILETYPE
  else
  {
     imgclean.replaceWith( imgclean = imgclean.clone( true ) );
    alert('Sorry Only you can uplaod JPEG|JPG|PNG|GIF file type ');
  }
  }//end filecount
  else
  {    imgclean.replaceWith( imgclean = imgclean.clone( true ) );
     alert('You Can not Upload more than 6 Photos');
  }
}

Here is PHP code :

$filetype = array('jpeg','jpg','png','gif','PNG','JPEG','JPG');
   foreach ($_FILES as $key )
    {

          $name =time().$key['name'];

          $path='local_cdn/'.$name;
          $file_ext =  pathinfo($name, PATHINFO_EXTENSION);
          if(in_array(strtolower($file_ext), $filetype))
          {
            if($key['name']<1000000)
            {

             @move_uploaded_file($key['tmp_name'],$path);
             echo $name;

            }
           else
           {
               echo "FILE_SIZE_ERROR";
           }
        }
        else
        {
            echo "FILE_TYPE_ERROR";
        }// Its simple code.Its not with proper validation.

Here upload and preview part done.Now if you want to delete and remove image from page and folder both then code is here for deletion. Ajax Part:

function removeit (arg) {
       var id  = arg;
       // GET FILE VALUE
       var fname = $('#filename').val();
       var fcnt = $('#filecount').val();
        // GET FILE VALUE

       $('#img_'+id).remove();
       $('#rmv_'+id).remove();
       $('#img_'+id).css('display','none');

        var dname  =  $('#name_'+id).val();
        fcnt = parseInt(fcnt)-1;
        $('#filecount').val(fcnt);
        var fname = fname.replace(dname, "");
        var fname = fname.replace(",,", "");
        $('#filename').val(fname);
        $.ajax({
          url: 'delete.php',
          type: 'POST',
          data:{'name':dname},
          success:function(a){
            console.log(a);
            }
        });
    } 

Here is PHP part(delete.php):

$path='local_cdn/'.$_POST['name'];

   if(@unlink($path))
   {
     echo "Success";
   }
   else
   {
     echo "Failed";
   }

AngularJS error: 'argument 'FirstCtrl' is not a function, got undefined'

Watch your letter casing too. I spent a good hour chasing this bug.

<section id="forgotpwd" ng-controller="ForgotPwdController">

while I name the controller

angular
    .module('app')
    .controller('ForgotpwdController', ForgotpwdController);

They all should be consistently named, in this case ForgotpwdController with lower case p.

Getting or changing CSS class property with Javascript using DOM style

Maybe better document.querySelectorAll(".col1") because getElementsByClassName doesn't works in IE 8 and querySelectorAll does (althought CSS2 selectors only).

https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll

How to upload multiple files using PHP, jQuery and AJAX

Finally I have found the solution by using the following code:

$('body').on('click', '#upload', function(e){
        e.preventDefault();
        var formData = new FormData($(this).parents('form')[0]);

        $.ajax({
            url: 'upload.php',
            type: 'POST',
            xhr: function() {
                var myXhr = $.ajaxSettings.xhr();
                return myXhr;
            },
            success: function (data) {
                alert("Data Uploaded: "+data);
            },
            data: formData,
            cache: false,
            contentType: false,
            processData: false
        });
        return false;
});

How to read xml file contents in jQuery and display in html elements?

You can use $.each()

Suppose your xml is

<Cloudtags><id>1</id></Cloudtags><Cloudtags><id>2</id></Cloudtags><Cloudtags><id>3</id></Cloudtags>

In your Ajax success

success: function (xml) {
    $(xml).find('Cloudtags').each(function(){// your outer tag of xml
         var id = $(this).find("id").text(); // 
    });
}

For your case

success: function (xml) {
        $(xml).find('person').each(function(){// your outer tag of xml
             var name = $(this).find("name").text(); // 
             var age = $(this).find("age").text();
        });
    }

How to get coordinates of an svg element?

I was trying to select an area of svg with a rectangle and get all the elements from it. For this, element.getBoundingClientRect() worked perfectly for me. It returns current coordinates of svg elements regardless of whether svg is scaled or transformed.

How to align form at the center of the page in html/css

I would just use table and not the form. Its done by using margin.

table {
  margin: 0 auto;
}

also try using something like

table td {
    padding-bottom: 5px;
}

instead of <br />

and also your input should end with /> e.g:

<input type="password" name="cpwd" />

How to display a database table on to the table in the JSP page

Tracking ID Track
    <br>
    <%String id = request.getParameter("track_id");%>
       <%if (id.length() == 0) {%>
    <b><h1>Please Enter Tracking ID</h1></b>
    <% } else {%>
    <div class="container">
        <table border="1" class="table" >
            <thead>
                <tr class="warning" >
                    <td ><h4>Track ID</h4></td>
                    <td><h4>Source</h4></td>
                    <td><h4>Destination</h4></td>
                    <td><h4>Current Status</h4></td>

                </tr>
            </thead>
            <%
                try {
                    connection = DriverManager.getConnection(connectionUrl + database, userid, password);
                    statement = connection.createStatement();
                    String sql = "select * from track where track_id="+ id;
                    resultSet = statement.executeQuery(sql);
                    while (resultSet.next()) {
            %>
            <tr class="info">
                <td><%=resultSet.getString("track_id")%></td>
                <td><%=resultSet.getString("source")%></td>
                <td><%=resultSet.getString("destination")%></td>
                <td><%=resultSet.getString("status")%></td>
            </tr>
            <%
                    }
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            %>
        </table>

        <%}%>
</body>

Create a new file in git bash

This is a very simple to create file in git bash at first write touch then file name with extension

for example

touch filename.extension

Move_uploaded_file() function is not working

The file will be stored in a temporary location, so use tmp_name instead of name:

if (move_uploaded_file($_FILES['image']['tmp_name'], __DIR__.'/../../uploads/'. $_FILES["image"]['name'])) {
    echo "Uploaded";
} else {
   echo "File not uploaded";
}

Center content in responsive bootstrap navbar

This code worked for me

.navbar .navbar-nav {
    display: inline-block;
    float: none;
}
.navbar .navbar-collapse {
    text-align: center;
}

White space at top of page

I Just put CSS in my <div> now working in code

position: relative; top: -22px;

HTML button onclick event

Having trouble with a button onclick event in jsfiddle?

If so see Onclick event not firing on jsfiddle.net

CSS scale down image to fit in containing div, without specifing original size

Hope this will answer the age old problem (Without using CSS background property)

Html

<div class="card-cont">
 <img src="demo.png" />
</div>

Css

.card-cont{
  width:100%;
  height:150px;
}

.card-cont img{
  max-width: 100%;
  min-width: 100%;
  min-height: 150px;
}

How to use bootstrap datepicker

I believe you have to reference bootstrap.js before bootstrap-datepicker.js

HTML 5 video recording and storing a stream

The followin example shows how to capture and process video frames in HTML5:

_x000D_
_x000D_
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Capturing & Processing Video in HTML5</title>
</head>
<body>
    <div>
        <h2>Camera Preview</h2>
        <video id="cameraPreview" width="240" height="180" autoplay></video>
        <p>
            <button id="startButton" onclick="startCapture();">Start Capture</button>
            <button id="stopButton" onclick="stopCapture();">Stop Capture</button>
        </p>
    </div>

    <div>
        <h2>Processing Preview</h2>
        <canvas id="processingPreview" width="240" height="180"></canvas>
    </div>

    <div>
        <h2>Recording Preview</h2>
        <video id="recordingPreview" width="240" height="180" autoplay controls></video>
        <p>
            <a id="downloadButton">Download</a>
        </p>
    </div>

    <script>

    const ROI_X = 250;
    const ROI_Y = 150;
    const ROI_WIDTH = 240;
    const ROI_HEIGHT = 180;
    
    const FPS = 25;
    
    let cameraStream = null;
    let processingStream = null;
    let mediaRecorder = null;
    let mediaChunks = null;
    let processingPreviewIntervalId = null;

    function processFrame() {
        let cameraPreview = document.getElementById("cameraPreview");
        
        processingPreview
            .getContext('2d')
            .drawImage(cameraPreview, ROI_X, ROI_Y, ROI_WIDTH, ROI_HEIGHT, 0, 0, ROI_WIDTH, ROI_HEIGHT);
    }
    
    function generateRecordingPreview() {
        let mediaBlob = new Blob(mediaChunks, { type: "video/webm" });
        let mediaBlobUrl = URL.createObjectURL(mediaBlob);
        
        let recordingPreview = document.getElementById("recordingPreview");
        recordingPreview.src = mediaBlobUrl;

        let downloadButton = document.getElementById("downloadButton");
        downloadButton.href = mediaBlobUrl;
        downloadButton.download = "RecordedVideo.webm";
    }
        
    function startCapture() {
        const constraints = { video: true, audio: false };
        navigator.mediaDevices.getUserMedia(constraints)
        .then((stream) => {
            cameraStream = stream;
            
            let processingPreview = document.getElementById("processingPreview");
            processingStream = processingPreview.captureStream(FPS);
            
            mediaRecorder = new MediaRecorder(processingStream);
            mediaChunks = []
            
            mediaRecorder.ondataavailable = function(event) {
                mediaChunks.push(event.data);
                if(mediaRecorder.state == "inactive") {
                    generateRecordingPreview();
                }
            };
            
            mediaRecorder.start();
            
            let cameraPreview = document.getElementById("cameraPreview");
            cameraPreview.srcObject = stream;
        
            processingPreviewIntervalId = setInterval(processFrame, 1000 / FPS);
        })
        .catch((err) => {
            alert("No media device found!");
        });
    };
    
    function stopCapture() {
        if(cameraStream != null) {
            cameraStream.getTracks().forEach(function(track) {
                track.stop();
            });
        }
        
        if(processingStream != null) {
            processingStream.getTracks().forEach(function(track) {
                track.stop();
            });
        }
        
        if(mediaRecorder != null) {
            if(mediaRecorder.state == "recording") {
                mediaRecorder.stop();
            }
        }
        
        if(processingPreviewIntervalId != null) {
            clearInterval(processingPreviewIntervalId);
            processingPreviewIntervalId = null;
        }
    };
    </script>
</body>
</html>
_x000D_
_x000D_
_x000D_

Remove "whitespace" between div element

HTML

<div id="div1">
        <div></div><div></div><div></div><br/><div></div><div></div><div></div>
</div>

CSS

#div1 {
    width:150px;height:100px;white-space:nowrap;
    line-height: 0px;
    border:blue 1px solid;padding:5px;
}
#div1 div {
    width:30px;height:30px;
    border:blue 1px solid;
    display:inline-block;
    *display:inline;zoom:1;
    margin:0px;outline:none;
}

DEMO

How do I collapse a table row in Bootstrap?

You are using collapse on the div inside of your table row (tr). So when you collapse the div, the row is still there. You need to change it to where your id and class are on the tr instead of the div.

Change this:

<tr><td><div class="collapse out" id="collapseme">Should be collapsed</div></td></tr>

to this:

<tr class="collapse out" id="collapseme"><td><div>Should be collapsed</div></td></tr>

JSFiddle: http://jsfiddle.net/KnuU6/21/

EDIT: If you are unable to upgrade to 3.0.0, I found a JQuery workaround in 2.3.2:

Remove your data-toggle and data-target and add this JQuery to your button.

$(".btn").click(function() {
    if($("#collapseme").hasClass("out")) {
        $("#collapseme").addClass("in");
        $("#collapseme").removeClass("out");
    } else {
        $("#collapseme").addClass("out");
        $("#collapseme").removeClass("in");
    }
});

JSFiddle: http://jsfiddle.net/KnuU6/25/

How to style SVG with external CSS?

You can include in your SVG files link to external css file using:

<link xmlns="http://www.w3.org/1999/xhtml" rel="stylesheet" href="mystyles.css" type="text/css"/>

You need to put this after opening tag:

<svg>
  <link xmlns="http://www.w3.org/1999/xhtml" rel="stylesheet" href="mystyles.css" type="text/css"/>
  <g>
    <path d=.../>
  </g>
</svg>

It's not perfect solution, because you have to modify svg files, but you modify them once and than all styling changes can be done in one css file for all svg files.

add item to dropdown list in html using javascript

Try to use appendChild method:

select.appendChild(option);

Bootstrap 3.0 Popovers and tooltips

If you're using Rails and ActiveAdmin, this is going to be your problem: https://github.com/seyhunak/twitter-bootstrap-rails/issues/450 Basically, a conflict with active_admin.js

This is the solution: https://stackoverflow.com/a/11745446/264084 (Karen's answer) tldr: Move active_admin assets into the "vendor" directory.

Bootstrap dropdown menu not working (not dropping down when clicked)

Adding this script to my code fixed the dropdown menu.

<script>
    $(document).ready(function () {
        $('.dropdown-toggle').dropdown();
    });
</script>

How to set-up a favicon?

There is a very simple method to set a favicon, which had been around for a long time AFAIK. Place the favicon.ico file in the default location. i.e

http://www.yoursite.com/favicon.ico

This works in almost every browser without a <link> tag. However, this works only if it is an *.ico file. PNGs and other formats still have to be linked with a <link> tag

Form Validation With Bootstrap (jQuery)

enter image description here

Here is a very simple and lightweight plugin for validation with Boostrap, you can use it if you like: https://github.com/wpic/bootstrap.validator.js

box-shadow on bootstrap 3 container

You should give the container an id and use that in your custom css file (which should be linked after the bootstrap css):

#container { box-shadow: values }

Cannot set property 'innerHTML' of null

There are different possible cause as discussed would just like to add this for someone who might have the same issue as mine.

In my case I had a missing close div as shown below

   <!DOCTYPE HTML>
   <html>
   <head>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <title>Untitled Document</title>
   </head>
   <body>
   <div> //I am an open div
    <div id="hello"></div>
   <script type ="text/javascript">
       what();
       function what(){
          document.getElementById('hello').innerHTML = 'hi';
       };
   </script>
   </body>
   </html>

Missing a close div can result in disorganization of the transversal from child to parent or parent to child hence resulting in an error when you try to access an element in the DOM

How to add a button dynamically using jquery

Try this:

<script type="text/javascript">

function test()
{
    if($('input#field').length==0)
    {
       $('<input type="button" id="field"/>').appendTo('body');
     }
}
</script>

Upload video files via PHP and save them in appropriate folder and have a database entry

"Could you suggest a simpler code main thing is uploading the file Data base entry is secondary"

^--- As per OP's request. ---^

Image and video uploading code (tested with PHP Version 5.4.17)

HTML form

<!DOCTYPE html>

<head>
<title></title>
</head>

<body>

<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file"><span>Filename:</span></label>
<input type="file" name="file" id="file" /> 
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>

PHP handler (upload_file.php)

Change upload folder to preferred name. Presently saves to upload/

<?php

$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma");
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

if ((($_FILES["file"]["type"] == "video/mp4")
|| ($_FILES["file"]["type"] == "audio/mp3")
|| ($_FILES["file"]["type"] == "audio/wma")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg"))

&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))

  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

Generate pdf from HTML in div using Javascript

This example works great.

<button onclick="genPDF()">Generate PDF</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script>
    function genPDF() {
        var doc = new jsPDF();
        doc.text(20, 20, 'Hello world!');
        doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
        doc.addPage();
        doc.text(20, 20, 'Do you like that?');
    
        doc.save('Test.pdf');
    }
</script>

how to use font awesome in own css?

Try this way. In your css file change font-family: FontAwesome into font-family: "FontAwesome"; or font-family: 'FontAwesome';. I've solved the same problem using this method.

What is the cause for "angular is not defined"

I had the same problem as deke. I forgot to include the most important script: angular.js :)

<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>

Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

In my case the problem was because of conflicting Jars.

Here is the full list of jars which is working absolutely fine for me.

antlr-2.7.7.jar
byte-buddy-1.8.12.jar
c3p0-0.9.5.2.jar
classmate-1.3.4.jar
dom4j-1.6.1.jar
geolatte-geom-1.3.0.jar
hibernate-c3p0-5.3.1.Final.jar
hibernate-commons-annotations-5.0.3.Final.jar
hibernate-core-5.3.1.Final.jar
hibernate-envers-5.3.1.Final.jar
hibernate-jpamodelgen-5.3.1.Final.jar
hibernate-osgi-5.3.1.Final.jar
hibernate-proxool-5.3.1.Final.jar
hibernate-spatial-5.3.1.Final.jar
jandex-2.0.3.Final.jar
javassist-3.22.0-GA.jar
javax.interceptor-api-1.2.jar
javax.persistence-api-2.2.jar
jboss-logging-3.3.2.Final.jar
jboss-transaction-api_1.2_spec-1.1.1.Final.jar
jts-core-1.14.0.jar
mchange-commons-java-0.2.11.jar
mysql-connector-java-5.1.21.jar
org.osgi.compendium-4.3.1.jar
org.osgi.core-4.3.1.jar
postgresql-42.2.2.jar
proxool-0.8.3.jar
slf4j-api-1.6.1.jar

how to get param in method post spring mvc?

  1. Spring annotations will work fine if you remove enctype="multipart/form-data".

    @RequestParam(value="txtEmail", required=false)
    
  2. You can even get the parameters from the request object .

    request.getParameter(paramName);
    
  3. Use a form in case the number of attributes are large. It will be convenient. Tutorial to get you started.

  4. Configure the Multi-part resolver if you want to receive enctype="multipart/form-data".

    <bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="250000"/>
    </bean>
    

Refer the Spring documentation.

Plot size and resolution with R markdown, knitr, pandoc, beamer

Figure sizes are specified in inches and can be included as a global option of the document output format. For example:

---
title: "My Document"
output:
  html_document:
    fig_width: 6
    fig_height: 4
---

And the plot's size in the graphic device can be increased at the chunk level:

```{r, fig.width=14, fig.height=12}          #Expand the plot width to 14 inches

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

You can also use the out.width and out.height arguments to directly define the size of the plot in the output file:

```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

You can use the "filter" filter in your controller to get all the "C" grades. Getting the first element of the result array will give you the title of the subject that has grade "C".

$scope.gradeC = $filter('filter')($scope.results.subjects, {grade: 'C'})[0];

http://jsbin.com/ewitun/1/edit

The same with plain ES6:

$scope.gradeC = $scope.results.subjects.filter((subject) => subject.grade === 'C')[0]

Displaying a vector of strings in C++

Because userString is empty. You only declare it

vector<string> userString;     

but never add anything, so the for loop won't even run.

HTML Form Redirect After Submit

Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:

<script type="text/javascript">
$(function() {
  $('form').submit(function(){
    $.post('http://example.com/upload', function() {
      window.location = 'http://google.com';
    });
    return false;
  });
});
</script>

phpinfo() is not working on my CentOS server

My solution was uninstalling and installing the PHP instance (7.0 in my case) again:

sudo apt-get purge php7.0
sudo apt-get install php7.0

After that you will need to restart the Apache service:

sudo service apache2 restart

Finally, verify again in your browser with your localhost or IP address.

Add a list item through javascript

Try something like this:

var node=document.createElement("LI");
var textnode=document.createTextNode(firstname);
node.appendChild(textnode);
document.getElementById("demo").appendChild(node);

Fiddle: http://jsfiddle.net/FlameTrap/3jDZd/

Refused to apply inline style because it violates the following Content Security Policy directive

As per http://content-security-policy.com/ The best place to start:

    default-src 'none'; 
    script-src 'self'; 
    connect-src 'self'; 
    img-src 'self'; 
    style-src 'self';
    font-src 'self';

Never inline styles or scripts as it undermines the purpose of CSP. You can use a stylesheet to set a style property and then use a function in a .js file to change the style property (if need be).

How to make the checkbox unchecked by default always

One quick solution that came to mind :-

<input type="checkbox" id="markitem" name="markitem" value="1" onchange="GetMarkedItems(1)">
<label for="markitem" style="position:absolute; top:1px; left:165px;">&nbsp</label>
<!-- Fire the below javascript everytime the page reloads -->
<script type=text/javascript>
  document.getElementById("markitem").checked = false;
</script>
<!-- Tested on Latest FF, Chrome, Opera and IE. -->

Hide Show content-list with only CSS, no javascript used

The answer below includes changing text for "show/hide", and uses a single checkbox, two labels, a total of four lines of html and five lines of css. It also starts out with the content hidden.

Try it in JSFiddle

HTML

<input id="display-toggle" type=checkbox>
<label id="display-button" for="display-toggle"><span>Display Content</span></label>
<label id="hide-button" for="display-toggle"><span>Hide Content</span></label>    
<div id="hidden-content"><br />Hidden Content</div>

CSS

label {
  background-color: #ccc;
  color: brown;
  padding: 15px;
  text-decoration: none;
  font-size: 16px;
  border: 2px solid brown;
  border-radius: 5px;
  display: block;
  width: 200px;
  text-align: center;
}

input,
label#hide-button,
#hidden-content {
  display: none;
}

input#display-toggle:checked ~ label#display-button {
  display: none;
}

input#display-toggle:checked ~ label#hide-button {
  display: block;
  background-color: #aaa;
  color: #333
}

input#display-toggle:checked ~ #hidden-content {
  display: block;
} 

How to upload images into MySQL database using PHP code

Firstly, you should check if your image column is BLOB type!

I don't know anything about your SQL table, but if I'll try to make my own as an example.

We got fields id (int), image (blob) and image_name (varchar(64)).

So the code should look like this (assume ID is always '1' and let's use this mysql_query):

$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); //SQL Injection defence!
$image_name = addslashes($_FILES['image']['name']);
$sql = "INSERT INTO `product_images` (`id`, `image`, `image_name`) VALUES ('1', '{$image}', '{$image_name}')";
if (!mysql_query($sql)) { // Error handling
    echo "Something went wrong! :("; 
}

You are doing it wrong in many ways. Don't use mysql functions - they are deprecated! Use PDO or MySQLi. You should also think about storing files locations on disk. Using MySQL for storing images is thought to be Bad Idea™. Handling SQL table with big data like images can be problematic.

Also your HTML form is out of standards. It should look like this:

<form action="insert_product.php" method="POST" enctype="multipart/form-data">
    <label>File: </label><input type="file" name="image" />
    <input type="submit" />
</form>

Sidenote:

When dealing with files and storing them as a BLOB, the data must be escaped using mysql_real_escape_string(), otherwise it will result in a syntax error.

Full Page <iframe>

This is cross-browser and fully responsive:

<iframe
  src="https://drive.google.com/file/d/0BxrMaW3xINrsR3h2cWx0OUlwRms/preview"
  style="
    position: fixed;
    top: 0px;
    bottom: 0px;
    right: 0px;
    width: 100%;
    border: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    z-index: 999999;
    height: 100%;
  ">
</iframe>

Changing the color of a clicked table row using jQuery

in your css:

.selected{
    background: #F00;
}

in the jquery:

$("#data tr").click(function(){
   $(this).toggleClass('selected');
});

Basically you create a class and adds/removes it from the selected row.

Btw you could have shown more effort, there's no css or jquery/js at all in your code xD

Refresh Page and Keep Scroll Position

If you don't want to use local storage then you could attach the y position of the page to the url and grab it with js on load and set the page offset to the get param you passed in, i.e.:

//code to refresh the page
var page_y = $( document ).scrollTop();
window.location.href = window.location.href + '?page_y=' + page_y;


//code to handle setting page offset on load
$(function() {
    if ( window.location.href.indexOf( 'page_y' ) != -1 ) {
        //gets the number from end of url
        var match = window.location.href.split('?')[1].match( /\d+$/ );
        var page_y = match[0];

        //sets the page offset 
        $( 'html, body' ).scrollTop( page_y );
    }
});

org.apache.jasper.JasperException: Unable to compile class for JSP:

This maybe caused by jar conflict. Remove the servlet-api.jar in your servlet/WEB-INF/ directory, %Tomcat home%/lib already have this lib.

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.

$("new").show();

$("new").hide();

w3cSchool link to JQuery show and hide

read.csv warning 'EOF within quoted string' prevents complete reading of file

The readr package will fix this issue.

install.packages('readr')
library(readr)
readr::read_csv('yourfile.csv')

Error: Argument is not a function, got undefined

Could it be as simple as enclosing your asset in " " and whatever needs quotes on the inside with ' '?

<link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">

becomes

<link rel="stylesheet" media="screen" href="@routes.Assets.at('stylesheets/main.css')">

That could be causing some problems with parsing

How do I debug error ECONNRESET in Node.js?

Had the same problem today. After some research i found a very useful --abort-on-uncaught-exception node.js option. Not only it provides much more verbose and useful error stack trace, but also saves core file on application crash allowing further debug.

AngularJS Uploading An Image With ng-upload

In my case above mentioned methods work fine with php but when i try to upload files with these methods in node.js then i have some problem. So instead of using $http({..,..,...}) use the normal jquery ajax.

For select file use this

<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this)"/>

And in controller

$scope.uploadFile = function(element) {   
var data = new FormData();
data.append('file', $(element)[0].files[0]);
jQuery.ajax({
      url: 'brand/upload',
      type:'post',
      data: data,
      contentType: false,
      processData: false,
      success: function(response) {
      console.log(response);
      },
      error: function(jqXHR, textStatus, errorMessage) {
      alert('Error uploading: ' + errorMessage);
      }
 });   
};

Node.js Error: Cannot find module express

Check if you are not install express module, use this command:

 npm install express

and if your node_modules directory is in another place, set NODE_PATH envirnment variable:

 set NODE_PATH=your\directory\to\node_modules;%NODE_PATH%

Using PHP to upload file and add the path to MySQL database

First you should use print_r($_FILES) to debug, and see what it contains. :

your uploads.php would look like:

//This is the directory where images will be saved
$target = "pics/";
$target = $target . basename( $_FILES['Filename']['name']);

//This gets all the other information from the form
$Filename=basename( $_FILES['Filename']['name']);
$Description=$_POST['Description'];


//Writes the Filename to the server
if(move_uploaded_file($_FILES['Filename']['tmp_name'], $target)) {
    //Tells you if its all ok
    echo "The file ". basename( $_FILES['Filename']['name']). " has been uploaded, and your information has been added to the directory";
    // Connects to your Database
    mysql_connect("localhost", "root", "") or die(mysql_error()) ;
    mysql_select_db("altabotanikk") or die(mysql_error()) ;

    //Writes the information to the database
    mysql_query("INSERT INTO picture (Filename,Description)
    VALUES ('$Filename', '$Description')") ;
} else {
    //Gives and error if its not
    echo "Sorry, there was a problem uploading your file.";
}



?>

EDIT: Since this is old post, currently it is strongly recommended to use either mysqli or pdo instead mysql_ functions in php

Uncaught ReferenceError: $ is not defined

As an addition. If you are using $(Jquery) in your .js file. Logically all libs or frameworks should be before that .js file.

<script type="text/javascript" src="jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="app.js"></script>

jQuery change URL of form submit

Try using this:

$(".move_to").on("click", function(e){
    e.preventDefault();
    $('#contactsForm').attr('action', "/test1").submit();
});

Moving the order in which you use .preventDefault() might fix your issue. You also didn't use function(e) so e.preventDefault(); wasn't working.

Here it is working: http://jsfiddle.net/TfTwe/1/ - first of all, click the 'Check action attribute.' link. You'll get an alert saying undefined. Then click 'Set action attribute.' and click 'Check action attribute.' again. You'll see that the form's action attribute has been correctly set to /test1.

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

You don't need both hibernate.cfg.xml and persistence.xml in this case. Have you tried removing hibernate.cfg.xml and mapping everything in persistence.xml only?

But as the other answer also pointed out, this is not okay like this:

@Id
@JoinColumn(name = "categoria") 
private String id;

Didn't you want to use @Column instead?

Hide Button After Click (With Existing Form on Page)

Change the button to :

<button onclick="getElementById('hidden-div').style.display = 'block'; this.style.display = 'none'">Check Availability</button>

FIDDLE

Or even better, use a proper event handler by identifying the button :

<button id="show_button">Check Availability</button>

and a script

<script type="text/javascript">
    var button = document.getElementById('show_button')
    button.addEventListener('click',hideshow,false);

    function hideshow() {
        document.getElementById('hidden-div').style.display = 'block'; 
        this.style.display = 'none'
    }   
</script>

FIDDLE

Which to use <div class="name"> or <div id="name">?

Read the spec for the attributes and for CSS.

  • id must be unique. class does not have to be
  • id has higher (highest!) specificity in CSS
  • Elements can have multiple non-ordinal classes (separated by spaces), but only one id
  • It is faster to select an element by it's ID when querying the DOM
  • id can be used as an anchor target (using the fragment of the request) for any element. name only works with anchors (<a>)

npm WARN package.json: No repository field

To avoid warnings like:

npm WARN [email protected] No repository field.

You must define repository in your project package.json. In the case when you are developing with no publishing to the repository you can set "private": true in package.json

Example:

{
  "name": "test.loc",
  "version": "1.0.0",
  "private": true,
  ...
  "license": "ISC"
}

NPM documentation about this: https://docs.npmjs.com/files/package.json

How to refresh Gridview after pressed a button in asp.net

Adding the GridView1.DataBind() to the button click event did not work for me. However, adding it to the SqlDataSource1_Updated event did though.

Protected Sub SqlDataSource1_Updated(sender As Object, e As SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Updated
    GridView1.DataBind()
End Sub

What is the right way to write my script 'src' url for a local development environment?

I believe the browser is looking for those assets FROM the root of the webserver. This is difficult because it is easy to start developing on your machine WITHOUT actually using a webserver ( just by loading local files through your browser)

You could start by packaging your html and css/js together?

a directory structure something like:

-yourapp
  - index.html
  - assets
    - css
    - js
      - myPage.js

Then your script tag (from index.html) could look like

<script src="assets/js/myPage.js"></script>

An added benifit of packaging your html and assets in one directory is that you can copy the directory and give it to someone else or put it on another machine and it will work great.

How do I implement Toastr JS?

This is a simple way to do it!

<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/css/toastr.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/js/toastr.js"></script>
<script>
function notificationme(){
toastr.options = {
            "closeButton": false,
            "debug": false,
            "newestOnTop": false,
            "progressBar": true,
            "preventDuplicates": true,
            "onclick": null,
            "showDuration": "100",
            "hideDuration": "1000",
            "timeOut": "5000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "show",
            "hideMethod": "hide"
        };
toastr.info('MY MESSAGE!');
}
</script>

Bootstrap Carousel Full Screen

I found an answer on the startbootstrap.com. Try this code:

CSS

html,
body {
    height: 100%;
}

.carousel,
.item,
.active {
    height: 100%;
}


.carousel-inner {
    height: 100%;
}

/* Background images are set within the HTML using inline CSS, not here */

.fill {
    width: 100%;
    height: 100%;
    background-position: center;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;
    -o-background-size: cover;
}

footer {
    margin: 50px 0;
}

HTML

   <div class="carousel-inner">
        <div class="item active">
            <!-- Set the first background image using inline CSS below. -->
            <div class="fill" style="background-image:url('http://placehold.it/1900x1080&text=Slide One');"></div>
            <div class="carousel-caption">
                <h2>Caption 1</h2>
            </div>
        </div>
        <div class="item">
            <!-- Set the second background image using inline CSS below. -->
            <div class="fill" style="background-image:url('http://placehold.it/1900x1080&text=Slide Two');"></div>
            <div class="carousel-caption">
                <h2>Caption 2</h2>
            </div>
        </div>
        <div class="item">
            <!-- Set the third background image using inline CSS below. -->
            <div class="fill" style="background-image:url('http://placehold.it/1900x1080&text=Slide Three');"></div>
            <div class="carousel-caption">
                <h2>Caption 3</h2>
            </div>
        </div>
    </div>

Source

Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag

In my case I was getting the grey background and it turned out to be inclusion of a zoom value in the map options. Yup, makes no sense.

Automatically resize images with browser size using CSS

This may be too simplistic of an answer (I am still new here), but what I have done in the past to remedy this situation is figured out the percentage of the screen I would like the image to take up. For example, there is one webpage I am working on where the logo must take up 30% of the screen size to look best. I played around and finally tried this code and it has worked for me thus far:

img {
width:30%;
height:auto;
}

That being said, this will change all of your images to be 30% of the screen size at all times. To get around this issue, simply make this a class and apply it to the image that you desire to be at 30% directly. Here is an example of the code I wrote to accomplish this on the aforementioned site:

the CSS portion:

.logo {
position:absolute;
right:25%;
top:0px;
width:30%;
height:auto;
}

the HTML portion:

<img src="logo_001_002.png" class="logo">

Alternatively, you could place ever image you hope to automatically resize into a div of its own and use the class tag option on each div (creating now class tags whenever needed), but I feel like that would cause a lot of extra work eventually. But, if the site calls for it: the site calls for it.

Hopefully this helps. Have a great day!

How to preview an image before and after upload?

                    #######################
                    ###  the img page   ###
                    #######################


<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $('#f').live('change' ,function(){
            $('#fo').ajaxForm({target: '#d'}).submit();
        });
    });
</script>
<form id="fo" name="fo" action="nextimg.php" enctype="multipart/form-data" method="post">
    <input type="file" name="f" id="f" value="start upload" />
    <input type="submit" name="sub" value="upload" />
</form>
<div id="d"></div>


                    #############################
                    ###    the nextimg page   ###
                    #############################


<?php
     $name=$_FILES['f']['name'];
     $tmp=$_FILES['f']['tmp_name'];
     $new=time().$name;
     $new="upload/".$new;
     move_uploaded_file($tmp,$new);
     if($_FILES['f']['error']==0)
     {
?>
     <h1>PREVIEW</h1><br /><img src="<?php echo $new;?>" width="100" height="100" />
<?php
     }
?>

Adding a stylesheet to asp.net (using Visual Studio 2010)

The only thing you have to do is to add in the cshtml file, in the head, the following line:

        @Styles.Render("~/Content/Main.css")

The entire head will look somethink like that:

    <head>
         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
         <title>HTML Page</title>
         @Styles.Render("~/Content/main.css")
    </head>

Hope it helps!!

Get current cursor position in a textbox

Here's one possible method.

function isMouseInBox(e) {
  var textbox = document.getElementById('textbox');

  // Box position & sizes
  var boxX = textbox.offsetLeft;
  var boxY = textbox.offsetTop;
  var boxWidth = textbox.offsetWidth;
  var boxHeight = textbox.offsetHeight;

  // Mouse position comes from the 'mousemove' event
  var mouseX = e.pageX;
  var mouseY = e.pageY;
  if(mouseX>=boxX && mouseX<=boxX+boxWidth) {
    if(mouseY>=boxY && mouseY<=boxY+boxHeight){
       // Mouse is in the box
       return true;
    }
  }
}

document.addEventListener('mousemove', function(e){
    isMouseInBox(e);
})

How to get a reference to an iframe's window object inside iframe's onload handler created from parent window

You're declaring everything in the parent page. So the references to window and document are to the parent page's. If you want to do stuff to the iframe's, use iframe || iframe.contentWindow to access its window, and iframe.contentDocument || iframe.contentWindow.document to access its document.

There's a word for what's happening, possibly "lexical scope": What is lexical scope?

The only context of a scope is this. And in your example, the owner of the method is doc, which is the iframe's document. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.

This is how I would write it:

(function () {
  var dom, win, doc, where, iframe;

  iframe = document.createElement('iframe');
  iframe.src = "javascript:false";

  where = document.getElementsByTagName('script')[0];
  where.parentNode.insertBefore(iframe, where);

  win = iframe.contentWindow || iframe;
  doc = iframe.contentDocument || iframe.contentWindow.document;

  doc.open();
  doc._l = (function (w, d) {
    return function () {
      w.vanishing_global = new Date().getTime();

      var js = d.createElement("script");
      js.src = 'test-vanishing-global.js?' + w.vanishing_global;

      w.name = "foobar";
      d.foobar = "foobar:" + Math.random();
      d.foobar = "barfoo:" + Math.random();
      d.body.appendChild(js);
    };
  })(win, doc);
  doc.write('<body onload="document._l();"></body>');
  doc.close();
})();

The aliasing of win and doc as w and d aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe's stuff. If you want to access the parent's, you still use window and document.

I'm not sure what the implications are of adding methods to a document (doc in this case), but it might make more sense to set the _l method on win. That way, things can be run without a prefix...such as <body onload="_l();"></body>

How to stick <footer> element at the bottom of the page (HTML5 and CSS3)?

Here is an example using css3:

CSS:

html, body {
    height: 100%;
    margin: 0;
}
#wrap {
    padding: 10px;
    min-height: -webkit-calc(100% - 100px);     /* Chrome */
    min-height: -moz-calc(100% - 100px);     /* Firefox */
    min-height: calc(100% - 100px);     /* native */
}
.footer {
    position: relative;
    clear:both;
}

HTML:

<div id="wrap">
    body content....
</div>
<footer class="footer">
    footer content....
</footer>

jsfiddle

Update
As @Martin pointed, the ´position: relative´ is not mandatory on the .footer element, the same for clear:both. These properties are only there as an example. So, the minimum css necessary to stick the footer on the bottom should be:

html, body {
    height: 100%;
    margin: 0;
}
#wrap {
    min-height: -webkit-calc(100% - 100px);     /* Chrome */
    min-height: -moz-calc(100% - 100px);     /* Firefox */
    min-height: calc(100% - 100px);     /* native */
}

Also, there is an excellent article at css-tricks showing different ways to do this: https://css-tricks.com/couple-takes-sticky-footer/

HTML email in outlook table width issue - content is wider than the specified table width

I guess problem is in width attributes in table and td remove 'px' for example

<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">

Should be

<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">

HTML-Tooltip position relative to mouse pointer

This CAN be done with pure html and css. It may not be the best way but we all have different limitations. There are 3 ways that could be useful depending on what your specific circumstances are.

  1. The first involves overlaying an invisible table over top of your link with a hover action on each cell that displays an image.

_x000D_
_x000D_
#imagehover td:hover::after{_x000D_
  content: "             ";_x000D_
  white-space: pre;_x000D_
  background-image: url("http://www.google.com/images/srpr/logo4w.png");_x000D_
  position: relative;_x000D_
  left: 5px;_x000D_
  top: 5px;_x000D_
  font-size: 20px;_x000D_
  background-color: transparent;_x000D_
  background-position: 0px 0px;_x000D_
  background-size: 60px 20px;_x000D_
  background-repeat: no-repeat;_x000D_
  _x000D_
}_x000D_
_x000D_
_x000D_
#imagehover table, #imagehover th, #imagehover td {_x000D_
  border: 0px;_x000D_
  border-spacing: 0px;_x000D_
}
_x000D_
<a href="https://www.google.com">_x000D_
<table id="imagehover" style="width:50px;height:10px;z-index:9999;position:absolute" cellspacing="0">_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
_x000D_
</table>_x000D_
Google</a>
_x000D_
_x000D_
_x000D_

  1. The second relies on being able to create your own cursor image

_x000D_
_x000D_
#googleLink{_x000D_
_x000D_
cursor: url(https://winter-bush-d06c.sto.workers.dev/cursor-extern.php?id=98272),url(https://9dc1a5c00e8109665645209c2d036b1c.cloudflareworkers.com/cursor-extern.php?id=98272),auto;_x000D_
_x000D_
}
_x000D_
<a href="https://www.google.com" id="googleLink">Google</a>
_x000D_
_x000D_
_x000D_

  1. While the normal title tooltip doesn't technically allow images it does allow any unicode characters including block letters and emojis which may suite your needs.

_x000D_
_x000D_
<a href="https://www.google.com" title="??" alt="??">Google</a>
_x000D_
_x000D_
_x000D_

MVC 4 Razor File Upload

The Upload method's HttpPostedFileBase parameter must have the same name as the the file input.

So just change the input to this:

<input type="file" name="file" />

Also, you could find the files in Request.Files:

[HttpPost]
public ActionResult Upload()
{
     if (Request.Files.Count > 0)
     {
         var file = Request.Files[0];

         if (file != null && file.ContentLength > 0)
         {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
            file.SaveAs(path);
         }
     }

     return RedirectToAction("UploadDocument");
 }

Parsing JSON giving "unexpected token o" error

The source of your error, however, is that you need to place the full JSON string in quotes. The following will fix your sample:

<!doctype HTML>
<html>
    <head>
    </head>
    <body>
        <script type="text/javascript">
            var cur_ques_details ='{"ques_id":"15","ques_title":"jlkjlkjlkjljl"}';
            var ques_list = JSON.parse(cur_ques_details);
            document.write(ques_list['ques_title']);
        </script>
    </body>
</html>

As the other respondents have mentioned, the object is already parsed into a JS object so you don't need to parse it. To demonstrate how to accomplish the same thing without parsing, you can do the following:

<!doctype HTML>
<html>
<head>
</head>
    <body>
        <script type="text/javascript">
            var cur_ques_details ={"ques_id":"15","ques_title":"jlkjlkjlkjljl"};
            document.write(cur_ques_details.ques_title);
        </script>
    </body>
</html>

Node.js - How to send data from html to express

Using http.createServer is very low-level and really not useful for creating web applications as-is.

A good framework to use on top of it is Express, and I would seriously suggest using it. You can install it using npm install express.

When you have, you can create a basic application to handle your form:

var express = require('express');
var bodyParser = require('body-parser');
var app     = express();

//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true })); 

//app.use(express.bodyParser());

app.post('/myaction', function(req, res) {
  res.send('You sent the name "' + req.body.name + '".');
});

app.listen(8080, function() {
  console.log('Server running at http://127.0.0.1:8080/');
});

You can make your form point to it using:

<form action="http://127.0.0.1:8080/myaction" method="post">

The reason you can't run Node on port 80 is because there's already a process running on that port (which is serving your index.html). You could use Express to also serve static content, like index.html, using the express.static middleware.

Include CSS and Javascript in my django template

First, create staticfiles folder. Inside that folder create css, js, and img folder.

settings.py

import os

PROJECT_DIR = os.path.dirname(__file__)

DATABASES = {
    'default': {
         'ENGINE': 'django.db.backends.sqlite3', 
         'NAME': os.path.join(PROJECT_DIR, 'myweblabdev.sqlite'),                        
         'USER': '',
         'PASSWORD': '',
         'HOST': '',                      
         'PORT': '',                     
    }
}

MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')

MEDIA_URL = '/media/'

STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(PROJECT_DIR, 'staticfiles'),
)

main urls.py

from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from myweblab import settings

admin.autodiscover()

urlpatterns = patterns('',
    .......
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += staticfiles_urlpatterns()

template

{% load static %}

<link rel="stylesheet" href="{% static 'css/style.css' %}">

AngularJS: ng-repeat list is not updated when a model element is spliced from the model array

If you add a $scope.$apply(); right after $scope.pluginsDisplayed.splice(index,1); then it works.

I am not sure why this is happening, but basically when AngularJS doesn't know that the $scope has changed, it requires to call $apply manually. I am also new to AngularJS so cannot explain this better. I need too look more into it.

I found this awesome article that explains it quite properly. Note: I think it might be better to use ng-click (docs) rather than binding to "mousedown". I wrote a simple app here (http://avinash.me/losh, source http://github.com/hardfire/losh) based on AngularJS. It is not very clean, but it might be of help.

Edit In Place Content Editing

You should put the form inside each node and use ng-show and ng-hide to enable and disable editing, respectively. Something like this:

<li>
  <span ng-hide="editing" ng-click="editing = true">{{bday.name}} | {{bday.date}}</span>
  <form ng-show="editing" ng-submit="editing = false">
    <label>Name:</label>
    <input type="text" ng-model="bday.name" placeholder="Name" ng-required/>
    <label>Date:</label>
    <input type="date" ng-model="bday.date" placeholder="Date" ng-required/>
    <br/>
    <button class="btn" type="submit">Save</button>
   </form>
 </li>

The key points here are:

  • I've changed controls ng-model to the local scope
  • Added ng-show to form so we can show it while editing
  • Added a span with a ng-hide to hide the content while editing
  • Added a ng-click, that could be in any other element, that toggles editing to true
  • Changed ng-submit to toggle editing to false

Here is your updated Plunker.

Force IE10 to run in IE10 Compatibility View?

You can try :

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" >

Just like you tried before, but caution:

It seems like the X-UA-Compatible tag has to be the first tag in the < head > section

If this conclusion is correct, then I believe it is undocumented in Microsoft’s blogs/msdn (and if it is documented, then it isn’t sticking out well enough from the docs). Ensuring that this was the first meta tag in the forced IE9 to switch to IE8 mode successfully

When is JavaScript synchronous?

"I have been under the impression for that JavaScript was always asynchronous"

You can use JavaScript in a synchronous way, or an asynchronous way. In fact JavaScript has really good asynchronous support. For example I might have code that requires a database request. I can then run other code, not dependent on that request, while I wait for that request to complete. This asynchronous coding is supported with promises, async/await, etc. But if you don't need a nice way to handle long waits then just use JS synchronously.

What do we mean by 'asynchronous'. Well it does not mean multi-threaded, but rather describes a non-dependent relationship. Check out this image from this popular answer:

         A-Start ------------------------------------------ A-End   
           | B-Start -----------------------------------------|--- B-End   
           |    |      C-Start ------------------- C-End      |      |   
           |    |       |                           |         |      |
           V    V       V                           V         V      V      
1 thread->|<-A-|<--B---|<-C-|-A-|-C-|--A--|-B-|--C-->|---A---->|--B-->| 

We see that a single threaded application can have async behavior. The work in function A is not dependent on function B completing, and so while function A began before function B, function A is able to complete at a later time and on the same thread.

So, just because JavaScript executes one command at a time, on a single thread, it does not then follow that JavaScript can only be used as a synchronous language.

"Is there a good reference anywhere about when it will be synchronous and when it will be asynchronous"

I'm wondering if this is the heart of your question. I take it that you mean how do you know if some code you are calling is async or sync. That is, will the rest of your code run off and do something while you wait for some result? Your first check should be the documentation for whichever library you are using. Node methods, for example, have clear names like readFileSync. If the documentation is no good there is a lot of help here on SO. EG:

How to know if a function is async?

ImportError: No module named pandas

It might be too late to answer this but I just had the problem and I kept installing and uninstalling, it turns out the the problem happens when you're installing pandas to a version of python and trying to run the program using another python version

So to start off, run:

which python
python --version
which pip

make sure both are aligned, most probably, python is 2.7 and pip is working on 3.x or pip is coming from anaconda's python version which is highly likely to be 3.x as well

Incase of python redirects to 2.7, and pip redirects to pip3, install pandas using pip install pandas and use python3 file_name.py to run the program.

jQuery - Add active class and remove active from other element on click

You can remove class active from all .tab and use $(this) to target current clicked .tab:

$(document).ready(function() {
    $(".tab").click(function () {
        $(".tab").removeClass("active");
        $(this).addClass("active");     
    });
});

Your code won't work because after removing class active from all .tab, you also add class active to all .tab again. So you need to use $(this) instead of $('.tab') to add the class active only to the clicked .tab anchor

Updated Fiddle

SSH to Vagrant box in Windows?

  1. Install Git Bash (Comes with OpenSSH, as well as grep, find, perl, sed, etc.;)

    If you have Vagrant installed, open appwiz.cpl (AKA Add/Remove Programs) and Repair the Vagrant installation. This will make vagrant add itself to your git-bash path.

  2. Open Git Bash (Via the start menu)

  3. cd ~/vagrant/mybox to your vagrant box'es folder and vagrant ssh

SQL server ignore case in a where expression

I found another solution elsewhere; that is, to use

upper(@yourString)

but everyone here is saying that, in SQL Server, it doesn't matter because it's ignoring case anyway? I'm pretty sure our database is case-sensitive.

Change one value based on another value in pandas

One option is to use Python's slicing and indexing features to logically evaluate the places where your condition holds and overwrite the data there.

Assuming you can load your data directly into pandas with pandas.read_csv then the following code might be helpful for you.

import pandas
df = pandas.read_csv("test.csv")
df.loc[df.ID == 103, 'FirstName'] = "Matt"
df.loc[df.ID == 103, 'LastName'] = "Jones"

As mentioned in the comments, you can also do the assignment to both columns in one shot:

df.loc[df.ID == 103, ['FirstName', 'LastName']] = 'Matt', 'Jones'

Note that you'll need pandas version 0.11 or newer to make use of loc for overwrite assignment operations.


Another way to do it is to use what is called chained assignment. The behavior of this is less stable and so it is not considered the best solution (it is explicitly discouraged in the docs), but it is useful to know about:

import pandas
df = pandas.read_csv("test.csv")
df['FirstName'][df.ID == 103] = "Matt"
df['LastName'][df.ID == 103] = "Jones"

JNZ & CMP Assembly Instructions

I will make a little bit wider answer here.

There are generally speaking two types of conditional jumps in x86:

  1. Arithmetic jumps - like JZ (jump if zero), JC (jump if carry), JNC (jump if not carry), etc.

  2. Comparison jumps - JE (jump if equal), JB (jump if below), JAE (jump if above or equal), etc.

So, use the first type only after arithmetic or logical instructions:

sub  eax, ebx
jnz  .result_is_not_zero 

and  ecx, edx
jz   .the_bit_is_not_set

Use the second group only after CMP instructions:

cmp  eax, ebx
jne  .eax_is_not_equal_to_ebx

cmp  ecx, edx
ja   .ecx_is_above_than_edx

This way, the program becomes more readable and you will never be confused.

Note, that sometimes these instructions are actually synonyms. JZ == JE; JC == JB; JNC == JAE and so on. The full table is following. As you can see, there are only 16 conditional jump instructions, but 30 mnemonics - they are provided to allow creation of more readable source code:

Mnemonic        Condition tested  Description  

jo              OF = 1            overflow 
jno             OF = 0            not overflow 
jc, jb, jnae    CF = 1            carry / below / not above nor equal
jnc, jae, jnb   CF = 0            not carry / above or equal / not below
je, jz          ZF = 1            equal / zero
jne, jnz        ZF = 0            not equal / not zero
jbe, jna        CF or ZF = 1      below or equal / not above
ja, jnbe        CF and ZF = 0      above / not below or equal
js              SF = 1            sign 
jns             SF = 0            not sign 
jp, jpe         PF = 1            parity / parity even 
jnp, jpo        PF = 0            not parity / parity odd 
jl, jnge        SF xor OF = 1     less / not greater nor equal
jge, jnl        SF xor OF = 0     greater or equal / not less
jle, jng    (SF xor OF) or ZF = 1 less or equal / not greater
jg, jnle    (SF xor OF) or ZF = 0 greater / not less nor equal 

Android list view inside a scroll view

I'll leave it here in case anyone will face the same issue. I had to put a ListView inside a ScrollView. ListView with header was not an option by a number of reasons. Neither was an option to use LinearLayout instead of ListView. So I followed the accepted solution, but it didn't work because items in the list had complex layout with multiple rows and each listview item was of variable height. Height was measured not properly. The solution was to measure each item inside ListView Adapter's getView() method.

@Override
public View getView(int position, View view, ViewGroup parent) {
    ViewHolder holder;
    if (view == null) {
        . . .
        view.setTag(holder);
    } else holder = (ViewHolder)view.getTag();
    . . .

    // measure ListView item (to solve 'ListView inside ScrollView' problem)
    view.measure(View.MeasureSpec.makeMeasureSpec(
                    View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
    return view;
}

using OR and NOT in solr query

You can find the follow up to the solr-user group on: solr user mailling list

The prevailing thought is that the NOT operator may only be used to remove results from a query - not just exclude things out of the entire dataset. I happen to like the syntax you suggested mausch - thanks!

What is the shortcut to Auto import all in Android Studio?

You can make short cut key for missing import in android studio which you like

  1. Click on file Menu
  2. Click on Settting
  3. click on key map
  4. Search for "auto-import"
  5. double click on auto import and select add keyboard short cut key
  6. that's all

enter image description here

enter image description here

enter image description here

Note: You can import single missing import using alt+enter which shown in pop up

enter image description here

Get query from java.sql.PreparedStatement

I have made a workaround to solve this problem. Visit the below link for more details http://code-outofbox.blogspot.com/2015/07/java-prepared-statement-print-values.html

Solution:

// Initialize connection
PreparedStatement prepStmt = connection.prepareStatement(sql);

PreparedStatementHelper prepHelper = new PreparedStatementHelper(prepStmt);

// User prepHelper.setXXX(indx++, value);
// .....

try {
   Pattern pattern = Pattern.compile("\\?");
   Matcher matcher = pattern.matcher(sql);
   StringBuffer sb = new StringBuffer();
   int indx = 1;  // Parameter begin with index 1
   while (matcher.find()) {
 matcher.appendReplacement(sb, prepHelper.getParameter(indx++));
   }
   matcher.appendTail(sb);
   LOGGER.debug("Executing Query [" + sb.toString() + "] with Database[" + /*db name*/ + "] ...");
   } catch (Exception ex) {
    LOGGER.debug("Executing Query [" + sql + "] with Database[" +  /*db name*/+ "] ...");
}

/****************************************************/

package java.sql;

import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.Date;
import java.sql.NClob;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;

public class PreparedStatementHelper implements PreparedStatement {

 private PreparedStatement prepStmt;
 private String[] values;

 public PreparedStatementHelper(PreparedStatement prepStmt) throws SQLException {
  this.prepStmt = prepStmt;
  this.values = new String[this.prepStmt.getParameterMetaData().getParameterCount()];
 }

 public String getParameter(int index) {
  String value = this.values[index-1];
  return String.valueOf(value);
 }

 private void setParameter(int index, Object value) {
  String valueStr = "";
  if (value instanceof String) {
   valueStr = "'" + String.valueOf(value).replaceAll("'", "''") + "'";
  } else if (value instanceof Integer) {
   valueStr = String.valueOf(value);
  } else if (value instanceof Date || value instanceof Time || value instanceof Timestamp) {
   valueStr = "'" + String.valueOf(value) + "'";
  } else {
   valueStr = String.valueOf(value);
  }
  this.values[index-1] = valueStr;
 }

 @Override
 public ResultSet executeQuery(String sql) throws SQLException {
  return this.prepStmt.executeQuery(sql);
 }

 @Override
 public int executeUpdate(String sql) throws SQLException {
  return this.prepStmt.executeUpdate(sql);
 }

 @Override
 public void close() throws SQLException {
  this.prepStmt.close();

 }

 @Override
 public int getMaxFieldSize() throws SQLException {
  return this.prepStmt.getMaxFieldSize();
 }

 @Override
 public void setMaxFieldSize(int max) throws SQLException {
  this.prepStmt.setMaxFieldSize(max);
 }

 @Override
 public int getMaxRows() throws SQLException {
  return this.prepStmt.getMaxRows();
 }

 @Override
 public void setMaxRows(int max) throws SQLException {
  this.prepStmt.setMaxRows(max);
 }

 @Override
 public void setEscapeProcessing(boolean enable) throws SQLException {
  this.prepStmt.setEscapeProcessing(enable);
 }

 @Override
 public int getQueryTimeout() throws SQLException {
  return this.prepStmt.getQueryTimeout();
 }

 @Override
 public void setQueryTimeout(int seconds) throws SQLException {
  this.prepStmt.setQueryTimeout(seconds);
 }

 @Override
 public void cancel() throws SQLException {
  this.prepStmt.cancel();
 }

 @Override
 public SQLWarning getWarnings() throws SQLException {
  return this.prepStmt.getWarnings();
 }

 @Override
 public void clearWarnings() throws SQLException {
  this.prepStmt.clearWarnings();
 }

 @Override
 public void setCursorName(String name) throws SQLException {
  this.prepStmt.setCursorName(name);
 }

 @Override
 public boolean execute(String sql) throws SQLException {
  return this.prepStmt.execute(sql);
 }

 @Override
 public ResultSet getResultSet() throws SQLException {
  return this.prepStmt.getResultSet();
 }

 @Override
 public int getUpdateCount() throws SQLException {
  return this.prepStmt.getUpdateCount();
 }

 @Override
 public boolean getMoreResults() throws SQLException {
  return this.prepStmt.getMoreResults();
 }

 @Override
 public void setFetchDirection(int direction) throws SQLException {
  this.prepStmt.setFetchDirection(direction);
 }

 @Override
 public int getFetchDirection() throws SQLException {
  return this.prepStmt.getFetchDirection();
 }

 @Override
 public void setFetchSize(int rows) throws SQLException {
  this.prepStmt.setFetchSize(rows);
 }

 @Override
 public int getFetchSize() throws SQLException {
  return this.prepStmt.getFetchSize();
 }

 @Override
 public int getResultSetConcurrency() throws SQLException {
  return this.prepStmt.getResultSetConcurrency();
 }

 @Override
 public int getResultSetType() throws SQLException {
  return this.prepStmt.getResultSetType();
 }

 @Override
 public void addBatch(String sql) throws SQLException {
  this.prepStmt.addBatch(sql);
 }

 @Override
 public void clearBatch() throws SQLException {
  this.prepStmt.clearBatch();
 }

 @Override
 public int[] executeBatch() throws SQLException {
  return this.prepStmt.executeBatch();
 }

 @Override
 public Connection getConnection() throws SQLException {
  return this.prepStmt.getConnection();
 }

 @Override
 public boolean getMoreResults(int current) throws SQLException {
  return this.prepStmt.getMoreResults(current);
 }

 @Override
 public ResultSet getGeneratedKeys() throws SQLException {
  return this.prepStmt.getGeneratedKeys();
 }

 @Override
 public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
  return this.prepStmt.executeUpdate(sql, autoGeneratedKeys);
 }

 @Override
 public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
  return this.prepStmt.executeUpdate(sql, columnIndexes);
 }

 @Override
 public int executeUpdate(String sql, String[] columnNames) throws SQLException {
  return this.prepStmt.executeUpdate(sql, columnNames);
 }

 @Override
 public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
  return this.prepStmt.execute(sql, autoGeneratedKeys);
 }

 @Override
 public boolean execute(String sql, int[] columnIndexes) throws SQLException {
  return this.prepStmt.execute(sql, columnIndexes);
 }

 @Override
 public boolean execute(String sql, String[] columnNames) throws SQLException {
  return this.prepStmt.execute(sql, columnNames);
 }

 @Override
 public int getResultSetHoldability() throws SQLException {
  return this.prepStmt.getResultSetHoldability();
 }

 @Override
 public boolean isClosed() throws SQLException {
  return this.prepStmt.isClosed();
 }

 @Override
 public void setPoolable(boolean poolable) throws SQLException {
  this.prepStmt.setPoolable(poolable);
 }

 @Override
 public boolean isPoolable() throws SQLException {
  return this.prepStmt.isPoolable();
 }

 @Override
 public <T> T unwrap(Class<T> iface) throws SQLException {
  return this.prepStmt.unwrap(iface);
 }

 @Override
 public boolean isWrapperFor(Class<?> iface) throws SQLException {
  return this.prepStmt.isWrapperFor(iface);
 }

 @Override
 public ResultSet executeQuery() throws SQLException {
  return this.prepStmt.executeQuery();
 }

 @Override
 public int executeUpdate() throws SQLException {
  return this.prepStmt.executeUpdate();
 }

 @Override
 public void setNull(int parameterIndex, int sqlType) throws SQLException {
  this.prepStmt.setNull(parameterIndex, sqlType);
  setParameter(parameterIndex, null);
 }

 @Override
 public void setBoolean(int parameterIndex, boolean x) throws SQLException {
  this.prepStmt.setBoolean(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setByte(int parameterIndex, byte x) throws SQLException {
  this.prepStmt.setByte(parameterIndex, x);
  // TODO Add to tree set
 }

 @Override
 public void setShort(int parameterIndex, short x) throws SQLException {
  this.prepStmt.setShort(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setInt(int parameterIndex, int x) throws SQLException {
  this.prepStmt.setInt(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setLong(int parameterIndex, long x) throws SQLException {
  this.prepStmt.setLong(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setFloat(int parameterIndex, float x) throws SQLException {
  this.prepStmt.setFloat(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setDouble(int parameterIndex, double x) throws SQLException {
  this.prepStmt.setDouble(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException {
  this.prepStmt.setBigDecimal(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setString(int parameterIndex, String x) throws SQLException {
  this.prepStmt.setString(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setBytes(int parameterIndex, byte[] x) throws SQLException {
  this.prepStmt.setBytes(parameterIndex, x);
  // TODO Add to tree set
 }

 @Override
 public void setDate(int parameterIndex, Date x) throws SQLException {
  this.prepStmt.setDate(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setTime(int parameterIndex, Time x) throws SQLException {
  this.prepStmt.setTime(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {
  this.prepStmt.setTimestamp(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException {
  this.prepStmt.setAsciiStream(parameterIndex, x, length);
 }

 @SuppressWarnings("deprecation")
 @Override
 public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException {
  this.prepStmt.setUnicodeStream(parameterIndex, x, length);
 }

 @Override
 public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException {
  this.prepStmt.setBinaryStream(parameterIndex, x, length);
 }

 @Override
 public void clearParameters() throws SQLException {
  this.prepStmt.clearParameters();
 }

 @Override
 public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {
  this.prepStmt.setObject(parameterIndex, x, targetSqlType);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setObject(int parameterIndex, Object x) throws SQLException {
  this.prepStmt.setObject(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public boolean execute() throws SQLException {
  return this.prepStmt.execute();
 }

 @Override
 public void addBatch() throws SQLException {
  this.prepStmt.addBatch();
 }

 @Override
 public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException {
  this.prepStmt.setCharacterStream(parameterIndex, reader, length);
 }

 @Override
 public void setRef(int parameterIndex, Ref x) throws SQLException {
  this.prepStmt.setRef(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setBlob(int parameterIndex, Blob x) throws SQLException {
  this.prepStmt.setBlob(parameterIndex, x);
 }

 @Override
 public void setClob(int parameterIndex, Clob x) throws SQLException {
  this.prepStmt.setClob(parameterIndex, x);
 }

 @Override
 public void setArray(int parameterIndex, Array x) throws SQLException {
  this.prepStmt.setArray(parameterIndex, x);
  // TODO Add to tree set
 }

 @Override
 public ResultSetMetaData getMetaData() throws SQLException {
  return this.prepStmt.getMetaData();
 }

 @Override
 public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException {
  this.prepStmt.setDate(parameterIndex, x, cal);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException {
  this.prepStmt.setTime(parameterIndex, x, cal);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException {
  this.prepStmt.setTimestamp(parameterIndex, x, cal);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException {
  this.prepStmt.setNull(parameterIndex, sqlType, typeName);
  setParameter(parameterIndex, null);
 }

 @Override
 public void setURL(int parameterIndex, URL x) throws SQLException {
  this.prepStmt.setURL(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public ParameterMetaData getParameterMetaData() throws SQLException {
  return this.prepStmt.getParameterMetaData();
 }

 @Override
 public void setRowId(int parameterIndex, RowId x) throws SQLException {
  this.prepStmt.setRowId(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setNString(int parameterIndex, String value) throws SQLException {
  this.prepStmt.setNString(parameterIndex, value);
  setParameter(parameterIndex, value);
 }

 @Override
 public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException {
  this.prepStmt.setNCharacterStream(parameterIndex, value, length);
 }

 @Override
 public void setNClob(int parameterIndex, NClob value) throws SQLException {
  this.prepStmt.setNClob(parameterIndex, value);
 }

 @Override
 public void setClob(int parameterIndex, Reader reader, long length) throws SQLException {
  this.prepStmt.setClob(parameterIndex, reader, length);
 }

 @Override
 public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException {
  this.prepStmt.setBlob(parameterIndex, inputStream, length);
 }

 @Override
 public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException {
  this.prepStmt.setNClob(parameterIndex, reader, length);
 }

 @Override
 public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException {
  this.prepStmt.setSQLXML(parameterIndex, xmlObject);
  setParameter(parameterIndex, xmlObject);
 }

 @Override
 public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException {
  this.prepStmt.setObject(parameterIndex, x, targetSqlType, scaleOrLength);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException {
  this.prepStmt.setAsciiStream(parameterIndex, x, length);
 }

 @Override
 public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException {
  this.prepStmt.setBinaryStream(parameterIndex, x, length);
 }

 @Override
 public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException {
  this.prepStmt.setCharacterStream(parameterIndex, reader, length);
 }

 @Override
 public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException {
  this.prepStmt.setAsciiStream(parameterIndex, x);
  // TODO Add to tree set
 }

 @Override
 public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException {
  this.prepStmt.setBinaryStream(parameterIndex, x);
 }

 @Override
 public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException {
  this.prepStmt.setCharacterStream(parameterIndex, reader);
 }

 @Override
 public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException {
  this.prepStmt.setNCharacterStream(parameterIndex, value);
 }

 @Override
 public void setClob(int parameterIndex, Reader reader) throws SQLException {
  this.prepStmt.setClob(parameterIndex, reader);
  // TODO Add to tree set
 }

 @Override
 public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException {
  this.prepStmt.setBlob(parameterIndex, inputStream);
 }

 @Override
 public void setNClob(int parameterIndex, Reader reader) throws SQLException {
  this.prepStmt.setNClob(parameterIndex, reader);
 }

}

Deleting an object in java?

You can remove the reference using null.

Let's say You have class A:

A a = new A();
a=null;

last statement will remove the reference of the object a and that object will be "garbage collected" by JVM. It is one of the easiest ways to do this.

Event binding on dynamically created elements?

<html>
    <head>
        <title>HTML Document</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    </head>

    <body>
        <div id="hover-id">
            Hello World
        </div>

        <script>
            jQuery(document).ready(function($){
                $(document).on('mouseover', '#hover-id', function(){
                    $(this).css('color','yellowgreen');
                });

                $(document).on('mouseout', '#hover-id', function(){
                    $(this).css('color','black');
                });
            });
        </script>
    </body>
</html>

PHP append one array to another (not array_push or +)

Why not use

$appended = array_merge($a,$b); 

Why don't you want to use this, the correct, built-in method.

The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported

Another solution is to migrate the database to e.g 2012 when you "export" the DB from e.g. Sql Server manager 2014. This is done in menu Tasks-> generate scripts when right-click on DB. Just follow this instruction:

https://www.mssqltips.com/sqlservertip/2810/how-to-migrate-a-sql-server-database-to-a-lower-version/

It generates an scripts with everything and then in your SQL server manager e.g. 2012 run the script as specified in the instruction. I have performed the test with success.

Using multiple .cpp files in c++ program?

You should have header files (.h) that contain the function's declaration, then a corresponding .cpp file that contains the definition. You then include the header file everywhere you need it. Note that the .cpp file that contains the definitions also needs to include (it's corresponding) header file.

// main.cpp
#include "second.h"
int main () {
    secondFunction();
}

// second.h
void secondFunction();

// second.cpp
#include "second.h"
void secondFunction() {
   // do stuff
}

Unresolved external symbol on static class members

Since this is the first SO thread that seemed to come up for me when searching for "unresolved externals with static const members" in general, I'll leave another hint to solve one problem with unresolved externals here:

For me, the thing that I forgot was to mark my class definition __declspec(dllexport), and when called from another class (outside that class's dll's boundaries), I of course got the my unresolved external error.
Still, easy to forget when you're changing an internal helper class to a one accessible from elsewhere, so if you're working in a dynamically linked project, you might as well check that, too.

How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable

With JBoss 7.2(Undertow) and PrimeFaces 6.0 org.primefaces.webapp.filter.FileUploadFilter should be removed from web.xml and context param file uploader should be set to native:

<context-param>
    <param-name>primefaces.UPLOADER</param-name>
    <param-value>native</param-value>
</context-param>

Integrating MySQL with Python in Windows

upvoted itsadok's answer because it led me to the installation for python 2.7 as well, which is located here: http://www.codegood.com/archives/129

Black transparent overlay on image hover with only CSS?

Here's a good way using :after on the image div, instead of the extra overlay div: http://jsfiddle.net/Zf5am/576/

<div class="image">
    <img src="http://www.newyorker.com/online/blogs/photobooth/NASAEarth-01.jpg" alt="" />
</div>

.image {position:relative; border:1px solid black; width:200px; height:200px;}
.image img {max-width:100%; max-height:100%;}
.image:hover:after {content:""; position:absolute; top:0; left:0; bottom:0; right:0; background-color: rgba(0,0,0,0.3);}

how to fix java.lang.IndexOutOfBoundsException

You want to get an element from an empty array. That's why the Size: 0 from the exception

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

So you cant do lstpp.get(0) until you fill the array.

git stash blunder: git stash pop and ended up with merge conflicts

If, like me, what you usually want is to overwrite the contents of the working directory with that of the stashed files, and you still get a conflict, then what you want is to resolve the conflict using git checkout --theirs -- . from the root.

After that, you can git reset to bring all the changes from the index to the working directory, since apparently in case of conflict the changes to non-conflicted files stay in the index.

You may also want to run git stash drop [<stash name>] afterwards, to get rid of the stash, because git stash pop doesn't delete it in case of conflicts.

How to dump a table to console?

found this:

-- Print contents of `tbl`, with indentation.
-- `indent` sets the initial level of indentation.
function tprint (tbl, indent)
  if not indent then indent = 0 end
  for k, v in pairs(tbl) do
    formatting = string.rep("  ", indent) .. k .. ": "
    if type(v) == "table" then
      print(formatting)
      tprint(v, indent+1)
    elseif type(v) == 'boolean' then
      print(formatting .. tostring(v))      
    else
      print(formatting .. v)
    end
  end
end

from here https://gist.github.com/ripter/4270799

works pretty good for me...

If statement in aspx page

A complete answer for optional content in the header of a VB.NET aspx page using a master page:

 <%@ Page Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="some_vb_page.aspx.vb" Inherits="some_vb_page" %> 
 <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">          
     <% If Request.QueryString("id_query_param") = 123 Then 'Add some VB comment here, 
         'which will not be visible in the rendered source code of the aspx page later %>        
         <!-- add some html content depending on -->
         <!-- the condition in the if statement: -->                
         <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js" type="text/javascript" charset="utf-8"></script>
     <% End If %>
</asp:Content>

Where your current page url is something like:

http://mywebpage.com/some_vb_page.aspx?id_query_param=123

Egit rejected non-fast-forward

In the meantime (while you were updating your project), other commits have been made to the 'master' branch. Therefore, you must pull those changes first to be able to push your changes.

Using an if statement to check if a div is empty

if (typeof($('#container .prateleira')[0]) === 'undefined') {
    $('#ctl00_Conteudo_ctrPaginaSistemaAreaWrapper').css('display','none');
}

Is it possible to style a select box?

As for CSS, Mozilla seems to be the most friendly, especially from FF 3.5+. Webkit browsers mostly just do their own thing, and ignore any style. IE is very limited, though IE8 lets you at least style border color/width.

The following actually looks fairly nice in FF 3.5+ (picking your color preference, of course):

select {
    -moz-border-radius: 4px;
    -moz-box-shadow: 1px 1px 5px #cfcfcf inset;
    border: 1px solid #cfcfcf;
    vertical-align: middle;
    background-color: transparent;
}
option {
    background-color: #fef5e6;
    border-bottom: 1px solid #ebdac0;
    border-right: 1px solid #d6bb86;
    border-left: 1px solid #d6bb86;
}
option:hover {
    cursor: pointer;
}

But when it comes to IE, you have to disable the background color on the option if you don't want it to display when the option menu isn't pulled down. And, as I said, webkit does its own thing.

MySQL config file location - redhat linux server

In the docker containers(centos based images) it is located at

/etc/mysql/my.cnf

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

I'd like to add one additional piece of information since the accepted answer above didn't fix my errors completely.

In my scenario, I have a parent component, which holds a child component. And that child component also contains another component.

So, my parent component's spec file need to have the declaration of the child component, AS WELL AS THE CHILD'S CHILD COMPONENT. That finally fixed the issue for me.

Angular 2 Scroll to bottom (Chat style)

this.contentList.nativeElement.scrollTo({left: 0 , top: this.contentList.nativeElement.scrollHeight, behavior: 'smooth'});

How can I customize the tab-to-space conversion factor?

I tried to change editor.tabSize to 4, but .editorConfig overrides whatever settings I had specified, so there is no need to change any configuration in user settings. You just need to edit .editorConfig file:

set indent_size = 4

JavaScript hard refresh of current page

window.location.href = window.location.href

Function overloading in Javascript - Best practices

I've been using this function to prettify my overloads for years:

function overload(){
  const fs = arguments, fallback = fs[fs.length - 1];
  return function(){
    const f = fs[arguments.length] || (arguments.length >= fs.length ? fallback : null);
    return f.apply(this, arguments);
  }
}

Demostrated:

function curry1(f){
  return curry2(f, f.length);
}

function curry2(f, minimum){
  return function(...applied){
    if (applied.length >= minimum) {
      return f.apply(this, applied);
    } else {
      return curry2(function(...args){
        return f.apply(this, applied.concat(args));
      }, minimum - applied.length);
    }
  }
}

export const curry = overload(null, curry1, curry2);

Take a look at jQuery's off method:

  function off( types, selector, fn ) {
    var handleObj, type;
    if ( types && types.preventDefault && types.handleObj ) {

        // ( event )  dispatched jQuery.Event
        handleObj = types.handleObj;
        jQuery( types.delegateTarget ).off(
            handleObj.namespace ?
                handleObj.origType + "." + handleObj.namespace :
                handleObj.origType,
            handleObj.selector,
            handleObj.handler
        );
        return this;
    }
    if ( typeof types === "object" ) {

        // ( types-object [, selector] )
        for ( type in types ) {
            this.off( type, selector, types[ type ] );
        }
        return this;
    }
    if ( selector === false || typeof selector === "function" ) {

        // ( types [, fn] )
        fn = selector;
        selector = undefined;
    }
    if ( fn === false ) {
        fn = returnFalse;
    }
    return this.each( function() {
        jQuery.event.remove( this, types, fn, selector );
    } );
  }

Many overloaded functions when optimized for performance are nigh unreadable. You have to decipher the head of the function. This is perhaps faster than using an overload function like I provide; however, it is slower from a human perspective with regard to identifying which overload was called.

What is the command to exit a Console application in C#?

Several options, by order of most appropriate way:

  1. Return an int from the Program.Main method
  2. Throw an exception and don't handle it anywhere (use for unexpected error situations)
  3. To force termination elsewhere, System.Environment.Exit (not portable! see below)

Edited 9/2013 to improve readability

Returning with a specific exit code: As Servy points out in the comments, you can declare Main with an int return type and return an error code that way. So there really is no need to use Environment.Exit unless you need to terminate with an exit code and can't possibly do it in the Main method. Most probably you can avoid that by throwing an exception, and returning an error code in Main if any unhandled exception propagates there. If the application is multi-threaded you'll probably need even more boilerplate to properly terminate with an exit code so you may be better off just calling Environment.Exit.

Another point against using Evironment.Exit - even when writing multi-threaded applications - is reusability. If you ever want to reuse your code in an environment that makes Environment.Exit irrelevant (such as a library that may be used in a web server), the code will not be portable. The best solution still is, in my opinion, to always use exceptions and/or return values that represent that the method reached some error/finish state. That way, you can always use the same code in any .NET environment, and in any type of application. If you are writing specifically an app that needs to return an exit code or to terminate in a way similar to what Environment.Exit does, you can then go ahead and wrap the thread at the highest level and handle the errors/exceptions as needed.

Select a dummy column with a dummy value in SQL?

Try this:

select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;

How do I minimize the command prompt from my bat file

Another option that works fine for me is to use ConEmu, see http://conemu.github.io/en/ConEmuArgs.html

"C:\Program Files\ConEmu\ConEmu64.exe" -min -run myfile.bat

What's the difference between the atomic and nonatomic attributes?

Atomic

  • is the default behavior
  • will ensure the present process is completed by the CPU, before another process accesses the variable
  • is not fast, as it ensures the process is completed entirely

Non-Atomic

  • is NOT the default behavior
  • faster (for synthesized code, that is, for variables created using @property and @synthesize)
  • not thread-safe
  • may result in unexpected behavior, when two different process access the same variable at the same time

Reusing output from last command in Bash

Not sure exactly what you're needing this for, so this answer may not be relevant. You can always save the output of a command: netstat >> output.txt, but I don't think that's what you're looking for.

There are of course programming options though; you could simply get a program to read the text file above after that command is run and associate it with a variable, and in Ruby, my language of choice, you can create a variable out of command output using 'backticks':

output = `ls`                       #(this is a comment) create variable out of command

if output.include? "Downloads"      #if statement to see if command includes 'Downloads' folder
print "there appears to be a folder named downloads in this directory."
else
print "there is no directory called downloads in this file."
end

Stick this in a .rb file and run it: ruby file.rb and it will create a variable out of the command and allow you to manipulate it.

Bootstrap modal link

Please remove . from your target it should be a id

<a href="#bannerformmodal" data-toggle="modal" data-target="#bannerformmodal">Load me</a>

Also you have to give your modal id like below

<div class="modal fade bannerformmodal" tabindex="-1" role="dialog" aria-labelledby="bannerformmodal" aria-hidden="true" id="bannerformmodal">

Here is the solution in a fiddle.

FIFO class in Java

Try ArrayDeque or LinkedList, which both implement the Queue interface.

http://docs.oracle.com/javase/6/docs/api/java/util/ArrayDeque.html

Requery a subform from another form?

All your controls are belong to us!

Fionnuala answered this correctly but skimmers like me would find it easy to miss the point.

You don't refresh the subFORM you refresh the subform CONTROL. In fact, if you check with allforms() the subForm isn't even loaded as far as access is concerned.

On the main form look at the label the subform wizard provided or select the subform by clicking once or on the border around it and look at the "caption" in the "Other" tab in properties. That's the name you use for requerying, not the name of the form that appears in the navigation panel.

In my case I had a subform called frmInvProdSub and I tried for many hours to figure out why Access didn't think it existed. I gave up, deleted the form and re-created it. The very last step is telling it what you want to call the control so I called it frmInvProdSub and finished the wizard. Then I tried and voila, it worked!

When I looked at the form name in the navigation window I realized I'd forgotten to put "Sub" in the name! That's when it clicked. The CONTROL is called frmInvProdSub, not the form and using the control name works.

Of course if both names are identical then you didn't have this problem lol.

Anaconda export Environment file

  1. First activate your conda environment (the one u want to export/backup)
conda activate myEnv
  1. Export all packages to a file (myEnvBkp.txt)
conda list --explicit > myEnvBkp.txt
  1. Restore/import the environment:
conda create --name myEnvRestored --file myEnvBkp.txt

Sending mass email using PHP

Do not send email to 5,000 people using standard PHP tools. You'll get banned by most ISPs in seconds and never even know it. You should either use some mailing lists software or an Email Service Provider do to this.

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

This is common, you will need to do the following steps:

1- Right click on the project

2- Build path

3- Configure Build Path

4- Remove jars/projects that had moved from their old path

5- clean the project

6- build the project "if not automatically built"

7- Add the jars/projects using their new locations

Run and that is it!

How to turn off page breaks in Google Docs?

Turn off "Print Layout" from the "View" menu.

How to record phone calls in android?

The accepted answer is perfect, except it does not record outgoing calls. Note that for outgoing calls it is not possible (as near as I can tell from scouring many posts) to detect when the call is actually answered (if anybody can find a way other than scouring notifications or logs please let me know). The easiest solution is to just start recording straight away when the outgoing call is placed and stop recording when IDLE is detected. Just adding the same class as above with outgoing recording in this manner for completeness:

private void startRecord(String seed) {
        String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
        File sampleDir = new File(Environment.getExternalStorageDirectory(), "/TestRecordingDasa1");
        if (!sampleDir.exists()) {
            sampleDir.mkdirs();
        }
        String file_name = "Record" + seed;
        try {
            audiofile = File.createTempFile(file_name, ".amr", sampleDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();

        recorder = new MediaRecorder();

        recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        recorder.setOutputFile(audiofile.getAbsolutePath());
        try {
            recorder.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        recorder.start();
        recordstarted = true;
    }


    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION_IN)) {
            if ((bundle = intent.getExtras()) != null) {
                state = bundle.getString(TelephonyManager.EXTRA_STATE);
                if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                    inCall = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
                    wasRinging = true;
                    Toast.makeText(context, "IN : " + inCall, Toast.LENGTH_LONG).show();
                } else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
                    if (wasRinging == true) {

                        Toast.makeText(context, "ANSWERED", Toast.LENGTH_LONG).show();

                        startRecord("incoming");
                    }
                } else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                    wasRinging = false;
                    Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
                    if (recordstarted) {
                        recorder.stop();
                        recordstarted = false;
                    }
                }
            }
        } else if (intent.getAction().equals(ACTION_OUT)) {
            if ((bundle = intent.getExtras()) != null) {
                outCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
                Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show();
                startRecord("outgoing");
                if ((bundle = intent.getExtras()) != null) {
                    state = bundle.getString(TelephonyManager.EXTRA_STATE);
                    if (state != null) {
                        if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                            wasRinging = false;
                            Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
                            if (recordstarted) {
                                recorder.stop();
                                recordstarted = false;
                            }
                        }
                    }


                }
            }
        }
    }

Adding up BigDecimals using Streams

If you don't mind a third party dependency, there is a class named Collectors2 in Eclipse Collections which contains methods returning Collectors for summing and summarizing BigDecimal and BigInteger. These methods take a Function as a parameter so you can extract a BigDecimal or BigInteger value from an object.

List<BigDecimal> list = mList(
        BigDecimal.valueOf(0.1),
        BigDecimal.valueOf(1.1),
        BigDecimal.valueOf(2.1),
        BigDecimal.valueOf(0.1));

BigDecimal sum =
        list.stream().collect(Collectors2.summingBigDecimal(e -> e));
Assert.assertEquals(BigDecimal.valueOf(3.4), sum);

BigDecimalSummaryStatistics statistics =
        list.stream().collect(Collectors2.summarizingBigDecimal(e -> e));
Assert.assertEquals(BigDecimal.valueOf(3.4), statistics.getSum());
Assert.assertEquals(BigDecimal.valueOf(0.1), statistics.getMin());
Assert.assertEquals(BigDecimal.valueOf(2.1), statistics.getMax());
Assert.assertEquals(BigDecimal.valueOf(0.85), statistics.getAverage());

Note: I am a committer for Eclipse Collections.

Using Alert in Response.Write Function in ASP.NET

string str = "Error mEssage";
Response.Write("<script language=javascript>alert('"+str+"');</script>");

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

A solution kind of delicate

class DotDict(dict):

    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

    def __getattr__(self, key):

        def typer(candidate):
            if isinstance(candidate, dict):
                return DotDict(candidate)

            if isinstance(candidate, str):  # iterable but no need to iter
                return candidate

            try:  # other iterable are processed as list
                return [typer(item) for item in candidate]
            except TypeError:
                return candidate

            return candidate

        return typer(dict.get(self, key))

In C#, how to check if a TCP port is available?

Since you're using a TcpClient, that means you're checking open TCP ports. There are lots of good objects available in the System.Net.NetworkInformation namespace.

Use the IPGlobalProperties object to get to an array of TcpConnectionInformation objects, which you can then interrogate about endpoint IP and port.


 int port = 456; //<--- This is your value
 bool isAvailable = true;

 // Evaluate current system tcp connections. This is the same information provided
 // by the netstat command line application, just in .Net strongly-typed object
 // form.  We will look through the list, and if our port we would like to use
 // in our TcpClient is occupied, we will set isAvailable to false.
 IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
 TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();

 foreach (TcpConnectionInformation tcpi in tcpConnInfoArray)
 {
   if (tcpi.LocalEndPoint.Port==port)
   {
     isAvailable = false;
     break;
   }
 }

 // At this point, if isAvailable is true, we can proceed accordingly.

Clear the value of bootstrap-datepicker

Current version 1.4.0 has clearBtn option:

$('.datepicker').datepicker({
    clearBtn: true
});

Besides adding button to interface it allows to delete value from input box manually.

What is the python keyword "with" used for?

Explanation from the Preshing on Programming blog:

It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it:

 with open('output.txt', 'w') as f:
     f.write('Hi there!')

The above with statement will automatically close the file after the nested block of code. (Continue reading to see exactly how the close occurs.) The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too.

How to properly use jsPDF library

how about in vuejs how is it applicable?

_x000D_
_x000D_
function onClick() {_x000D_
  var pdf = new jsPDF('p', 'pt', 'letter');_x000D_
  pdf.canvas.height = 72 * 11;_x000D_
  pdf.canvas.width = 72 * 8.5;_x000D_
_x000D_
  pdf.fromHTML(document.body);_x000D_
_x000D_
  pdf.save('test.pdf');_x000D_
};_x000D_
_x000D_
var element = document.getElementById("clickbind");_x000D_
element.addEventListener("click", onClick);
_x000D_
<h1>Dsdas</h1>_x000D_
_x000D_
<a id="clickbind" href="#">Click</a>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
_x000D_
_x000D_
_x000D_

LINQ syntax where string value is not null or empty

This will work fine with Linq to Objects. However, some LINQ providers have difficulty running CLR methods as part of the query. This is expecially true of some database providers.

The problem is that the DB providers try to move and compile the LINQ query as a database query, to prevent pulling all of the objects across the wire. This is a good thing, but does occasionally restrict the flexibility in your predicates.

Unfortunately, without checking the provider documentation, it's difficult to always know exactly what will or will not be supported directly in the provider. It looks like your provider allows comparisons, but not the string check. I'd guess that, in your case, this is probably about as good of an approach as you can get. (It's really not that different from the IsNullOrEmpty check, other than creating the "string.Empty" instance for comparison, but that's minor.)

Trigger back-button functionality on button click in Android

layout.xml

<Button
    android:id="@+id/buttonBack"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="finishActivity"
    android:text="Back" />

Activity.java

public void finishActivity(View v){
    finish();
}

Related:

Only detect click event on pseudo-element

Short Answer:

I did it. I wrote a function for dynamic usage for all the little people out there...

Working example which displays on the page

Working example logging to the console

Long Answer:

...Still did it.

It took me awhile to do it, since a psuedo element is not really on the page. While some of the answers above work in SOME scenarios, they ALL fail to be both dynamic and work in a scenario in which an element is both unexpected in size and position(such as absolute positioned elements overlaying a portion of the parent element). Mine does not.

Usage:

//some element selector and a click event...plain js works here too
$("div").click(function() {
    //returns an object {before: true/false, after: true/false}
    psuedoClick(this);

    //returns true/false
    psuedoClick(this).before;

    //returns true/false
    psuedoClick(this).after;

});

How it works:

It grabs the height, width, top, and left positions(based on the position away from the edge of the window) of the parent element and grabs the height, width, top, and left positions(based on the edge of the parent container) and compares those values to determine where the psuedo element is on the screen.

It then compares where the mouse is. As long as the mouse is in the newly created variable range then it returns true.

Note:

It is wise to make the parent element RELATIVE positioned. If you have an absolute positioned psuedo element, this function will only work if it is positioned based on the parent's dimensions(so the parent has to be relative...maybe sticky or fixed would work too....I dont know).

Code:

function psuedoClick(parentElem) {

    var beforeClicked,
      afterClicked;

  var parentLeft = parseInt(parentElem.getBoundingClientRect().left, 10),
      parentTop = parseInt(parentElem.getBoundingClientRect().top, 10);

  var parentWidth = parseInt(window.getComputedStyle(parentElem).width, 10),
      parentHeight = parseInt(window.getComputedStyle(parentElem).height, 10);

  var before = window.getComputedStyle(parentElem, ':before');

  var beforeStart = parentLeft + (parseInt(before.getPropertyValue("left"), 10)),
      beforeEnd = beforeStart + parseInt(before.width, 10);

  var beforeYStart = parentTop + (parseInt(before.getPropertyValue("top"), 10)),
      beforeYEnd = beforeYStart + parseInt(before.height, 10);

  var after = window.getComputedStyle(parentElem, ':after');

  var afterStart = parentLeft + (parseInt(after.getPropertyValue("left"), 10)),
      afterEnd = afterStart + parseInt(after.width, 10);

  var afterYStart = parentTop + (parseInt(after.getPropertyValue("top"), 10)),
      afterYEnd = afterYStart + parseInt(after.height, 10);

  var mouseX = event.clientX,
      mouseY = event.clientY;

  beforeClicked = (mouseX >= beforeStart && mouseX <= beforeEnd && mouseY >= beforeYStart && mouseY <= beforeYEnd ? true : false);

  afterClicked = (mouseX >= afterStart && mouseX <= afterEnd && mouseY >= afterYStart && mouseY <= afterYEnd ? true : false);

  return {
    "before" : beforeClicked,
    "after"  : afterClicked

  };      

}

Support:

I dont know....it looks like ie is dumb and likes to return auto as a computed value sometimes. IT SEEMS TO WORK WELL IN ALL BROWSERS IF DIMENSIONS ARE SET IN CSS. So...set your height and width on your psuedo elements and only move them with top and left. I recommend using it on things that you are okay with it not working on. Like an animation or something. Chrome works...as usual.

C++ Object Instantiation

I had the same problem in Visual Studio. You have to use:

yourClass->classMethod();

rather than:

yourClass.classMethod();

Differences between fork and exec

I think some concepts from "Advanced Unix Programming" by Marc Rochkind were helpful in understanding the different roles of fork()/exec(), especially for someone used to the Windows CreateProcess() model:

A program is a collection of instructions and data that is kept in a regular file on disk. (from 1.1.2 Programs, Processes, and Threads)

.

In order to run a program, the kernel is first asked to create a new process, which is an environment in which a program executes. (also from 1.1.2 Programs, Processes, and Threads)

.

It’s impossible to understand the exec or fork system calls without fully understanding the distinction between a process and a program. If these terms are new to you, you may want to go back and review Section 1.1.2. If you’re ready to proceed now, we’ll summarize the distinction in one sentence: A process is an execution environment that consists of instruction, user-data, and system-data segments, as well as lots of other resources acquired at runtime, whereas a program is a file containing instructions and data that are used to initialize the instruction and user-data segments of a process. (from 5.3 exec System Calls)

Once you understand the distinction between a program and a process, the behavior of fork() and exec() function can be summarized as:

  • fork() creates a duplicate of the current process
  • exec() replaces the program in the current process with another program

(this is essentially a simplified 'for dummies' version of paxdiablo's much more detailed answer)

What is the standard Python docstring format?

PEP-8 is the official python coding standard. It contains a section on docstrings, which refers to PEP-257 -- a complete specification for docstrings.

regex for zip-code

^\d{5}(?:[-\s]\d{4})?$
  • ^ = Start of the string.
  • \d{5} = Match 5 digits (for condition 1, 2, 3)
  • (?:…) = Grouping
  • [-\s] = Match a space (for condition 3) or a hyphen (for condition 2)
  • \d{4} = Match 4 digits (for condition 2, 3)
  • …? = The pattern before it is optional (for condition 1)
  • $ = End of the string.

Css transition from display none to display block, navigation with subnav

As you know the display property cannot be animated BUT just by having it in your CSS it overrides the visibility and opacity transitions.

The solution...just removed the display properties.

_x000D_
_x000D_
nav.main ul ul {_x000D_
  position: absolute;_x000D_
  list-style: none;_x000D_
  opacity: 0;_x000D_
  visibility: hidden;_x000D_
  padding: 10px;_x000D_
  background-color: rgba(92, 91, 87, 0.9);_x000D_
  -webkit-transition: opacity 600ms, visibility 600ms;_x000D_
  transition: opacity 600ms, visibility 600ms;_x000D_
}_x000D_
nav.main ul li:hover ul {_x000D_
  visibility: visible;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<nav class="main">_x000D_
  <ul>_x000D_
    <li>_x000D_
      <a href="">Lorem</a>_x000D_
      <ul>_x000D_
        <li><a href="">Ipsum</a>_x000D_
        </li>_x000D_
        <li><a href="">Dolor</a>_x000D_
        </li>_x000D_
        <li><a href="">Sit</a>_x000D_
        </li>_x000D_
        <li><a href="">Amet</a>_x000D_
        </li>_x000D_
      </ul>_x000D_
    </li>_x000D_
  </ul>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

How do I diff the same file between two different commits on the same branch?

You can also compare two different files in two different revisions, like this:

git diff <revision_1>:<file_1> <revision_2>:<file_2>

Python - Create list with numbers between 2 values?

The most elegant way to do this is by using the range function however if you want to re-create this logic you can do something like this :

def custom_range(*args):
    s = slice(*args)
    start, stop, step = s.start, s.stop, s.step
    if 0 == step:
        raise ValueError("range() arg 3 must not be zero")
    i = start
    while i < stop if step > 0 else i > stop:
        yield i
        i += step

>>> [x for x in custom_range(10, 3, -1)]

This produces the output:

[10, 9, 8, 7, 6, 5, 4]

As expressed before by @Jared, the best way is to use the range or numpy.arrange however I find the code interesting to be shared.

Windows batch - concatenate multiple text files into one

Place all files need to copied in a separate folder, for ease place them in c drive.

Open Command Prompt - windows>type cmd>select command prompt.

You can see the default directory pointing - Ex : C:[Folder_Name]>. Change the directory to point to the folder which you have placed files to be copied, using ' cd [Folder_Name] ' command.

After pointing to directory - type 'dir' which shows all the files present in folder, just to make sure everything at place.

Now type : 'copy *.txt [newfile_name].txt' and press enter.

Done!

All the text in individual files will be copied to [newfile_name].txt

How can I get the current time in C#?

DateTime.Now.ToString("HH:mm:ss tt");

this gives it to you as a string.

Add image to layout in ruby on rails

simple just use the img tag helper. Rails knows to look in the images folder in the asset pipeline, you can use it like this

<%= image_tag "image.jpg" %>

How to create strings containing double quotes in Excel formulas?

Have you tried escaping with a double-quote?

= "Maurice ""The Rocket"" Richard"

Calling one method from another within same class in Python

To accessing member functions or variables from one scope to another scope (In your case one method to another method we need to refer method or variable with class object. and you can do it by referring with self keyword which refer as class object.

class YourClass():

    def your_function(self, *args):

        self.callable_function(param) # if you need to pass any parameter

    def callable_function(self, *params): 
        print('Your param:', param)

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

You have in your module

import {Routes, RouterModule} from '@angular/router';

you have to export the module RouteModule

example:

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})

to be able to access the functionalities for all who import this module.

How to connect from windows command prompt to mysql command line

First jump to the mysql bin directory. You have two ways to connect

1) mysql -u root -p1234 (without space for password flag) 2) mysql -u root -p and enter the password when it is asking

newline in <td title="">

If you're looking to put line breaks into the tooltip that appears on mouseover, there's no reliable crossbrowser way to do that. You'd have to fall back to one of the many Javascript tooltip code samples

Update MongoDB field using value of another field

With MongoDB version 4.2+, updates are more flexible as it allows the use of aggregation pipeline in its update, updateOne and updateMany. You can now transform your documents using the aggregation operators then update without the need to explicity state the $set command (instead we use $replaceRoot: {newRoot: "$$ROOT"})

Here we use the aggregate query to extract the timestamp from MongoDB's ObjectID "_id" field and update the documents (I am not an expert in SQL but I think SQL does not provide any auto generated ObjectID that has timestamp to it, you would have to automatically create that date)

var collection = "person"

agg_query = [
    {
        "$addFields" : {
            "_last_updated" : {
                "$toDate" : "$_id"
            }
        }
    },
    {
        $replaceRoot: {
            newRoot: "$$ROOT"
        } 
    }
]

db.getCollection(collection).updateMany({}, agg_query, {upsert: true})

Convert string to date then format the date

    String start_dt = "2011-01-01"; // Input String

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // Existing Pattern
    Date getStartDt = formatter.parse(start_dt); //Returns Date Format according to existing pattern

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd-yyyy");// New Pattern
    String formattedDate = simpleDateFormat.format(getStartDt); // Format given String to new pattern

    System.out.println(formattedDate); //outputs: 01-01-2011

sed one-liner to convert all uppercase to lowercase?

If you have GNU extensions, you can use sed's \L (lower entire match, or until \L [lower] or \E [end - toggle casing off] is reached), like so:

sed 's/.*/\L&/' <input >output

Note: '&' means the full match pattern.

As a side note, GNU extensions include \U (upper), \u (upper next character of match), \l (lower next character of match). For example, if you wanted to camelcase a sentence:

$ sed -r 's/\w+/\u&/g' <<< "Now is the time for all good men..." # Camel Case
Now Is The Time For All Good Men...

Note: Since the assumption is we have GNU extensions, we can also use the dash-r (extended regular expressions) option, which allows \w (word character) and relieves you of having to escape the capturing parenthesis and one-or-more quantifier (+). (Aside: \W [non-word], \s [whitespace], \S [non-whitespace] are also supported with dash-r, but \d [digit] and \D [non-digit] are not.)

UIImage resize (Scale proportion)

I used this single line of code to create a new UIImage which is scaled. Set the scale and orientation params to achieve what you want. The first line of code just grabs the image.

    // grab the original image
    UIImage *originalImage = [UIImage imageNamed:@"myImage.png"];
    // scaling set to 2.0 makes the image 1/2 the size. 
    UIImage *scaledImage = 
                [UIImage imageWithCGImage:[originalImage CGImage] 
                              scale:(originalImage.scale * 2.0)
                                 orientation:(originalImage.imageOrientation)];

Python find min max and average of a list (array)

from __future__ import division

somelist =  [1,12,2,53,23,6,17] 
max_value = max(somelist)
min_value = min(somelist)
avg_value = 0 if len(somelist) == 0 else sum(somelist)/len(somelist)

If you want to manually find the minimum as a function:

somelist =  [1,12,2,53,23,6,17] 

def my_min_function(somelist):
    min_value = None
    for value in somelist:
        if not min_value:
            min_value = value
        elif value < min_value:
            min_value = value
    return min_value

Python 3.4 introduced the statistics package, which provides mean and additional stats:

from statistics import mean, median

somelist =  [1,12,2,53,23,6,17]
avg_value = mean(somelist)
median_value = median(somelist)

Print commit message of a given commit in git

This will give you a very compact list of all messages for any specified time.

git log --since=1/11/2011 --until=28/11/2011 --no-merges --format=%B > CHANGELOG.TXT

How to get the MD5 hash of a file in C++?

QFile file("bigimage.jpg");

if (file.open(QIODevice::ReadOnly))
{
    QByteArray fileData = file.readAll();

    QByteArray hashData = QCryptographicHash::hash(fileData,QCryptographicHash::Md5); // or QCryptographicHash::Sha1
    qDebug() << hashData.toHex();  // 0e0c2180dfd784dd84423b00af86e2fc

}

Deleting a pointer in C++

  1. You are trying to delete a variable allocated on the stack. You can not do this
  2. Deleting a pointer does not destruct a pointer actually, just the memory occupied is given back to the OS. You can access it untill the memory is used for another variable, or otherwise manipulated. So it is good practice to set a pointer to NULL (0) after deleting.
  3. Deleting a NULL pointer does not delete anything.

Shorthand if/else statement Javascript

Another way to write it shortly

bePlanVar = !!((bePlanVar == false));

// is equivalent to

bePlanVar = (bePlanVar == false) ? true : false;

// and 

if (bePlanVar == false) {
    bePlanVar = true;
} else {
    bePlanVar = false;
}

Get Element value with minidom with Python

you can use something like this.It worked out for me

doc = parse('C:\\eve.xml')
my_node_list = doc.getElementsByTagName("name")
my_n_node = my_node_list[0]
my_child = my_n_node.firstChild
my_text = my_child.data 
print my_text

Find value in an array

Thanks for replies.

I did like this:

puts 'find' if array.include?(value)

Programmatically add new column to DataGridView

Here's a sample method that adds two extra columns programmatically to the grid view:

    private void AddColumnsProgrammatically()
    {
        // I created these columns at function scope but if you want to access 
        // easily from other parts of your class, just move them to class scope.
        // E.g. Declare them outside of the function...
        var col3 = new DataGridViewTextBoxColumn();
        var col4 = new DataGridViewCheckBoxColumn();

        col3.HeaderText = "Column3";
        col3.Name = "Column3";

        col4.HeaderText = "Column4";
        col4.Name = "Column4";

        dataGridView1.Columns.AddRange(new DataGridViewColumn[] {col3,col4});
    }

A great way to figure out how to do this kind of process is to create a form, add a grid view control and add some columns. (This process will actually work for ANY kind of form control. All instantiation and initialization happens in the Designer.) Then examine the form's Designer.cs file to see how the construction takes place. (Visual Studio does everything programmatically but hides it in the Form Designer.)

For this example I created two columns for the view named Column1 and Column2 and then searched Form1.Designer.cs for Column1 to see everywhere it was referenced. The following information is what I gleaned and, copied and modified to create two more columns dynamically:

// Note that this info scattered throughout the designer but can easily collected.

        System.Windows.Forms.DataGridViewTextBoxColumn Column1;
        System.Windows.Forms.DataGridViewCheckBoxColumn Column2;

        this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
        this.Column2 = new System.Windows.Forms.DataGridViewCheckBoxColumn();

        this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
        this.Column1,
        this.Column2});

        this.Column1.HeaderText = "Column1";
        this.Column1.Name = "Column1";

        this.Column2.HeaderText = "Column2";
        this.Column2.Name = "Column2";

How to call controller from the button click in asp.net MVC 4

You are mixing razor and aspx syntax,if your view engine is razor just do this:

<button class="btn btn-info" type="button" id="addressSearch"   
          onclick="location.href='@Url.Action("List", "Search")'">

How to display an image stored as byte array in HTML/JavaScript?

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions:

How to make cross domain request

You can make cross domain requests using the XMLHttpRequest object. This is done using something called "Cross Origin Resource Sharing". See: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Very simply put, when the request is made to the server the server can respond with a Access-Control-Allow-Origin header which will either allow or deny the request. The browser needs to check this header and if it is allowed then it will continue with the request process. If not the browser will cancel the request.

You can find some more information and a working example here: http://www.leggetter.co.uk/2010/03/12/making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html

JSONP is an alternative solution, but you could argue it's a bit of a hack.

Changing precision of numeric column in Oracle

Assuming that you didn't set a precision initially, it's assumed to be the maximum (38). You're reducing the precision because you're changing it from 38 to 14.

The easiest way to handle this is to rename the column, copy the data over, then drop the original column:

alter table EVAPP_FEES rename column AMOUNT to AMOUNT_OLD;

alter table EVAPP_FEES add AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_OLD;

alter table EVAPP_FEES drop column AMOUNT_OLD;

If you really want to retain the column ordering, you can move the data twice instead:

alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);

update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;

update EVAPP_FEES set AMOUNT = null;

alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;

alter table EVAPP_FEES drop column AMOUNT_TEMP;

How can I delete a query string parameter in JavaScript?

You can change the URL with:

window.history.pushState({}, document.title, window.location.pathname);

this way, you can overwrite the URL without the search parameter, I use it to clean the URL after take the GET parameters.

How to debug in Django, the good way?

I use PyCharm (same pydev engine as eclipse). Really helps me to visually be able to step through my code and see what is happening.

View's SELECT contains a subquery in the FROM clause

Looks to me as MySQL 3.6 gives the following error while MySQL 3.7 no longer errors out. I am yet to find anything in the documentation regarding this fix.

I get a "An attempt was made to load a program with an incorrect format" error on a SQL Server replication project

in windows form application I do this, Right-click on Project->Properties->Build->Check Prefer 32-bit checkbox. Thanks all

How to find list of possible words from a letter matrix [Boggle Solver]

So I wanted to add another PHP way of solving this, since everyone loves PHP. There's a little bit of refactoring I would like to do, like using a regexpression match against the dictionary file, but right now I'm just loading the entire dictionary file into a wordList.

I did this using a linked list idea. Each Node has a character value, a location value, and a next pointer.

The location value is how I found out if two nodes are connected.

1     2     3     4
11    12    13    14
21    22    23    24
31    32    33    34

So using that grid, I know two nodes are connected if the first node's location equals the second nodes location +/- 1 for the same row, +/- 9, 10, 11 for the row above and below.

I use recursion for the main search. It takes a word off the wordList, finds all the possible starting points, and then recursively finds the next possible connection, keeping in mind that it can't go to a location it's already using (which is why I add $notInLoc).

Anyway, I know it needs some refactoring, and would love to hear thoughts on how to make it cleaner, but it produces the correct results based on the dictionary file I'm using. Depending on the number of vowels and combinations on the board, it takes about 3 to 6 seconds. I know that once I preg_match the dictionary results, that will reduce significantly.

<?php
    ini_set('xdebug.var_display_max_depth', 20);
    ini_set('xdebug.var_display_max_children', 1024);
    ini_set('xdebug.var_display_max_data', 1024);

    class Node {
        var $loc;

        function __construct($value) {
            $this->value = $value;
            $next = null;
        }
    }

    class Boggle {
        var $root;
        var $locList = array (1, 2, 3, 4, 11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34);
        var $wordList = [];
        var $foundWords = [];

        function __construct($board) {
            // Takes in a board string and creates all the nodes
            $node = new Node($board[0]);
            $node->loc = $this->locList[0];
            $this->root = $node;
            for ($i = 1; $i < strlen($board); $i++) {
                    $node->next = new Node($board[$i]);
                    $node->next->loc = $this->locList[$i];
                    $node = $node->next;
            }
            // Load in a dictionary file
            // Use regexp to elimate all the words that could never appear and load the 
            // rest of the words into wordList
            $handle = fopen("dict.txt", "r");
            if ($handle) {
                while (($line = fgets($handle)) !== false) {
                    // process the line read.
                    $line = trim($line);
                    if (strlen($line) > 2) {
                        $this->wordList[] = trim($line);
                    }
                }
                fclose($handle);
            } else {
                // error opening the file.
                echo "Problem with the file.";
            } 
        }

        function isConnected($node1, $node2) {
        // Determines if 2 nodes are connected on the boggle board

            return (($node1->loc == $node2->loc + 1) || ($node1->loc == $node2->loc - 1) ||
               ($node1->loc == $node2->loc - 9) || ($node1->loc == $node2->loc - 10) || ($node1->loc == $node2->loc - 11) ||
               ($node1->loc == $node2->loc + 9) || ($node1->loc == $node2->loc + 10) || ($node1->loc == $node2->loc + 11)) ? true : false;

        }

        function find($value, $notInLoc = []) {
            // Returns a node with the value that isn't in a location
            $current = $this->root;
            while($current) {
                if ($current->value == $value && !in_array($current->loc, $notInLoc)) {
                    return $current;
                }
                if (isset($current->next)) {
                    $current = $current->next;
                } else {
                    break;
                }
            }
            return false;
        }

        function findAll($value) {
            // Returns an array of nodes with a specific value
            $current = $this->root;
            $foundNodes = [];
            while ($current) {
                if ($current->value == $value) {
                    $foundNodes[] = $current;
                }
                if (isset($current->next)) {
                    $current = $current->next;
                } else {
                    break;
                }
            }
            return (empty($foundNodes)) ? false : $foundNodes;
        }

        function findAllConnectedTo($node, $value, $notInLoc = []) {
            // Returns an array of nodes that are connected to a specific node and 
            // contain a specific value and are not in a certain location
            $nodeList = $this->findAll($value);
            $newList = [];
            if ($nodeList) {
                foreach ($nodeList as $node2) {
                    if (!in_array($node2->loc, $notInLoc) && $this->isConnected($node, $node2)) {
                        $newList[] = $node2;
                    }
                }
            }
            return (empty($newList)) ? false : $newList;
        }



        function inner($word, $list, $i = 0, $notInLoc = []) {
            $i++;
            foreach($list as $node) {
                $notInLoc[] = $node->loc;
                if ($list2 = $this->findAllConnectedTo($node, $word[$i], $notInLoc)) {
                    if ($i == (strlen($word) - 1)) {
                        return true;
                    } else {
                        return $this->inner($word, $list2, $i, $notInLoc);
                    }
                }
            }
            return false;
        }

        function findWord($word) {
            if ($list = $this->findAll($word[0])) {
                return $this->inner($word, $list);
            }
            return false;
        }

        function findAllWords() {
            foreach($this->wordList as $word) {
                if ($this->findWord($word)) {
                    $this->foundWords[] = $word;
                }
            }
        }

        function displayBoard() {
            $current = $this->root;
            for ($i=0; $i < 4; $i++) {
                echo $current->value . " " . $current->next->value . " " . $current->next->next->value . " " . $current->next->next->next->value . "<br />";
                if ($i < 3) {
                    $current = $current->next->next->next->next;
                }
            }
        }

    }

    function randomBoardString() {
        return substr(str_shuffle(str_repeat("abcdefghijklmnopqrstuvwxyz", 16)), 0, 16);
    }

    $myBoggle = new Boggle(randomBoardString());
    $myBoggle->displayBoard();
    $x = microtime(true);
    $myBoggle->findAllWords();
    $y = microtime(true);
    echo ($y-$x);
    var_dump($myBoggle->foundWords);

    ?>

Simple way to convert datarow array to datatable

DataTable dataTable = new DataTable();
dataTable = OldDataTable.Tables[0].Clone();
foreach(DataRow dr in RowData.Tables[0].Rows)
{
 DataRow AddNewRow = dataTable.AddNewRow();
 AddNewRow.ItemArray = dr.ItemArray;
 dataTable.Rows.Add(AddNewRow);
}

Replacing Numpy elements if condition is met

>>> import numpy as np
>>> a = np.random.randint(0, 5, size=(5, 4))
>>> a
array([[4, 2, 1, 1],
       [3, 0, 1, 2],
       [2, 0, 1, 1],
       [4, 0, 2, 3],
       [0, 0, 0, 2]])
>>> b = a < 3
>>> b
array([[False,  True,  True,  True],
       [False,  True,  True,  True],
       [ True,  True,  True,  True],
       [False,  True,  True, False],
       [ True,  True,  True,  True]], dtype=bool)
>>> 
>>> c = b.astype(int)
>>> c
array([[0, 1, 1, 1],
       [0, 1, 1, 1],
       [1, 1, 1, 1],
       [0, 1, 1, 0],
       [1, 1, 1, 1]])

You can shorten this with:

>>> c = (a < 3).astype(int)

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

Cleanest version specially good if you just want to get the .value from the element.

document.getElementById('elementsid') ? function_if_exists(); function_if_doesnt_exists();

Python open() gives FileNotFoundError/IOError: Errno 2 No such file or directory

The file may be existing but may have a different path. Try writing the absolute path for the file.

Try os.listdir() function to check that atleast python sees the file.

Try it like this:

file1 = open(r'Drive:\Dir\recentlyUpdated.yaml')

Android Studio - Auto complete and other features not working

Most of the times i have seen that the problem is that Power Save Mode is enabled, to disable go to Current inspection profile (lower right corner in Android Studio).

enter image description here

Base64 Encoding Image

My synopsis of rfc2397 is:

Once you've got your base64 encoded image data put it inside the <Image></Image> tags prefixed with "data:{mimetype};base64," this is similar to the prefixing done in the parenthesis of url() definition in CSS or in the quoted value of the src attribute of the img tag in [X]HTML. You can test the data url in firefox by putting the data:image/... line into the URL field and pressing enter, it should show your image.

For actually encoding I think we need to go over all your options, not just PHP, because there's so many ways to base64 encode something.

  1. Use the base64 command line tool. It's part of the GNU coreutils (v6+) and pretty much default in any Cygwin, Linux, GnuWin32 install, but not the BSDs I tried. Issue: $ base64 imagefile.ico > imagefile.base64.txt
  2. Use a tool that features the option to convert to base64, like Notepad++ which has the feature under plugins->MIME tools->base64 Encode
  3. Email yourself the file and view the raw email contents, copy and paste.
  4. Use a web form.

A note on mime-types: I would prefer you use one of image/png image/jpeg or image/gif as I can't find the popular image/x-icon. Should that be image/vnd.microsoft.icon? Also the other formats are much shorter.

compare 265 bytes vs 1150 bytes:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAVFBMVEWcZjTcViTMuqT8/vzcYjTkhhTkljT87tz03sRkZmS8mnT03tT89vTsvoTk1sz86uTkekzkjmzkwpT01rTsmnzsplTUwqz89uy0jmzsrmTknkT0zqT3X4fRAAAAbklEQVR4XnXOVw6FIBBAUafQsZfX9r/PB8JoTPT+QE4o01AtMoS8HkALcH8BGmGIAvaXLw0wCqxKz0Q9w1LBfFSiJBzljVerlbYhlBO4dZHM/F3llybncbIC6N+70Q7OlUm7DdO+gKs9gyRwdgd/LOcGXHzLN5gAAAAASUVORK5CYII=

data:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAD/////ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv///////////2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb///////////9mZmb/ZmZm//////////////////////////////////////////////////////9mZmb/ZmZm////////////ZmZm/2ZmZv//////ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv//////ZmZm/2ZmZv///////////2ZmZv9mZmb//////2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb//////2ZmZv9mZmb///////////9mZmb/ZmZm////////////////////////////8fX4/8nW5P+twtb/oLjP//////9mZmb/ZmZm////////////////////////////oLjP/3eZu/9pj7T/M2aZ/zNmmf8zZpn/M2aZ/zNmmf///////////////////////////////////////////zNmmf8zZpn/M2aZ/zNmmf8zZpn/d5m7/6C4z/+WwuH/wN/3//////////////////////////////////////+guM//rcLW/8nW5P/x9fj//////9/v+/+w1/X/QZ7m/1Cm6P//////////////////////////////////////////////////////7/f9/4C+7v8xluT/EYbg/zGW5P/A3/f/0933/9Pd9//////////////////////////////////f7/v/YK7q/xGG4P8RhuD/MZbk/7DX9f//////4uj6/zJh2/8yYdv/8PT8////////////////////////////UKbo/xGG4P8xluT/sNf1////////////4uj6/zJh2/8jVtj/e5ro/////////////////////////////////8Df9/+gz/P/////////////////8PT8/0944P8jVtj/bI7l/////////////////////////////////////////////////////////////////2yO5f8jVtj/T3jg//D0/P///////////////////////////////////////////////////////////3ua6P8jVtj/MmHb/+Lo+v////////////////////////////////////////////////////////////D0/P8yYdv/I1bY/9Pd9///////////////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==

placeholder for select tag

Try this

HTML

<select class="form-control"name="country">
<option class="servce_pro_disabled">Select Country</option>
<option class="servce_pro_disabled" value="Aruba" id="cl_country_option">Aruba</option>
</select>

CSS

.form-control option:first-child {
    display: none;
}

You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application

You must setup postgresql-server-dev-X.Y, where X.Y. your's servers version, and it will install libpq-dev and other servers variables at modules for server side developing. In my case it was

apt-get install postgresql-server-dev-9.5

Reading package lists... Done Building dependency tree Reading state information... Done The following packages were automatically installed and are no longer required: libmysqlclient18 mysql-common Use 'apt-get autoremove' to remove them. The following extra packages will be installed:
libpq-dev Suggested packages: postgresql-doc-10 The following NEW packages will be installed: libpq-dev postgresql-server-dev-9.5

In your's case

sudo apt-get install postgresql-server-dev-X.Y
sudo apt-get install python-psycopg2

Get local IP address

Keep in mind, in the general case you could have multiple NAT translations going on, and multiple dns servers, each operating on different NAT translation levels.

What if you have carrier grade NAT, and want to communicate with other customers of the same carrier? In the general case you never know for sure because you might appear with different host names at every NAT translation.

IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7

I have same problem but with different situation. I can compile without any issue with maven in command line (mvn clean install), but in Intellij I always got "java: diamond operator is not supported in -source 1.5" compile error despite I have set the maven-compiler-plugin with java 1.8 in the pom.xml.

It turned out I have remote repository setting in my maven's settings.xml which the project depends on, but Intellij uses his own maven which doesn't have same setting with my local maven.

So my solution was changing the Intellij's maven setting (Settings -> Build, execution, Deployment -> Maven -> Maven home directory) to use the local maven.

How to improve a case statement that uses two columns

Just change your syntax ever so slightly:

CASE WHEN STATE = 2 AND RetailerProcessType = 1 THEN '"AUTHORISED"'
     WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
     WHEN STATE = 2 AND RetailerProcessType = 2 THEN '"AUTHORISED"'
     ELSE '"DECLINED"'
END

If you don't put the field expression before the CASE statement, you can put pretty much any fields and comparisons in there that you want. It's a more flexible method but has slightly more verbose syntax.

Which MIME type to use for a binary file that's specific to my program?

I'd recommend application/octet-stream as RFC2046 says "The "octet-stream" subtype is used to indicate that a body contains arbitrary binary data" and "The recommended action for an implementation that receives an "application/octet-stream" entity is to simply offer to put the data in a file[...]".

I think that way you will get better handling from arbitrary programs, that might barf when encountering your unknown mime type.

pinpointing "conditional jump or move depends on uninitialized value(s)" valgrind message

What this means is that you are trying to print out/output a value which is at least partially uninitialized. Can you narrow it down so that you know exactly what value that is? After that, trace through your code to see where it is being initialized. Chances are, you will see that it is not being fully initialized.

If you need more help, posting the relevant sections of source code might allow someone to offer more guidance.

EDIT

I see you've found the problem. Note that valgrind watches for Conditional jump or move based on unitialized variables. What that means is that it will only give out a warning if the execution of the program is altered due to the uninitialized value (ie. the program takes a different branch in an if statement, for example). Since the actual arithmetic did not involve a conditional jump or move, valgrind did not warn you of that. Instead, it propagated the "uninitialized" status to the result of the statement that used it.

It may seem counterintuitive that it does not warn you immediately, but as mark4o pointed out, it does this because uninitialized values get used in C all the time (examples: padding in structures, the realloc() call, etc.) so those warnings would not be very useful due to the false positive frequency.

How to generate List<String> from SQL query?

I think this is what you're looking for.

List<String> columnData = new List<String>();

using(SqlConnection connection = new SqlConnection("conn_string"))
{
    connection.Open();
    string query = "SELECT Column1 FROM Table1";
    using(SqlCommand command = new SqlCommand(query, connection))
    {
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                columnData.Add(reader.GetString(0));
            }         
        }
    }
}

Not tested, but this should work fine.

What is the difference between a Docker image and a container?

I couldn't understand the concept of image and layer in spite of reading all the questions here and then eventually stumbled upon this excellent documentation from Docker (duh!).

The example there is really the key to understand the whole concept. It is a lengthy post, so I am summarising the key points that need to be really grasped to get clarity.

  • Image: A Docker image is built up from a series of read-only layers

  • Layer: Each layer represents an instruction in the image’s Dockerfile.

Example: The below Dockerfile contains four commands, each of which creates a layer.

FROM ubuntu:15.04

COPY . /app

RUN make /app

CMD python /app/app.py

Importantly, each layer is only a set of differences from the layer before it.

  • Container. When you create a new container, you add a new writable layer on top of the underlying layers. This layer is often called the “container layer”. All changes made to the running container, such as writing new files, modifying existing files, and deleting files, are written to this thin writable container layer.

Hence, the major difference between a container and an image is the top writable layer. All writes to the container that add new or modify existing data are stored in this writable layer. When the container is deleted, the writable layer is also deleted. The underlying image remains unchanged.

Understanding images cnd Containers from a size-on-disk perspective

To view the approximate size of a running container, you can use the docker ps -s command. You get size and virtual size as two of the outputs:

  • Size: the amount of data (on disk) that is used for the writable layer of each container

  • Virtual Size: the amount of data used for the read-only image data used by the container. Multiple containers may share some or all read-only image data. Hence these are not additive. I.e. you can't add all the virtual sizes to calculate how much size on disk is used by the image

Another important concept is the copy-on-write strategy

If a file or directory exists in a lower layer within the image, and another layer (including the writable layer) needs read access to it, it just uses the existing file. The first time another layer needs to modify the file (when building the image or running the container), the file is copied into that layer and modified.

I hope that helps someone else like me.

How do I download a file using VBA (without Internet Explorer)

I was struggling for hours on this until I figured out it can be done in one line of powershell:

invoke-webrequest -Uri "http://myserver/Reports/Pages/ReportViewer.aspx?%2fClients%2ftest&rs:Format=PDF&rs:ClearSession=true&CaseCode=12345678" -OutFile "C:\Temp\test.pdf" -UseDefaultCredentials

I looked into doing it purely in VBA but it runs to several pages, so I just call my powershell script from VBA every time I want to download a file.

Simple.

How to declare a vector of zeros in R

replicate is another option:

replicate(10, 0)
# [1] 0 0 0 0 0 0 0 0 0 0

replicate(5, 1)
# [1] 1 1 1 1 1

To create a matrix:

replicate( 5, numeric(3) )

#     [,1] [,2] [,3] [,4] [,5]
#[1,]    0    0    0    0    0
#[2,]    0    0    0    0    0
#[3,]    0    0    0    0    0

What is the time complexity of indexing, inserting and removing from common data structures?

Red-Black trees:

  • Insert - O(log n)
  • Retrieve - O(log n)
  • Delete - O(log n)

Remove Top Line of Text File with PowerShell

For smaller files you could use this:

& C:\windows\system32\more +1 oldfile.csv > newfile.csv | out-null

... but it's not very effective at processing my example file of 16MB. It doesn't seem to terminate and release the lock on newfile.csv.

How to get everything after a certain character?

I use strrchr(). For instance to find the extension of a file I use this function:

$string = 'filename.jpg';
$extension = strrchr( $string, '.'); //returns ".jpg"

Count the number of times a string appears within a string

Probably not the most efficient, but think it's a neat way to do it.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(CountAllTheTimesThisStringAppearsInThatString("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "true"));
        Console.WriteLine(CountAllTheTimesThisStringAppearsInThatString("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "false"));

    }

    static Int32 CountAllTheTimesThisStringAppearsInThatString(string orig, string find)
    {
        var s2 = orig.Replace(find,"");
        return (orig.Length - s2.Length) / find.Length;
    }
}

Subprocess check_output returned non-zero exit status 1

The command yum that you launch was executed properly. It returns a non zero status which means that an error occured during the processing of the command. You probably want to add some argument to your yum command to fix that.

Your code could show this error this way:

import subprocess
try:
    subprocess.check_output("dir /f",shell=True,stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
    raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))

In Python, when to use a Dictionary, List or Set?

Although this doesn't cover sets, it is a good explanation of dicts and lists:

Lists are what they seem - a list of values. Each one of them is numbered, starting from zero - the first one is numbered zero, the second 1, the third 2, etc. You can remove values from the list, and add new values to the end. Example: Your many cats' names.

Dictionaries are similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. In python, the word is called a 'key', and the definition a 'value'. The values in a dictionary aren't numbered - tare similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. The values in a dictionary aren't numbered - they aren't in any specific order, either - the key does the same thing. You can add, remove, and modify the values in dictionaries. Example: telephone book.

http://www.sthurlow.com/python/lesson06/

Select row on click react-table

There is a HOC included for React-Table that allows for selection, even when filtering and paginating the table, the setup is slightly more advanced than the basic table so read through the info in the link below first.


enter image description here



After importing the HOC you can then use it like this with the necessary methods:

/**
* Toggle a single checkbox for select table
*/
toggleSelection(key: number, shift: string, row: string) {
    // start off with the existing state
    let selection = [...this.state.selection];
    const keyIndex = selection.indexOf(key);

    // check to see if the key exists
    if (keyIndex >= 0) {
        // it does exist so we will remove it using destructing
        selection = [
            ...selection.slice(0, keyIndex),
            ...selection.slice(keyIndex + 1)
        ];
    } else {
        // it does not exist so add it
        selection.push(key);
    }
    // update the state
    this.setState({ selection });
}

/**
* Toggle all checkboxes for select table
*/
toggleAll() {
    const selectAll = !this.state.selectAll;
    const selection = [];

    if (selectAll) {
        // we need to get at the internals of ReactTable
        const wrappedInstance = this.checkboxTable.getWrappedInstance();
        // the 'sortedData' property contains the currently accessible records based on the filter and sort
        const currentRecords = wrappedInstance.getResolvedState().sortedData;
        // we just push all the IDs onto the selection array
        currentRecords.forEach(item => {
            selection.push(item._original._id);
        });
    }
    this.setState({ selectAll, selection });
}

/**
* Whether or not a row is selected for select table
*/
isSelected(key: number) {
    return this.state.selection.includes(key);
}

<CheckboxTable
    ref={r => (this.checkboxTable = r)}
    toggleSelection={this.toggleSelection}
    selectAll={this.state.selectAll}
    toggleAll={this.toggleAll}
    selectType="checkbox"
    isSelected={this.isSelected}
    data={data}
    columns={columns}
/>

See here for more information:
https://github.com/tannerlinsley/react-table/tree/v6#selecttable

Here is a working example:
https://codesandbox.io/s/react-table-select-j9jvw

How do I remove a key from a JavaScript object?

If you are using Underscore.js or Lodash, there is a function 'omit' that will do it.
http://underscorejs.org/#omit

var thisIsObject= {
    'Cow' : 'Moo',
    'Cat' : 'Meow',
    'Dog' : 'Bark'
};
_.omit(thisIsObject,'Cow'); //It will return a new object

=> {'Cat' : 'Meow', 'Dog' : 'Bark'}  //result

If you want to modify the current object, assign the returning object to the current object.

thisIsObject = _.omit(thisIsObject,'Cow');

With pure JavaScript, use:

delete thisIsObject['Cow'];

Another option with pure JavaScript.

thisIsObject.cow = undefined;

thisIsObject = JSON.parse(JSON.stringify(thisIsObject ));

Case statement in MySQL

Try to use IF(condition, value1, value2)

SELECT ID, HEADING, 
IF(action_type='Income',action_amount,0) as Income,
IF(action_type='Expense',action_amount,0) as Expense

How do I install SciPy on 64 bit Windows?

WinPython is an open-source distribution that has 64-bit NumPy and SciPy.

Sort a List of Object in VB.NET

To sort by a property in the object, you have to specify a comparer or a method to get that property.

Using the List.Sort method:

theList.Sort(Function(x, y) x.age.CompareTo(y.age))

Using the OrderBy extension method:

theList = theList.OrderBy(Function(x) x.age).ToList()

Mockito How to mock only the call of a method of the superclass

create a package protected (assumes test class in same package) method in the sub class that calls the super class method and then call that method in your overridden sub class method. you can then set expectations on this method in your test through the use of the spy pattern. not pretty but certainly better than having to deal with all the expectation setting for the super method in your test

Is there a typical state machine implementation pattern?

You might want to look into the libero FSM generator software. From a state description language and/or a (windows) state diagram editor you may generate code for C, C++, java and many others ... plus nice documentation and diagrams. Source and binaries from iMatix

How to generate a range of numbers between two numbers?

-- Generate Numeric Range
-- Source: http://www.sqlservercentral.com/scripts/Miscellaneous/30397/

CREATE TABLE #NumRange(
    n int
)

DECLARE @MinNum int
DECLARE @MaxNum int
DECLARE @I int

SET NOCOUNT ON

SET @I = 0
WHILE @I <= 9 BEGIN
    INSERT INTO #NumRange VALUES(@I)
    SET @I = @I + 1
END


SET @MinNum = 1
SET @MaxNum = 1000000

SELECT  num = a.n +
    (b.n * 10) +
    (c.n * 100) +
    (d.n * 1000) +
    (e.n * 10000)
FROM    #NumRange a
CROSS JOIN #NumRange b
CROSS JOIN #NumRange c
CROSS JOIN #NumRange d
CROSS JOIN #NumRange e
WHERE   a.n +
    (b.n * 10) +
    (c.n * 100) +
    (d.n * 1000) +
    (e.n * 10000) BETWEEN @MinNum AND @MaxNum
ORDER BY a.n +
    (b.n * 10) +
    (c.n * 100) +
    (d.n * 1000) +
    (e.n * 10000) 

DROP TABLE #NumRange

RegEx: How can I match all numbers greater than 49?

Try a conditional group matching 50-99 or any string of three or more digits:

var r = /^(?:[5-9]\d|\d{3,})$/

how to install gcc on windows 7 machine?

EDIT Since not so recently by now, MinGW-w64 has "absorbed" one of the toolchain building projects. The downloads can be found here. The installer should work, and allow you to pick a version that you need.

Note the Qt SDK comes with the same toolchain. So if you are developing in Qt and using the SDK, just use the toolchain it comes with.

Another alternative that has up to date toolchains comes from... harhar... a Microsoft developer, none other than STL (Stephan T. Lavavej, isn't that a spot-on name for the maintainer of MSVC++ Standard Library!). You can find it here. It includes Boost.

Another option which is highly useful if you care for prebuilt dependencies is MSYS2, which provides a Unix shell (a Cygwin fork modified to work better with Windows pathnames and such), also provides a GCC. It usually lags a bit behind, but that is compensated for by its good package management system and stability. They also provide a functional Clang with libc++ if you care for such thing.

I leave the below for reference, but I strongly suggest against using MinGW.org, due to limitations detailed below. TDM-GCC (the MinGW-w64 version) provides some hacks that you may find useful in your specific situation, although I recommend using vanilla GCC at all times for maximum compatibility.


GCC for Windows is provided by two projects currently. They both provide a very own implementation of the Windows SDK (headers and libraries) which is necessary because GCC does not work with Visual Studio files.

  1. The older mingw.org, which @Mat already pointed you to. They provide only a 32-bit compiler. See here for the downloads you need:

    • Binutils is the linker and resource compiler etc.
    • GCC is the compiler, and is split in core and language packages
    • GDB is the debugger.
    • runtime library is required only for mingw.org
    • You might need to download mingw32-make seperately.
    • For support, you can try (don't expect friendly replies) [email protected]

    Alternatively, download mingw-get and use that.

  2. The newer mingw-w64, which as the name predicts, also provides a 64-bit variant, and in the future hopefully some ARM support. I use it and built toolchains with their CRT. Personal and auto builds are found under "Toolchains targetting Win32/64" here. They also provide Linux to Windows cross-compilers. I suggest you try a personal build first, they are more complete. Try mine (rubenvb) for GCC 4.6 to 4.8, or use sezero's for GCC 4.4 and 4.5. Both of us provide 32-bit and 64-bit native toolchains. These packages include everything listed above. I currently recommend the "MinGW-Builds" builds, as these are currently sanctioned as "official builds", and come with an installer (see above).

    For support, send an email to [email protected] or post on the forum via sourceforge.net.

Both projects have their files listed on sourceforge, and all you have to do is either run the installer (in case of mingw.org) or download a suitable zipped package and extract it (in the case of mingw-w64).

There are a lot of "non-official" toolchain builders, one of the most popular is TDM-GCC. They may use patches that break binary compatibility with official/unpatched toolchains, so be careful using them. It's best to use the official releases.

Using an attribute of the current class instance as a default value for method's parameter

There is much more to it than you think. Consider the defaults to be static (=constant reference pointing to one object) and stored somewhere in the definition; evaluated at method definition time; as part of the class, not the instance. As they are constant, they cannot depend on self.

Here is an example. It is counterintuitive, but actually makes perfect sense:

def add(item, s=[]):
    s.append(item)
    print len(s)

add(1)     # 1
add(1)     # 2
add(1, []) # 1
add(1, []) # 1
add(1)     # 3

This will print 1 2 1 1 3.

Because it works the same way as

default_s=[]
def add(item, s=default_s):
    s.append(item)

Obviously, if you modify default_s, it retains these modifications.

There are various workarounds, including

def add(item, s=None):
    if not s: s = []
    s.append(item)

or you could do this:

def add(self, item, s=None):
    if not s: s = self.makeDefaultS()
    s.append(item)

Then the method makeDefaultS will have access to self.

Another variation:

import types
def add(item, s=lambda self:[]):
    if isinstance(s, types.FunctionType): s = s("example")
    s.append(item)

here the default value of s is a factory function.

You can combine all these techniques:

class Foo:
    import types
    def add(self, item, s=Foo.defaultFactory):
        if isinstance(s, types.FunctionType): s = s(self)
        s.append(item)

    def defaultFactory(self):
        """ Can be overridden in a subclass, too!"""
        return []

Angular 2 Scroll to top on Route Change

The best answer resides in the Angular GitHub discussion (Changing route doesn't scroll to top in the new page).

Maybe you want go to top only in root router changes (not in children, because you can load routes with lazy load in f.e. a tabset)

app.component.html

<router-outlet (deactivate)="onDeactivate()"></router-outlet>

app.component.ts

onDeactivate() {
  document.body.scrollTop = 0;
  // Alternatively, you can scroll to top by using this other call:
  // window.scrollTo(0, 0)
}

Full credits to JoniJnm (original post)

Get Path from another app (WhatsApp)

You can also convert the URI to file and then to bytes if you want to upload the photo to your server.

Check out : https://www.stackoverflow.com/a/49575321

np.mean() vs np.average() in Python NumPy?

In some version of numpy there is another imporant difference that you must be aware:

average do not take in account masks, so compute the average over the whole set of data.

mean takes in account masks, so compute the mean only over unmasked values.

g = [1,2,3,55,66,77]
f = np.ma.masked_greater(g,5)

np.average(f)
Out: 34.0

np.mean(f)
Out: 2.0

What is an ORM, how does it work, and how should I use one?

Like all acronyms it's ambiguous, but I assume they mean object-relational mapper -- a way to cover your eyes and make believe there's no SQL underneath, but rather it's all objects;-). Not really true, of course, and not without problems -- the always colorful Jeff Atwood has described ORM as the Vietnam of CS;-). But, if you know little or no SQL, and have a pretty simple / small-scale problem, they can save you time!-)

json: cannot unmarshal object into Go value of type

You JSON doesn't match your struct fields: E.g. "district" in JSON and "District" as the field.

Also: Your Item is a slice type but your JSON is a dict value. Do not mix this up. Slices decode from arrays.

bash script use cut command at variable and store result at another variable

The awk solution is what I would use, but if you want to understand your problems with bash, here is a revised version of your script.

#!/bin/bash -vx

##config file with ip addresses like 10.10.10.1:80
file=config.txt

while read line ; do
  ##this line is not correct, should strip :port and store to ip var
  ip=$( echo "$line" |cut -d\: -f1 )
  ping $ip
done < ${file}

You could write your top line as

for line in $(cat $file) ; do ...

(but not recommended).

You needed command substitution $( ... ) to get the value assigned to $ip

reading lines from a file is usually considered more efficient with the while read line ... done < ${file} pattern.

I hope this helps.

How to create a new schema/new user in Oracle Database 11g?

SQL> select Username from dba_users
  2  ;

USERNAME
------------------------------
SYS
SYSTEM
ANONYMOUS
APEX_PUBLIC_USER
FLOWS_FILES
APEX_040000
OUTLN
DIP
ORACLE_OCM
XS$NULL
MDSYS

USERNAME
------------------------------
CTXSYS
DBSNMP
XDB
APPQOSSYS
HR

16 rows selected.

SQL> create user testdb identified by password;

User created.

SQL> select username from dba_users;

USERNAME
------------------------------
TESTDB
SYS
SYSTEM
ANONYMOUS
APEX_PUBLIC_USER
FLOWS_FILES
APEX_040000
OUTLN
DIP
ORACLE_OCM
XS$NULL

USERNAME
------------------------------
MDSYS
CTXSYS
DBSNMP
XDB
APPQOSSYS
HR

17 rows selected.

SQL> grant create session to testdb;

Grant succeeded.

SQL> create tablespace testdb_tablespace
  2  datafile 'testdb_tabspace.dat'
  3  size 10M autoextend on;

Tablespace created.

SQL> create temporary tablespace testdb_tablespace_temp
  2  tempfile 'testdb_tabspace_temp.dat'
  3  size 5M autoextend on;

Tablespace created.

SQL> drop user testdb;

User dropped.

SQL> create user testdb
  2  identified by password
  3  default tablespace testdb_tablespace
  4  temporary tablespace testdb_tablespace_temp;

User created.

SQL> grant create session to testdb;

Grant succeeded.

SQL> grant create table to testdb;

Grant succeeded.

SQL> grant unlimited tablespace to testdb;

Grant succeeded.

SQL>

What Are The Best Width Ranges for Media Queries

best bet is targeting features not devices unless you have to, bootstrap do well and you can extend on their breakpoints, for instance targeting pixel density and larger screens above 1920

<div> cannot appear as a descendant of <p>

I got this from using a custom component inside a <Card.Text> section of a <Card> component in React. None of my components were in p tags

How can I avoid running ActiveRecord callbacks?

When I need full control over the callback, I create another attribute that is used as a switch. Simple and effective:

Model:

class MyModel < ActiveRecord::Base
  before_save :do_stuff, unless: :skip_do_stuff_callback
  attr_accessor :skip_do_stuff_callback

  def do_stuff
    puts 'do stuff callback'
  end
end

Test:

m = MyModel.new()

# Fire callbacks
m.save

# Without firing callbacks
m.skip_do_stuff_callback = true
m.save

# Fire callbacks again
m.skip_do_stuff_callback = false
m.save

Keystore type: which one to use?

There are a few more types than what's listed in the standard name list you've linked to. You can find more in the cryptographic providers documentation. The most common are certainly JKS (the default) and PKCS12 (for PKCS#12 files, often with extension .p12 or sometimes .pfx).

JKS is the most common if you stay within the Java world. PKCS#12 isn't Java-specific, it's particularly convenient to use certificates (with private keys) backed up from a browser or coming from OpenSSL-based tools (keytool wasn't able to convert a keystore and import its private keys before Java 6, so you had to use other tools).

If you already have a PKCS#12 file, it's often easier to use the PKCS12 type directly. It's possible to convert formats, but it's rarely necessary if you can choose the keystore type directly.

In Java 7, PKCS12 was mainly useful as a keystore but less for a truststore (see the difference between a keystore and a truststore), because you couldn't store certificate entries without a private key. In contrast, JKS doesn't require each entry to be a private key entry, so you can have entries that contain only certificates, which is useful for trust stores, where you store the list of certificates you trust (but you don't have the private key for them).

This has changed in Java 8, so you can now have certificate-only entries in PKCS12 stores too. (More details about these changes and further plans can be found in JEP 229: Create PKCS12 Keystores by Default.)

There are a few other keystore types, perhaps less frequently used (depending on the context), those include:

  • PKCS11, for PKCS#11 libraries, typically for accessing hardware cryptographic tokens, but the Sun provider implementation also supports NSS stores (from Mozilla) through this.
  • BKS, using the BouncyCastle provider (commonly used for Android).
  • Windows-MY/Windows-ROOT, if you want to access the Windows certificate store directly.
  • KeychainStore, if you want to use the OSX keychain directly.

What is the best (and safest) way to merge a Git branch into master?

I would use the rebase method. Mostly because it perfectly reflects your case semantically, ie. what you want to do is to refresh the state of your current branch and "pretend" as if it was based on the latest.

So, without even checking out master, I would:

git fetch origin
git rebase -i origin/master
# ...solve possible conflicts here

Of course, just fetching from origin does not refresh the local state of your master (as it does not perform a merge), but it is perfectly ok for our purpose - we want to avoid switching around, for the sake of saving time.

background-size in shorthand background property (CSS3)

You can do as

 body{
        background:url('equote.png'),url('equote.png');
        background-size:400px 100px,50px 50px;
    }

jQuery - Disable Form Fields

try this

$("#inp").focus(function(){$("#sel").attr('disabled','true');});

$("#inp").blur(function(){$("#sel").removeAttr('disabled');});

vice versa for the select also.

Storing Form Data as a Session Variable

That's perfectly fine and will work. But to use sessions you have to put session_start(); on the first line of the php code. So basically

<?php
session_start();

//rest of stuff

?>

release Selenium chromedriver.exe from memory

I have looked at all the responses and tested them all. I pretty much compiled them all into one as a 'Safety closure'. This in c#

NOTE you can change the param from IModule app to that of the actual driver.

 public class WebDriverCleaner
{

    public static void CloseWebDriver(IModule app)
    {
        try
        {
            if (app?.GetDriver() != null)
            {
                app.GetDriver().Close();
                Thread.Sleep(3000); // Gives time for everything to close before quiting
                app.GetDriver().Quit();
                app.GetDriver().Dispose();
                KillProcessAndChildren("chromedriver.exe"); // One more to make sure we get rid of them chromedrivers.
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }

    public static void KillProcessAndChildren(string p_name)
    {
        ManagementObjectSearcher searcher = new ManagementObjectSearcher
            ("Select * From Win32_Process Where Name = '" + p_name + "'");

        ManagementObjectCollection moc = searcher.Get();
        foreach (ManagementObject mo in moc)
        {
            try
            {
                KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
            }
            catch (ArgumentException)
            {
                break;
            }
        }

    }


    public static void KillProcessAndChildren(int pid)
    {
        ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid);
        ManagementObjectCollection moc = searcher.Get();

        foreach (ManagementObject mo in moc)
        {
            try
            {
                KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
            }
            catch
            {
                break;
            }
        }

        try
        {
            Process proc = Process.GetProcessById(pid);
            proc.Kill();
        }
        catch (ArgumentException)
        {
            // Process already exited.
        }
    }

}

What is the difference between HTML tags and elements?

<p>Here is a quote from WWF's website:</p>.

In this part <p> is a tag.

<blockquote cite="www.facebook.com">facebook is the world's largest socialsite..</blockquote>

in this part <blockquote> is an element.

Not Able To Debug App In Android Studio

For me, it happened when I used Proguard, so by trying all the solutions I cleaned my project and pressed the debug button on Android Studio and it started debugging

Sending data through POST request from a node.js server to a node.js server

You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.

Just do the following for executing a POST request:

var requestify = require('requestify');

requestify.post('http://example.com', {
    hello: 'world'
})
.then(function(response) {
    // Get the response body (JSON parsed or jQuery object for XMLs)
    response.getBody();
});

Finding the length of a Character Array in C

If you want the length of the character array use sizeof(array)/sizeof(array[0]), if you want the length of the string use strlen(array).

SSH Key - Still asking for password and passphrase

Add Identity without Keychain

There may be times in which you don't want the passphrase stored in the keychain, but don't want to have to enter the passphrase over and over again.

You can do that like this:

ssh-add ~/.ssh/id_rsa 

This will ask you for the passphrase, enter it and it will not ask again until you restart.

Add Identity Using Keychain

As @dennis points out in the comments, to persist the passphrase through restarts by storing it in your keychain, you can use the -K option (-k for Ubuntu) when adding the identity like this:

ssh-add -K ~/.ssh/id_rsa

Once again, this will ask you for the passphrase, enter it and this time it will never ask again for this identity.

Cannot declare instance members in a static class in C#

Have you tried using the 'static' storage class similar to?:

public static class employee
{
    static NameValueCollection appSetting = ConfigurationManager.AppSettings;    
}

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

For all the Python 2.7.* users. There is a Python wrapper around the Github API that is currently on Version 3, called GitPython. Simply install using easy_install PyGithub or pip install PyGithub.

from github import Github
g = Github(your-email-addr, your-passwd)
repo = g.get_user().user.create_repo("your-new-repos-name")

# Make use of Repository object (repo)

The Repository object docs are here.

How to show PIL images on the screen?

If you find that PIL has problems on some platforms, using a native image viewer may help.

img.save("tmp.png") #Save the image to a PNG file called tmp.png.

For MacOS:

import os
os.system("open tmp.png") #Will open in Preview.

For most GNU/Linux systems with X.Org and a desktop environment:

import os
os.system("xdg-open tmp.png")

For Windows:

import os
os.system("powershell -c tmp.png")

How to round up with excel VBA round()?

Used the function "RDown" and "RUp" from ShamBhagwat and created another function that will return the round part (without the need to give "digits" for input)

Function RoundDown(a As Double, digits As Integer) As Double
    RoundDown = Int((a + (1 / (10 ^ (digits + 1)))) * (10 ^ digits)) / (10 ^ digits)
End Function

Function RoundUp(a As Double, digits As Integer) As Double
    RoundUp = RoundDown(a + (5 / (10 ^ (digits + 1))), digits)
End Function

Function RDownAuto(a As Double) As Double
    Dim i As Integer
    For i = 0 To 17
        If Abs(a * 10) > WorksheetFunction.Power(10, -(i - 1)) Then
            If a > 0 Then
                RDownAuto = RoundDown(a, i)
            Else
                RDownAuto = RoundUp(a, i)
            End If
        Exit Function
        End If
    Next
End Function

the output will be:

RDownAuto(458.067)=458
RDownAuto(10.11)=10
RDownAuto(0.85)=0.8
RDownAuto(0.0052)=0.005
RDownAuto(-458.067)=-458
RDownAuto(-10.11)=-10
RDownAuto(-0.85)=-0.8
RDownAuto(-0.0052)=-0.005

Convert InputStream to byte array in Java

In-case someone is still looking for a solution without dependency and If you have a file.

DataInputStream

 byte[] data = new byte[(int) file.length()];
 DataInputStream dis = new DataInputStream(new FileInputStream(file));
 dis.readFully(data);
 dis.close();

ByteArrayOutputStream

 InputStream is = new FileInputStream(file);
 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
 int nRead;
 byte[] data = new byte[(int) file.length()];
 while ((nRead = is.read(data, 0, data.length)) != -1) {
     buffer.write(data, 0, nRead);
 }

RandomAccessFile

 RandomAccessFile raf = new RandomAccessFile(file, "r");
 byte[] data = new byte[(int) raf.length()];
 raf.readFully(data);

Unable to merge dex

android {
    defaultConfig {
        ...
        minSdkVersion 15 
        targetSdkVersion 26
        multiDexEnabled true
    }
    ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.1'
}

c# replace \" characters

Replace(@"\""", "")

You have to use double-doublequotes to escape double-quotes within a verbatim string.

Android open pdf file

The reason you don't have permissions to open file is because you didn't grant other apps to open or view the file on your intent. To grant other apps to open the downloaded file, include the flag(as shown below): FLAG_GRANT_READ_URI_PERMISSION

Intent browserIntent = new Intent(Intent.ACTION_VIEW);
browserIntent.setDataAndType(getUriFromFile(localFile), "application/pdf");
browserIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION|
Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(browserIntent);

And for function:

getUriFromFile(localFile)

private Uri getUriFromFile(File file){
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
        return Uri.fromFile(file);
    }else {
        return FileProvider.getUriForFile(itemView.getContext(), itemView.getContext().getApplicationContext().getPackageName() + ".provider", file);
    }
}

Where are Magento's log files located?

These code lines can help you quickly enable log setting in your magento site.

INSERT INTO `core_config_data` (`config_id`, `scope`, `scope_id`, `path`, `value`) VALUES
('', 'default', 0, 'dev/log/active', '1'),
('', 'default', 0, 'dev/log/file', 'system.log'),
('', 'default', 0, 'dev/log/exception_file', 'exception.log');

Then you can see them inside the folder: /var/log under root installation.

More detail in this blog

tsconfig.json: Build:No inputs were found in config file

I ran into this issue constantly while packing my projects into nugets via Visual Studio 2019. After looking for a solution for ages I seem to have solved this by following advice in this article

MSBuild & Typescript

especially part about <TypeScriptCompile /> where I included all my .ts resources with the Include operator and excluded others such as node_modules with the Remove operator. I then deleted the tsconfig.json file in each offending project and the nuget packages were generated and no more errors

How do you change the colour of each category within a highcharts column chart?

Also you can set option:

  {plotOptions: {column: {colorByPoint: true}}}

for more information read docs

best practice to generate random token for forgot password

This answers the 'best random' request:

Adi's answer1 from Security.StackExchange has a solution for this:

Make sure you have OpenSSL support, and you'll never go wrong with this one-liner

$token = bin2hex(openssl_random_pseudo_bytes(16));

1. Adi, Mon Nov 12 2018, Celeritas, "Generating an unguessable token for confirmation e-mails", Sep 20 '13 at 7:06, https://security.stackexchange.com/a/40314/

Android studio- "SDK tools directory is missing"

In my case it was installing into an already existing directory. When you choose a directory for the installation. The programm won't allow you to type in a non-existing directory. So choose the path, get back to the main window and type the new folder name where you want install the SDK, probably feature.

Correct way to initialize HashMap and can HashMap hold different value types?

In answer to your second question: Yes a HashMap can hold different types of objects. Whether that's a good idea or not depends on the problem you're trying to solve.

That said, your example won't work. The int value is not an Object. You have to use the Integer wrapper class to store an int value in a HashMap

Floating divs in Bootstrap layout

I understand that you want the Widget2 sharing the bottom border with the contents div. Try adding

style="position: relative; bottom: 0px"

to your Widget2 tag. Also try:

style="position: absolute; bottom: 0px"

if you want to snap your widget to the bottom of the screen.

I am a little rusty with CSS, perhaps the correct style is "margin-bottom: 0px" instead "bottom: 0px", give it a try. Also the pull-right class seems to add a "float=right" style to the element, and I am not sure how this behaves with "position: relative" and "position: absolute", I would remove it.

How do I check whether an array contains a string in TypeScript?

The same as in JavaScript, using Array.prototype.indexOf():

console.log(channelArray.indexOf('three') > -1);

Or using ECMAScript 2016 Array.prototype.includes():

console.log(channelArray.includes('three'));

Note that you could also use methods like showed by @Nitzan to find a string. However you wouldn't usually do that for a string array, but rather for an array of objects. There those methods were more sensible. For example

const arr = [{foo: 'bar'}, {foo: 'bar'}, {foo: 'baz'}];
console.log(arr.find(e => e.foo === 'bar')); // {foo: 'bar'} (first match)
console.log(arr.some(e => e.foo === 'bar')); // true
console.log(arr.filter(e => e.foo === 'bar')); // [{foo: 'bar'}, {foo: 'bar'}]

Reference

Array.find()

Array.some()

Array.filter()

Easiest way to convert a List to a Set in Java

If you use the Guava library:

Set<Foo> set = Sets.newHashSet(list);

or, better:

Set<Foo> set = ImmutableSet.copyOf(list);

Reset all changes after last commit in git

There are two commands which will work in this situation,

root>git reset --hard HEAD~1

root>git push -f

For more git commands refer this page

Is it possible to override / remove background: none!important with jQuery?

Yes it is possible depending on what css you have, you simply just declare the same thing with a different background like this

ul li {
    background: none !important;
}

ul li{
    background: blue !important;
}

But you have to make sure the declaration comes after the first one seeing as it is cascading.

Demo

You can also create a style tag in jQuery like this

$('head').append('<style> #an-element li { background: inherit !important;} </style>');

Demo

You cannot see any changes because it's not inheriting any background but it is overwriting the background: none;

Pytorch reshape tensor dimension

import torch
>>>a = torch.Tensor([1,2,3,4,5])
>>>a.size()
torch.Size([5])
#use view to reshape

>>>b = a.view(1,a.shape[0])
>>>b
tensor([[1., 2., 3., 4., 5.]])
>>>b.size()
torch.Size([1, 5])
>>>b.type()
'torch.FloatTensor'

PHP GuzzleHttp. How to make a post request with params?

Try this

$client = new \GuzzleHttp\Client();
$client->post(
    'http://www.example.com/user/create',
    array(
        'form_params' => array(
            'email' => '[email protected]',
            'name' => 'Test user',
            'password' => 'testpassword'
        )
    )
);

Insert multiple values using INSERT INTO (SQL Server 2005)

In SQL Server 2008,2012,2014 you can insert multiple rows using a single SQL INSERT statement.

 INSERT INTO TableName ( Column1, Column2 ) VALUES
    ( Value1, Value2 ), ( Value1, Value2 )

Another way

INSERT INTO TableName (Column1, Column2 )
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2

How to turn off word wrapping in HTML?

Added webkit specific values missing from above

white-space: -moz-pre-wrap; /* Firefox */
white-space: -o-pre-wrap; /* Opera */
white-space: pre-wrap; /* Chrome */
word-wrap: break-word; /* IE */

JWT (Json Web Token) Audience "aud" versus Client_Id - What's the difference?

The JWT aud (Audience) Claim

According to RFC 7519:

The "aud" (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the "aud" claim when this claim is present, then the JWT MUST be rejected. In the general case, the "aud" value is an array of case- sensitive strings, each containing a StringOrURI value. In the special case when the JWT has one audience, the "aud" value MAY be a single case-sensitive string containing a StringOrURI value. The interpretation of audience values is generally application specific. Use of this claim is OPTIONAL.

The Audience (aud) claim as defined by the spec is generic, and is application specific. The intended use is to identify intended recipients of the token. What a recipient means is application specific. An audience value is either a list of strings, or it can be a single string if there is only one aud claim. The creator of the token does not enforce that aud is validated correctly, the responsibility is the recipient's to determine whether the token should be used.

Whatever the value is, when a recipient is validating the JWT and it wishes to validate that the token was intended to be used for its purposes, it MUST determine what value in aud identifies itself, and the token should only validate if the recipient's declared ID is present in the aud claim. It does not matter if this is a URL or some other application specific string. For example, if my system decides to identify itself in aud with the string: api3.app.com, then it should only accept the JWT if the aud claim contains api3.app.com in its list of audience values.

Of course, recipients may choose to disregard aud, so this is only useful if a recipient would like positive validation that the token was created for it specifically.

My interpretation based on the specification is that the aud claim is useful to create purpose-built JWTs that are only valid for certain purposes. For one system, this may mean you would like a token to be valid for some features but not for others. You could issue tokens that are restricted to only a certain "audience", while still using the same keys and validation algorithm.

Since in the typical case a JWT is generated by a trusted service, and used by other trusted systems (systems which do not want to use invalid tokens), these systems simply need to coordinate the values they will be using.

Of course, aud is completely optional and can be ignored if your use case doesn't warrant it. If you don't want to restrict tokens to being used by specific audiences, or none of your systems actually will validate the aud token, then it is useless.

Example: Access vs. Refresh Tokens

One contrived (yet simple) example I can think of is perhaps we want to use JWTs for access and refresh tokens without having to implement separate encryption keys and algorithms, but simply want to ensure that access tokens will not validate as refresh tokens, or vice-versa.

By using aud, we can specify a claim of refresh for refresh tokens and a claim of access for access tokens upon creating these tokens. When a request is made to get a new access token from a refresh token, we need to validate that the refresh token was a genuine refresh token. The aud validation as described above will tell us whether the token was actually a valid refresh token by looking specifically for a claim of refresh in aud.

OAuth Client ID vs. JWT aud Claim

The OAuth Client ID is completely unrelated, and has no direct correlation to JWT aud claims. From the perspective of OAuth, the tokens are opaque objects.

The application which accepts these tokens is responsible for parsing and validating the meaning of these tokens. I don't see much value in specifying OAuth Client ID within a JWT aud claim.

Java program to find the largest & smallest number in n numbers without using arrays

import java.util.Scanner;

public class LargestSmallestNumbers {

    private static Scanner input;

    public static void main(String[] args) {
       int count,items;
       int newnum =0 ;
       int highest=0;
       int lowest =0;

       input = new Scanner(System.in);
       System.out.println("How many numbers you want to enter?");
       items = input.nextInt();

       System.out.println("Enter "+items+" numbers: ");


       for (count=0; count<items; count++){
           newnum = input.nextInt();               
           if (highest<newnum)
               highest=newnum;

           if (lowest==0)
               lowest=newnum;

           else if (newnum<=lowest)
               lowest=newnum;
           }

       System.out.println("The highest number is "+highest);
       System.out.println("The lowest number is "+lowest);
    }
}

window.open(url, '_blank'); not working on iMac/Safari

To use window.open() in safari you must put it in an element's onclick event attribute.

For example: <button class='btn' onclick='window.open("https://www.google.com", "_blank");'>Open Google search</button>

android listview item height

The height of list view items are adjusted based on its contents. In first image, no content. so height is very minimum. In second image, height is increased based on the size of the text. Because, you specified android:layout_height="wrap_content".

Removing X-Powered-By

If you cannot disable the expose_php directive to mute PHP’s talkativeness (requires access to the php.ini), you could use Apache’s Header directive to remove the header field:

Header unset X-Powered-By

How to read data From *.CSV file using javascript?

Per the accepted answer,

I got this to work by changing the 1 to a 0 here:

for (var i=1; i<allTextLines.length; i++) {

changed to

for (var i=0; i<allTextLines.length; i++) {

It will compute the a file with one continuous line as having an allTextLines.length of 1. So if the loop starts at 1 and runs as long as it's less than 1, it never runs. Hence the blank alert box.

SSL Error When installing rubygems, Unable to pull data from 'https://rubygems.org/

The particular case of RubyGems (the command line tool) is that it requires to bundle inside of its code the trust certificates, which allow RubyGems to establish a connection with the servers even when base operating system is unable to verify the identity of them.

Up until a few months ago, this certificate was provided by one CA, but newer certificate is provided by a different one.

Because of this, existing installations of RubyGems would have to been updated before the switch of the certificate and give enough time for the change to spread (and people to update)

Anyone can find his solution by following the simple steps given in the link below

https://gist.github.com/luislavena/f064211759ee0f806c88

Which is the preferred way to concatenate a string in Python?

While somewhat dated, Code Like a Pythonista: Idiomatic Python recommends join() over + in this section. As does PythonSpeedPerformanceTips in its section on string concatenation, with the following disclaimer:

The accuracy of this section is disputed with respect to later versions of Python. In CPython 2.5, string concatenation is fairly fast, although this may not apply likewise to other Python implementations. See ConcatenationTestCode for a discussion.

What's the difference between utf8_general_ci and utf8_unicode_ci?

There are two big difference the sorting and the character matching:

Sorting:

  • utf8mb4_general_ci removes all accents and sorts one by one which may create incorrect sort results.
  • utf8mb4_unicode_ci sorts accurate.

Character Matching

They match characters differently.

For example, in utf8mb4_unicode_ci you have i != i, but in utf8mb4_general_ci it holds i=i.

For example, imagine you have a row with name="Yilmaz". Then

select id from users where name='Yilmaz';

would return the row if collocation is utf8mb4_general_ci, but if it is collocated with utf8mb4_unicode_ci it would not return the row!

On the other hand we have that a=ª and ß=ss in utf8mb4_unicode_ci which is not the case in utf8mb4_general_ci. So imagine you have a row with name="ªßi", then

select id from users where name='assi';

would return the row if collocation is utf8mb4_unicode_ci, but would not return a row if collocation is set to utf8mb4_general_ci.

A full list of matches for each collocation may be found here.

Annotations from javax.validation.constraints not working

You would have to call a Validator on the Entity if you want to validate it. Then you will get a set of ConstraintViolationException, which basically show for which field/s of your Entity there is a constraint violation and what exactly was it. Maybe you can also share some of the code you expect to validate your entity.

An often used technique is to do validation in @PrePersist and rollback transaction if using multiple data modifications during transaction or do other actions when you get a validation exception.

Your code should go like this:

@PrePersist
public void prePersist(SomeEntity someEntity){
    Validator validator = Validation.buildDefaultValidatorFactory.getValidator();
    Set<ConstraintViolation<SomeEntity>> = validator.validate(someEntity);
    //do stuff with them, like notify client what was the wrong field, log them, or, if empty, be happy
}

jQuery won't parse my JSON from AJAX query

I found in some of my implementations I had to add:

obj = new Object; obj = (data.obj);

which seemed to solve the problem. Eval or not it seemed to do exactly the same for me.

Convert a String of Hex into ASCII in Java

Check out Convert a string representation of a hex dump to a byte array using Java?

Disregarding encoding, etc. you can do new String (hexStringToByteArray("75546..."));

How to urlencode data for curl command?

Simple PHP option:

echo 'part-that-needs-encoding' | php -R 'echo urlencode($argn);'

Naming threads and thread-pools of ExecutorService

I use to do same like below (requires guava library) :

ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("SO-POOL-%d").build();
ExecutorService executorService = Executors.newFixedThreadPool(5,namedThreadFactory);

Reduce git repository size

git gc --aggressive is one way to force the prune process to take place (to be sure: git gc --aggressive --prune=now). You have other commands to clean the repo too. Don't forget though, sometimes git gc alone can increase the size of the repo!

It can be also used after a filter-branch, to mark some directories to be removed from the history (with a further gain of space); see here. But that means nobody is pulling from your public repo. filter-branch can keep backup refs in .git/refs/original, so that directory can be cleaned too.

Finally, as mentioned in this comment and this question; cleaning the reflog can help:

git reflog expire --all --expire=now
git gc --prune=now --aggressive

An even more complete, and possibly dangerous, solution is to remove unused objects from a git repository


Update Feb. 2021, eleven years later: the new git maintenance command (man page) should supersede git gc, and can be scheduled.

TypeError: ObjectId('') is not JSON serializable

Pymongo provides json_util - you can use that one instead to handle BSON types

def parse_json(data):
    return json.loads(json_util.dumps(data))

javax.naming.NameNotFoundException

The error means that your are trying to look up JNDI name, that is not attached to any EJB component - the component with that name does not exist.

As far as dir structure is concerned: you have to create a JAR file with EJB components. As I understand you want to play with EJB 2.X components (at least the linked example suggests that) so the structure of the JAR file should be:

/com/mypackage/MyEJB.class /com/mypackage/MyEJBInterface.class /com/mypackage/etc... etc... java classes /META-INF/ejb-jar.xml /META-INF/jboss.xml

The JAR file is more or less ZIP file with file extension changed from ZIP to JAR.

BTW. If you use JBoss 5, you can work with EJB 3.0, which are much more easier to configure. The simplest component is

@Stateless(mappedName="MyComponentName")
@Remote(MyEJBInterface.class)
public class MyEJB implements MyEJBInterface{
   public void bussinesMethod(){

   }
}

No ejb-jar.xml, jboss.xml is needed, just EJB JAR with MyEJB and MyEJBInterface compiled classes.

Now in your client code you need to lookup "MyComponentName".

Why do we use arrays instead of other data structures?

For O(1) random access, which can not be beaten.

How do you turn a Mongoose document into a plain object?

The lean option tells Mongoose to skip hydrating the result documents. This makes queries faster and less memory intensive, but the result documents are plain old JavaScript objects (POJOs), not Mongoose documents.

const leanDoc = await MyModel.findOne().lean();

not necessary to use JSON.parse() method

Is object empty?

fast onliner for 'dictionary'-objects:

function isEmptyDict(d){for (var k in d) return false; return true}

How do I set the background color of my main screen in Flutter?

and it's another approach to change the color of background:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(backgroundColor: Colors.pink,),);
  }
}

Remove all items from a FormArray in Angular

As of Angular 8+ you can use clear() to remove all controls in the FormArray:

const arr = new FormArray([
   new FormControl(),
   new FormControl()
]);
console.log(arr.length);  // 2

arr.clear();
console.log(arr.length);  // 0

For previous versions the recommended way is:

while (arr.length) {
   arr.removeAt(0);
}

https://angular.io/api/forms/FormArray#clear

Xcode is not currently available from the Software Update server

If you are trying this on a latest Mac OS X Mavericks, command line tools come with the Xcode 5.x

So make sure you have installed & updated Xcode to latest

after which make sure Xcode command line tools is pointed correctly using this command

xcode-select -p

Which might show some path like

/Applications/Xcode.app/Contents/Developer

Change the path to correct path using the switch command:

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

this should help you set it to correct path, after which you can use the same above command -p to check if it is set correctly

What is the use of "using namespace std"?

  • using: You are going to use it.
  • namespace: To use what? A namespace.
  • std: The std namespace (where features of the C++ Standard Library, such as string or vector, are declared).

After you write this instruction, if the compiler sees string it will know that you may be referring to std::string, and if it sees vector, it will know that you may be referring to std::vector. (Provided that you have included in your compilation unit the header files where they are defined, of course.)

If you don't write it, when the compiler sees string or vector it will not know what you are refering to. You will need to explicitly tell it std::string or std::vector, and if you don't, you will get a compile error.

Ruby on Rails - Import Data from a CSV file

The better way is to include it in a rake task. Create import.rake file inside /lib/tasks/ and put this code to that file.

desc "Imports a CSV file into an ActiveRecord table"
task :csv_model_import, [:filename, :model] => [:environment] do |task,args|
  lines = File.new(args[:filename], "r:ISO-8859-1").readlines
  header = lines.shift.strip
  keys = header.split(',')
  lines.each do |line|
    values = line.strip.split(',')
    attributes = Hash[keys.zip values]
    Module.const_get(args[:model]).create(attributes)
  end
end

After that run this command in your terminal rake csv_model_import[file.csv,Name_of_the_Model]

How to prevent favicon.ico requests?

I believe I've seen this (I haven't tested it or used it personally though):

<link rel="shortcut icon" href="#" />

Anyone had similar experience?

EDIT:

I just tested the above snippet and on a forced full refresh, no favicon requests were seen in Fiddler. I tested against IE8 (Compat mode as IE7 standards) and FF 3.6.

Onclick event to remove default value in a text input field

u can use placeholder and when u write a text on the search box placeholder will hidden. Thanks

<input placeholder="Search" type="text" />

grep's at sign caught as whitespace

No -P needed; -E is sufficient:

grep -E '(^|\s)abc(\s|$)' 

or even without -E:

grep '\(^\|\s\)abc\(\s\|$\)'