Programs & Examples On #Binutils

The GNU binary utilities. A collection of tools for operating on object files. Most notably they include the GNU assembler and linker. They are typically used in conjunction with the GNU compiler collection (GCC).

Install pip in docker

While T. Arboreus's answer might fix the issues with resolving 'archive.ubuntu.com', I think the last error you're getting says that it doesn't know about the packages php5-mcrypt and python-pip. Nevertheless, the reduced Dockerfile of you with just these two packages worked for me (using Debian 8.4 and Docker 1.11.0), but I'm not quite sure if that could be the case because my host system is different than yours.

FROM ubuntu:14.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    php5-mcrypt \
    python-pip

However, according to this answer you should think about installing the python3-pip package instead of the python-pip package when using Python 3.x.

Furthermore, to make the php5-mcrypt package installation working, you might want to add the universe repository like it's shown right here. I had trouble with the add-apt-repository command missing in the Ubuntu Docker image so I installed the package software-properties-common at first to make the command available.

Splitting up the statements and putting apt-get update and apt-get install into one RUN command is also recommended here.

Oh and by the way, you actually don't need the -y flag at apt-get update because there is nothing that has to be confirmed automatically.

Finally:

FROM ubuntu:14.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    software-properties-common
RUN add-apt-repository universe
RUN apt-get update && apt-get install -y \
    apache2 \
    curl \
    git \
    libapache2-mod-php5 \
    php5 \
    php5-mcrypt \
    php5-mysql \
    python3.4 \
    python3-pip

Remark: The used versions (e.g. of Ubuntu) might be outdated in the future.

npm WARN package.json: No repository field

use npm install -g angular-cli instead of
npm install -g@nagular/cli to install Angular

Twitter Bootstrap dropdown menu

You must include jQuery in the project.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

I didn't find any doc about this so I just opened a random code example from tutorialrepublic.com http://www.tutorialrepublic.com/twitter-bootstrap-tutorial/bootstrap-dropdowns.php

Hope this helps someone else.

Does Python have a ternary conditional operator?

I find cumbersome the default python syntax val = a if cond else b, so sometimes I do this:

iif = lambda (cond, a, b): a if cond else b
# so I can then use it like:
val = iif(cond, a, b)

Of course, it has the downside of always evaluating both sides (a and b), but the syntax it's way clearer to me

Gradle to execute Java class (without modifying build.gradle)

You just need to use the Gradle Application plugin:

apply plugin:'application'
mainClassName = "org.gradle.sample.Main"

And then simply gradle run.

As Teresa points out, you can also configure mainClassName as a system property and run with a command line argument.

Change the column label? e.g.: change column "A" to column "Name"

What version of Excel?

In general, you cannot change the column letters. They are part of the Excel system.

You can use a row in the sheet to enter headers for a table that you are using. The table headers can be descriptive column names.

In Excel 2007 and later, you can convert a range of data into an Excel Table (Insert Ribbon > Table). An Excel Table can use structured table references instead of cell addresses, so the labels in the first row of the table now serve as a name reference for the data in the column.

If you have an Excel Table in your sheet (Excel 2007 and later) and scroll down, the column letters will be replaced with the column headers for the table column.

enter image description here

If this does not answer your question, please consider editing your question to include the detail you want to learn about.

Are there bookmarks in Visual Studio Code?

If you are using vscodevim extension, then you can harness the power of vim keyboard moves. When you are on a line that you would like to bookmark, in normal mode, you can type:

m {a-z A-Z} for a possible 52 bookmarks within a file. Small letter alphabets are for bookmarks within a single file. Capital letters preserve their marks across files.

To navigate to a bookmark from within any file, you then need to hit ' {a-z A-Z}. I don't think these bookmarks stay across different VSCode sessions though.

More vim shortcuts here.

How to construct a set out of list items in python?

You can do

my_set = set(my_list)

or, in Python 3,

my_set = {*my_list}

to create a set from a list. Conversely, you can also do

my_list = list(my_set)

or, in Python 3,

my_list = [*my_set]

to create a list from a set.

Just note that the order of the elements in a list is generally lost when converting the list to a set since a set is inherently unordered. (One exception in CPython, though, seems to be if the list consists only of non-negative integers, but I assume this is a consequence of the implementation of sets in CPython and that this behavior can vary between different Python implementations.)

Scrolling to element using webdriver?

Example:

driver.execute_script("arguments[0].scrollIntoView();", driver.find_element_by_css_selector(.your_css_selector))

This one always works for me for any type of selectors. There is also the Actions class, but for this case, it is not so reliable.

grep a tab in UNIX

use gawk, set the field delimiter to tab (\t) and check for number of fields. If more than 1, then there is/are tabs

awk -F"\t" 'NF>1' file

Python POST binary data

you need to add Content-Disposition header, smth like this (although I used mod-python here, but principle should be the same):

request.headers_out['Content-Disposition'] = 'attachment; filename=%s' % myfname

Assert an object is a specific type

You can use the assertThat method and the Matchers that comes with JUnit.

Take a look at this link that describes a little bit about the JUnit Matchers.

Example:

public class BaseClass {
}

public class SubClass extends BaseClass {
}

Test:

import org.junit.Test;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;

/**
 * @author maba, 2012-09-13
 */
public class InstanceOfTest {

    @Test
    public void testInstanceOf() {
        SubClass subClass = new SubClass();
        assertThat(subClass, instanceOf(BaseClass.class));
    }
}

How to connect TFS in Visual Studio code

I know I'm a little late to the party, but I did want to throw some interjections. (I would have commented but not enough reputation points yet, so, here's a full answer).

This requires the latest version of VS Code, Azure Repo Extention, and Git to be installed.

Anyone looking to use the new VS Code (or using the preview like myself), when you go to the Settings (Still File -> Preferences -> Settings or CTRL+, ) you'll be looking under User Settings -> Extensions -> Azure Repos.

Azure_Repo_Settings

Then under Tfvc: Location you can paste the location of the executable.

Location_Settings

For 2017 it'll be

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

Or for 2019 (Preview)

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

After adding the location, I closed my VS Code (not sure if this was needed) and went my git repo to copy the git URL.

Git_URL

After that, went back into VS Code went to the Command Palette (View -> Command Palette or CTRL+Shift+P) typed Git: Clone pasted my repo:

Git_Repo

Selected the location for the repo to be stored. Next was an error that popped up. I proceeded to follow this video which walked me through clicking on the Team button with the exclamation mark on the bottom of your VS Code Screen

Team_Button

Then chose the new method of authentication

New_Method

Copy by using CTRL+C and then press enter. Your browser will launch a page where you'll enter the code you copied (CTRL+V).

Enter_Code_Screen

Click Continue

Continue_Button

Log in with your Microsoft Credentials and you should see a change on the bottom bar of VS Code.

Bottom_Bar

Cheers!

Send JavaScript variable to PHP variable

As Jordan already said you have to post back the javascript variable to your server before the server can handle the value. To do this you can either program a javascript function that submits a form - or you can use ajax / jquery. jQuery.post

Maybe the most easiest approach for you is something like this

function myJavascriptFunction() { 
  var javascriptVariable = "John";
  window.location.href = "myphpfile.php?name=" + javascriptVariable; 
}

On your myphpfile.php you can use $_GET['name'] after your javascript was executed.

Regards

PHP compare time

$ThatTime ="14:08:10";
if (time() >= strtotime($ThatTime)) {
  echo "ok";
}

A solution using DateTime (that also regards the timezone).

$dateTime = new DateTime($ThatTime);
if ($dateTime->diff(new DateTime)->format('%R') == '+') {
  echo "OK";
}

http://php.net/datetime.diff

What regular expression will match valid international phone numbers?

A simple version for european numbers, that matches numbers like 0034617393211 but also long ones as 004401484172842.

^0{2}[0-9]{11,}

Hope it helps :·)

Get width in pixels from element with style set with %?

You want to get the computed width. Try: .offsetWidth

(I.e: this.offsetWidth='50px' or var w=this.offsetWidth)

You might also like this answer on SO.

How to add 20 minutes to a current date?

Just get the millisecond timestamp and add 20 minutes to it:

twentyMinutesLater = new Date(currentDate.getTime() + (20*60*1000))

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

The accepted answer to this question is awesome and should remain the accepted answer. However I ran into an issue with the code where the read stream was not always being ended/closed. Part of the solution was to send autoClose: true along with start:start, end:end in the second createReadStream arg.

The other part of the solution was to limit the max chunksize being sent in the response. The other answer set end like so:

var end = positions[1] ? parseInt(positions[1], 10) : total - 1;

...which has the effect of sending the rest of the file from the requested start position through its last byte, no matter how many bytes that may be. However the client browser has the option to only read a portion of that stream, and will, if it doesn't need all of the bytes yet. This will cause the stream read to get blocked until the browser decides it's time to get more data (for example a user action like seek/scrub, or just by playing the stream).

I needed this stream to be closed because I was displaying the <video> element on a page that allowed the user to delete the video file. However the file was not being removed from the filesystem until the client (or server) closed the connection, because that is the only way the stream was getting ended/closed.

My solution was just to set a maxChunk configuration variable, set it to 1MB, and never pipe a read a stream of more than 1MB at a time to the response.

// same code as accepted answer
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;

// poor hack to send smaller chunks to the browser
var maxChunk = 1024 * 1024; // 1MB at a time
if (chunksize > maxChunk) {
  end = start + maxChunk - 1;
  chunksize = (end - start) + 1;
}

This has the effect of making sure that the read stream is ended/closed after each request, and not kept alive by the browser.

I also wrote a separate StackOverflow question and answer covering this issue.

Add st, nd, rd and th (ordinal) suffix to a number

I wrote this function for higher numbers and all test cases

function numberToOrdinal(num) {
    if (num === 0) {
        return '0'
    };
    let i = num.toString(), j = i.slice(i.length - 2), k = i.slice(i.length - 1);
    if (j >= 10 && j <= 20) {
        return (i + 'th')
    } else if (j > 20 && j < 100) {
        if (k == 1) {
            return (i + 'st')
        } else if (k == 2) {
            return (i + 'nd')
        } else if (k == 3) {
            return (i + 'rd')
        } else {
            return (i + 'th')
        }
    } else if (j == 1) {
        return (i + 'st')
    } else if (j == 2) {
        return (i + 'nd')
    } else if (j == 3) {
        return (i + 'rd')
    } else {
        return (i + 'th')
    }
}

npm install won't install devDependencies

I had a package-lock.json file from an old version of my package.json, I deleted that and then everything installed correctly.

How to check SQL Server version

select charindex(  'Express',@@version)

if this value is 0 is not a express edition

Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

Update using NuGet Package Manager Console in your Visual Studio

Update-Package -reinstall Microsoft.AspNet.Mvc

How to use an output parameter in Java?

This is not accurate ---> "...* pass array. arrays are passed by reference. i.e. if you pass array of integers, modified the array inside the method.

Every parameter type is passed by value in Java. Arrays are object, its object reference is passed by value.

This includes an array of primitives (int, double,..) and objects. The integer value is changed by the methodTwo() but it is still the same arr object reference, the methodTwo() cannot add an array element or delete an array element. methodTwo() cannot also, create a new array then set this new array to arr. If you really can pass an array by reference, you can replace that arr with a brand new array of integers.

Every object passed as parameter in Java is passed by value, no exceptions.

MySQL WHERE: how to write "!=" or "not equals"?

DELETE FROM konta WHERE taken <> '';

How to trim white spaces of array values in php

I had trouble with the existing answers when using multidimensional arrays. This solution works for me.

if (is_array($array)) {
    foreach ($array as $key => $val) {
        $array[$key] = trim($val);
    }
}

PHP check if file is an image

Using file extension and getimagesize function to detect if uploaded file has right format is just the entry level check and it can simply bypass by uploading a file with true extension and some byte of an image header but wrong content.

for being secure and safe you may make thumbnail/resize (even with original image sizes) the uploaded picture and save this version instead the uploaded one. Also its possible to get uploaded file content and search it for special character like <?php to find the file is image or not.

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.

MySQL select all rows from last month until (now() - 1 month), for comparative purposes

You can get the first of the month, by calculating the last_day of the month before and add one day. It is awkward, but I think it is better than formatting a date as string and use that for calculation.

select 
  *
from
  yourtable t
where
  /* Greater or equal to the start of last month */
  t.date >= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 2 MONTH)), INTERVAL 1 DAY) and
  /* Smaller or equal than one month ago */
  t.date <= DATE_SUB(NOW(), INTERVAL 1 MONTH)

show and hide divs based on radio button click

This worked for me:

<!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>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Untitled Document</title>
        <script type="text/javascript">
            function show(str){
                document.getElementById('sh2').style.display = 'none';
                document.getElementById('sh1').style.display = 'block';
            }
            function show2(sign){
                document.getElementById('sh2').style.display = 'block';
                document.getElementById('sh1').style.display = 'none';
            }
        </script>
    </head>

    <body>
        <p>
            <input type="radio" name="r1" id="e1" onchange="show2()"/>&nbsp;I Am New User&nbsp;&nbsp;&nbsp;
            <input type="radio" checked="checked" name="r1" onchange="show(this.value)"/>&nbsp;Existing Member
        </p>
        <div id="sh1">Hello There !!</div>
        <p>&nbsp;</p>
        <div id="sh2" style="display:none;">Hey Watz up !!</div>
    </body>
</html>

bash assign default value

The default value parameter expansion is often useful in build scripts like the example one below. If the user just calls the script as-is, perl will not be built in. The user has to explicitly set WITH_PERL to a value other than "no" to have it built in.

$ cat defvar.sh
#!/bin/bash

WITH_PERL=${WITH_PERL:-no}

if [[ "$WITH_PERL" != no ]]; then
    echo "building with perl"
    # ./configure --enable=perl
else
    echo "not building with perl"
    # ./configure
fi

Build without Perl

$ ./defvar.sh
not building with perl

Build with Perl

$ WITH_PERL=yes ./defvar.sh
building with perl

Can pm2 run an 'npm start' script

pm2 start npm --name "custom_pm2_name" -- run prod

"scripts": {
    "prod": "nodemon --exec babel-node ./src/index.js"
  }

This worked for me when the others didnt

How can I copy a Python string?

To put it a different way "id()" is not what you care about. You want to know if the variable name can be modified without harming the source variable name.

>>> a = 'hello'                                                                                                                                                                                                                                                                                        
>>> b = a[:]                                                                                                                                                                                                                                                                                           
>>> c = a                                                                                                                                                                                                                                                                                              
>>> b += ' world'                                                                                                                                                                                                                                                                                      
>>> c += ', bye'                                                                                                                                                                                                                                                                                       
>>> a                                                                                                                                                                                                                                                                                                  
'hello'                                                                                                                                                                                                                                                                                                
>>> b                                                                                                                                                                                                                                                                                                  
'hello world'                                                                                                                                                                                                                                                                                          
>>> c                                                                                                                                                                                                                                                                                                  
'hello, bye'                                                                                                                                                                                                                                                                                           

If you're used to C, then these are like pointer variables except you can't de-reference them to modify what they point at, but id() will tell you where they currently point.

The problem for python programmers comes when you consider deeper structures like lists or dicts:

>>> o={'a': 10}                                                                                                                                                                                                                                                                                        
>>> x=o                                                                                                                                                                                                                                                                                                
>>> y=o.copy()                                                                                                                                                                                                                                                                                         
>>> x['a'] = 20                                                                                                                                                                                                                                                                                        
>>> y['a'] = 30                                                                                                                                                                                                                                                                                        
>>> o                                                                                                                                                                                                                                                                                                  
{'a': 20}                                                                                                                                                                                                                                                                                              
>>> x                                                                                                                                                                                                                                                                                                  
{'a': 20}                                                                                                                                                                                                                                                                                              
>>> y                                                                                                                                                                                                                                                                                                  
{'a': 30}                                                                                                                                                                                                                                                                                              

Here o and x refer to the same dict o['a'] and x['a'], and that dict is "mutable" in the sense that you can change the value for key 'a'. That's why "y" needs to be a copy and y['a'] can refer to something else.

Storing database records into array

You shouldn't search through that array, but use database capabilities for this
Suppose you're passing username through GET form:

if (isset($_GET['search'])) {
  $search = mysql_real_escape_string($_GET['search']);
  $sql = "SELECT * FROM users WHERE username = '$search'";
  $res = mysql_query($sql) or trigger_error(mysql_error().$sql);
  $row = mysql_fetch_assoc($res);
  if ($row){
    print_r($row); //do whatever you want with found info
  }
}

How to validate domain name in PHP?

I know that this is an old question, but it was the first answer on a Google search, so it seems relevant. I recently had this same problem. The solution in my case was to just use the Public Suffix List:

https://publicsuffix.org/learn/

The suggested language specific libraries listed should all allow for easy validation of not just domain format, but also top level domain validity.

Unable to connect to SQL Express "Error: 26-Error Locating Server/Instance Specified)

It's security all about. Make sure you have double check your firewall (windows and anti virus) in some cases when you disabled av firewall and restart your computer, automatically windows firewall is active and it's still block your application. Hope this is helpful ..

How to add a custom right-click menu to a webpage?

According to the answers here and on other 'flows, I've made a version that looks like the one of Google Chrome, with css3 transition. JS Fiddle

Lets start eazy, since we have the js above on this page, we can worry about the css and layout. The layout that we will be using is an <a> element with a <img> element or a font awesome icon (<i class="fa fa-flag"></i>) and a <span> to show the keyboard shortcuts. So this is the structure:

<a href="#" onclick="doSomething()">
  <img src="path/to/image.gif" />
  This is a menu option
  <span>Ctrl + K</span>
</a>

We will put these in a div and show that div on the right-click. Let's style them like in Google Chrome, shall we?

#menu a {
  display: block;
  color: #555;
  text-decoration: no[...]

Now we will add the code from the accepted answer, and get the X and Y value of the cursor. To do this, we will use e.clientX and e.clientY. We are using client, so the menu div has to be fixed.

var i = document.getElementById("menu").style;
if (document.addEventListener) {
  document.addEventListener('contextmenu', function(e) {
    var posX = e.clientX;
    var posY = e.client[...]

And that is it! Just add the css transisions to fade in and out, and done!

_x000D_
_x000D_
var i = document.getElementById("menu").style;_x000D_
if (document.addEventListener) {_x000D_
  document.addEventListener('contextmenu', function(e) {_x000D_
    var posX = e.clientX;_x000D_
    var posY = e.clientY;_x000D_
    menu(posX, posY);_x000D_
    e.preventDefault();_x000D_
  }, false);_x000D_
  document.addEventListener('click', function(e) {_x000D_
    i.opacity = "0";_x000D_
    setTimeout(function() {_x000D_
      i.visibility = "hidden";_x000D_
    }, 501);_x000D_
  }, false);_x000D_
} else {_x000D_
  document.attachEvent('oncontextmenu', function(e) {_x000D_
    var posX = e.clientX;_x000D_
    var posY = e.clientY;_x000D_
    menu(posX, posY);_x000D_
    e.preventDefault();_x000D_
  });_x000D_
  document.attachEvent('onclick', function(e) {_x000D_
    i.opacity = "0";_x000D_
    setTimeout(function() {_x000D_
      i.visibility = "hidden";_x000D_
    }, 501);_x000D_
  });_x000D_
}_x000D_
_x000D_
function menu(x, y) {_x000D_
  i.top = y + "px";_x000D_
  i.left = x + "px";_x000D_
  i.visibility = "visible";_x000D_
  i.opacity = "1";_x000D_
}
_x000D_
body {_x000D_
  background: white;_x000D_
  font-family: sans-serif;_x000D_
  color: #5e5e5e;_x000D_
}_x000D_
_x000D_
#menu {_x000D_
  visibility: hidden;_x000D_
  opacity: 0;_x000D_
  position: fixed;_x000D_
  background: #fff;_x000D_
  color: #555;_x000D_
  font-family: sans-serif;_x000D_
  font-size: 11px;_x000D_
  -webkit-transition: opacity .5s ease-in-out;_x000D_
  -moz-transition: opacity .5s ease-in-out;_x000D_
  -ms-transition: opacity .5s ease-in-out;_x000D_
  -o-transition: opacity .5s ease-in-out;_x000D_
  transition: opacity .5s ease-in-out;_x000D_
  -webkit-box-shadow: 2px 2px 2px 0px rgba(143, 144, 145, 1);_x000D_
  -moz-box-shadow: 2px 2px 2px 0px rgba(143, 144, 145, 1);_x000D_
  box-shadow: 2px 2px 2px 0px rgba(143, 144, 145, 1);_x000D_
  padding: 0px;_x000D_
  border: 1px solid #C6C6C6;_x000D_
}_x000D_
_x000D_
#menu a {_x000D_
  display: block;_x000D_
  color: #555;_x000D_
  text-decoration: none;_x000D_
  padding: 6px 8px 6px 30px;_x000D_
  width: 250px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
#menu a img,_x000D_
#menu a i.fa {_x000D_
  height: 20px;_x000D_
  font-size: 17px;_x000D_
  width: 20px;_x000D_
  position: absolute;_x000D_
  left: 5px;_x000D_
  top: 2px;_x000D_
}_x000D_
_x000D_
#menu a span {_x000D_
  color: #BCB1B3;_x000D_
  float: right;_x000D_
}_x000D_
_x000D_
#menu a:hover {_x000D_
  color: #fff;_x000D_
  background: #3879D9;_x000D_
}_x000D_
_x000D_
#menu hr {_x000D_
  border: 1px solid #EBEBEB;_x000D_
  border-bottom: 0;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<h2>CSS3 and JAVASCRIPT custom menu.</h2>_x000D_
<em>Stephan Stanisic | Lisence free</em>_x000D_
<p>Right-click anywhere on this page to open the custom menu. Styled like the Google Chrome contextmenu. And yes, you can use <i class="fa fa-flag"></i>font-awesome</p>_x000D_
<p style="font-size: small">_x000D_
  <b>Lisence</b>_x000D_
  <br /> "THE PIZZA-WARE LICENSE" (Revision 42):_x000D_
  <br /> You can do whatever you want with this stuff. If we meet some day, and you think this stuff is worth it, you can buy me a Pizza in return._x000D_
  <br />_x000D_
  <a style="font-size:xx-small" href="https://github.com/KLVN/UrbanDictionary_API#license">https://github.com/KLVN/UrbanDictionary_API#license</a>_x000D_
</p>_x000D_
<br />_x000D_
<br />_x000D_
<small>(The white body background is just because I hate the light blue editor background on the result on jsfiddle)</small>_x000D_
<div id="menu">_x000D_
  <a href="#">_x000D_
    <img src="http://puu.sh/nr60s/42df867bf3.png" /> AdBlock Plus <span>Ctrl + ?!</span>_x000D_
  </a>_x000D_
  <a href="#">_x000D_
    <img src="http://puu.sh/nr5Z6/4360098fc1.png" /> SNTX <span>Ctrl + ?!</span>_x000D_
  </a>_x000D_
  <hr />_x000D_
  <a href="#">_x000D_
    <i class="fa fa-fort-awesome"></i> Fort Awesome <span>Ctrl + ?!</span>_x000D_
  </a>_x000D_
  <a href="#">_x000D_
    <i class="fa fa-flag"></i> Font Awesome <span>Ctrl + ?!</span>_x000D_
  </a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Error 500: Premature end of script headers

In my case (referencing a PHP file in the top folder of a Wordpress plugin) I had to change the permissions on that folder. My test environment was fine, but when deployed the folder had 775. I changed it to 755 and it works fine.

Multidimensional Array [][] vs [,]

double[,] is a 2d array (matrix) while double[][] is an array of arrays (jagged arrays) and the syntax is:

double[][] ServicePoint = new double[10][];

When is the init() function run?

See this picture. :)

import --> const --> var --> init()

  1. If a package imports other packages, the imported packages are initialized first.

  2. Current package's constant initialized then.

  3. Current package's variables are initialized then.

  4. Finally, init() function of current package is called.

A package can have multiple init functions (either in a single file or distributed across multiple files) and they are called in the order in which they are presented to the compiler.


A package will be initialised only once even if it is imported from multiple packages.

Changing color of Twitter bootstrap Nav-Pills

The Solution to this problem, tends to differ slightly from case to case. The general way to solve it is to
1.) right-click the bootstrap pill and select inspect or inspect element if firefox
2.) copy the css selector for the rule that changes the color
3.) modify it in your custom css file like so...

.TheCssSelectorYouJustCopied{
    background-color: #ff0000!important;//or any other color
}

#1273 - Unknown collation: 'utf8mb4_unicode_ci' cPanel

If you have already exported a .sql file, the best thing to do is to Find and Replace the following if you have them in your file:

  • utf8mb4_0900_ai_ci to utf8_unicode_ci
  • utf8mb4 to utf8
  • utf8_unicode_520_ci to utf8_unicode_ci

It will replace utf8mb4_unicode_ci to utf8_unicode_ci. Now you go to your phpMyAdmin cPanel and set the DB collation to utf8_unicode_ci through Operations > Collation.

If you are exporting to a .sql, it's better to change the format on how you're exporting the file. Check out Evster's anwer (it's in the same page as this)

Making PHP var_dump() values display one line per value

Wrap it in <pre> tags to preserve formatting.

Running Command Line in Java

Have you tried the exec command within the Runtime class?

Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug")

Runtime - Java Documentation

Asynchronous file upload (AJAX file upload) using jsp and javascript

The two common approaches are to submit the form to an invisible iframe, or to use a Flash control such as YUI Uploader. You could also use Java instead of Flash, but this has a narrower install base.

(Shame about the layout table in the first example)

Why would one omit the close tag?

If I understand the question correctly, it has to do with output buffering and the affect this might have on closing/ending tags. I am not sure that is an entirely valid question. The problem is that the output buffer does not mean all content is held in memory before sending it out to the client. It means some of the content is.

The programmer can purposely flush the buffer, or the output buffer so does the output buffer option in PHP really change how the closing tag affects coding? I would argue that it does not.

And maybe that is why most of the answers went back to personal style and syntax.

How do I create a URL shortener?

My approach: Take the Database ID, then Base36 Encode it. I would NOT use both Upper AND Lowercase letters, because that makes transmitting those URLs over the telephone a nightmare, but you could of course easily extend the function to be a base 62 en/decoder.

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

I had this problem when I wanted to make a vnc connection via a tunnel. But the vncserver was not running. I solved it by opening the channel on the remote machine with vncserver :3.

Factory Pattern. When to use factory methods?

Any class deferring the object creation to its sub class for the object it needs to work with can be seen as an example of Factory pattern.

I have mentioned in detail in an another answer at https://stackoverflow.com/a/49110001/504133

JPA COUNT with composite primary key query not working

Use count(d.ertek) or count(d.id) instead of count(d). This can be happen when you have composite primary key at your entity.

How to restart Activity in Android

The solution for your question is:

public static void restartActivity(Activity act){
    Intent intent=new Intent();
    intent.setClass(act, act.getClass());
    ((Activity)act).startActivity(intent);
    ((Activity)act).finish();
}

You need to cast to activity context to start new activity and as well as to finish the current activity.

Hope this helpful..and works for me.

JQuery ajax call default timeout value

As an aside, when trying to diagnose a similar bug I realised that jquery's ajax error callback returns a status of "timeout" if it failed due to a timeout.

Here's an example:

$.ajax({
    url: "/ajax_json_echo/",
    timeout: 500,
    error: function(jqXHR, textStatus, errorThrown) {
        alert(textStatus); // this will be "timeout"
    }
});

Here it is on jsfiddle.

How to disable manual input for JQuery UI Datepicker field?

I think you should add style="background:white;" to make looks like it is writable

<input type="text" size="23" name="dateMonthly" id="dateMonthly" readonly="readonly"   style="background:white;"/>

Bootstrap DatePicker, how to set the start date for tomorrow?

There is no official datepicker for bootstrap; as such, you should explicitly state which one you're using.

If you're using eternicode/bootstrap-datepicker, there's a startDate option. As discussed directly under the Options section in the README:

All options that take a "Date" can handle a Date object; a String formatted according to the given format; or a timedelta relative to today, eg '-1d', '+6m +1y', etc, where valid units are 'd' (day), 'w' (week), 'm' (month), and 'y' (year).

So you would do:

$('#datepicker').datepicker({
    startDate: '+1d'
})

How do you completely remove Ionic and Cordova installation from mac?

Command to remove Cordova and ionic

  • For Window system

    • npm uninstall -g ionic
    • npm uninstall -g cordova
  • For Mac system

    • sudo npm uninstall -g ionic
    • sudo npm uninstall -g cordova
  • For install cordova and ionic

    • npm install -g cordova
    • npm install -g ionic

Note:

  • If you want to install in MAC System use before npm use sudo only.
  • And plan to install specific version of ionic and cordova then use @(version no.).

eg.

sudo npm install -g [email protected]

sudo npm install -g [email protected]

How to get integer values from a string in Python?

def function(string):  
    final = ''  
    for i in string:  
        try:   
            final += str(int(i))   
        except ValueError:  
            return int(final)  
print(function("4983results should get"))  

Calculate summary statistics of columns in dataframe

describe may give you everything you want otherwise you can perform aggregations using groupby and pass a list of agg functions: http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-multiple-functions-at-once

In [43]:

df.describe()

Out[43]:

       shopper_num is_martian  number_of_items  count_pineapples
count      14.0000         14        14.000000                14
mean        7.5000          0         3.357143                 0
std         4.1833          0         6.452276                 0
min         1.0000      False         0.000000                 0
25%         4.2500          0         0.000000                 0
50%         7.5000          0         0.000000                 0
75%        10.7500          0         3.500000                 0
max        14.0000      False        22.000000                 0

[8 rows x 4 columns]

Note that some columns cannot be summarised as there is no logical way to summarise them, for instance columns containing string data

As you prefer you can transpose the result if you prefer:

In [47]:

df.describe().transpose()

Out[47]:

                 count      mean       std    min   25%  50%    75%    max
shopper_num         14       7.5    4.1833      1  4.25  7.5  10.75     14
is_martian          14         0         0  False     0    0      0  False
number_of_items     14  3.357143  6.452276      0     0    0    3.5     22
count_pineapples    14         0         0      0     0    0      0      0

[4 rows x 8 columns]

How do you post to the wall on a facebook page (not profile)

Get PHP SDK from github and run the following code:

<?php
$attachment = array(
    'message' => 'this is my message',
    'name' => 'This is my demo Facebook application!',
    'caption' => "Caption of the Post",
    'link' => 'http://mylink.com',
    'description' => 'this is a description',
    'picture' => 'http://mysite.com/pic.gif',
    'actions' => array(
        array(
            'name' => 'Get Search',
            'link' => 'http://www.google.com'
        )
    )
);

$result = $facebook->api('/me/feed/', 'post', $attachment);

the above code will Post the message on to your wall... and if you want to post onto your friends or others wall then replace me with the Facebook User Id of that user..for further information look out the API Documentation.

Auto Generate Database Diagram MySQL

Try SchemaBank. They support reverse engineering too.

Sorting HTML table with JavaScript

I have edited the code from one of the example here to use jquery. It's still not 100% jquery though. Any thoughts on the two different versions, like what are the pros and cons of each?

function column_sort() {
    getCellValue = (tr, idx) => $(tr).find('td').eq( idx ).text();

    comparer = (idx, asc) => (a, b) => ((v1, v2) => 
        v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)
        )(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
    
    table = $(this).closest('table')[0];
    tbody = $(table).find('tbody')[0];

    elm = $(this)[0];
    children = elm.parentNode.children;
    Array.from(tbody.querySelectorAll('tr')).sort( comparer(
        Array.from(children).indexOf(elm), table.asc = !table.asc))
        .forEach(tr => tbody.appendChild(tr) );
}

table.find('thead th').on('click', column_sort);

How to set cursor position in EditText?

You can use like this:

if (your_edittext.getText().length() > 0 ) {

    your_edittext.setSelection(your_edittext.getText().length());
}

Can you add this line to your EditText xml

android:gravity="right"
android:ellipsize="end"
android:paddingLeft="10dp"//you set this as you need

But when any Text writing you should set the paddingleft to zero

you should use this on addTextChangedListener

How to pass a variable to the SelectCommand of a SqlDataSource?

You can use the built in OnSelecting parameter of asp:SqlDataSource

Example: [.aspx file]

<asp:SqlDataSource ID="SqldsExample" runat="server"
SelectCommand="SELECT [SomeColumn], [AnotherColumn] 
               FROM [SomeTable]
               WHERE [Dynamic_Variable_Column] = @DynamicVariable"
OnSelecting="SqldsExample_Selecting">
<SelectParameters>
    <asp:Parameter Name="DynamicVariable" Type="String"/>
</SelectParameters>

Then in your code behind implement your OnSelecting method: [.aspx.cs]

protected void SqldsExample_Selecting(object sender, SqlDataSourceCommandEventArgs e)
{
     e.Command.Parameters["@DynamicVariable"].Value = (whatever value you want);
}

You can also use this for the other types of DB operations just implement your own methods:

OnInserting="SqldsExample_Inserting"
OnUpdating="SqldsExample_Updating"
OnDeleting="SqldsExample_Deleting"

Unable to allocate array with shape and data type

I had this same problem on Window's and came across this solution. So if someone comes across this problem in Windows the solution for me was to increase the pagefile size, as it was a Memory overcommitment problem for me too.

Windows 8

  1. On the Keyboard Press the WindowsKey + X then click System in the popup menu
  2. Tap or click Advanced system settings. You might be asked for an admin password or to confirm your choice
  3. On the Advanced tab, under Performance, tap or click Settings.
  4. Tap or click the Advanced tab, and then, under Virtual memory, tap or click Change
  5. Clear the Automatically manage paging file size for all drives check box.
  6. Under Drive [Volume Label], tap or click the drive that contains the paging file you want to change
  7. Tap or click Custom size, enter a new size in megabytes in the initial size (MB) or Maximum size (MB) box, tap or click Set, and then tap or click OK
  8. Reboot your system

Windows 10

  1. Press the Windows key
  2. Type SystemPropertiesAdvanced
  3. Click Run as administrator
  4. Under Performance, click Settings
  5. Select the Advanced tab
  6. Select Change...
  7. Uncheck Automatically managing paging file size for all drives
  8. Then select Custom size and fill in the appropriate size
  9. Press Set then press OK then exit from the Virtual Memory, Performance Options, and System Properties Dialog
  10. Reboot your system

Note: I did not have the enough memory on my system for the ~282GB in this example but for my particular case this worked.

EDIT

From here the suggested recommendations for page file size:

There is a formula for calculating the correct pagefile size. Initial size is one and a half (1.5) x the amount of total system memory. Maximum size is three (3) x the initial size. So let's say you have 4 GB (1 GB = 1,024 MB x 4 = 4,096 MB) of memory. The initial size would be 1.5 x 4,096 = 6,144 MB and the maximum size would be 3 x 6,144 = 18,432 MB.

Some things to keep in mind from here:

However, this does not take into consideration other important factors and system settings that may be unique to your computer. Again, let Windows choose what to use instead of relying on some arbitrary formula that worked on a different computer.

Also:

Increasing page file size may help prevent instabilities and crashing in Windows. However, a hard drive read/write times are much slower than what they would be if the data were in your computer memory. Having a larger page file is going to add extra work for your hard drive, causing everything else to run slower. Page file size should only be increased when encountering out-of-memory errors, and only as a temporary fix. A better solution is to adding more memory to the computer.

Eclipse - Failed to create the java virtual machine

Recently i encounter this issue and try all of the above method but none of them works for me.

Here is another Trick for to solve this error is

i just delete the eclipse configuration file and eclipse start working.. i don't know why but it works.

Maybe this helps someone else.

SQL Server function to return minimum date (January 1, 1753)

Here is a fast and highly readable way to get the min date value

Note: This is a Deterministic Function, so to improve performance further we might as well apply WITH SCHEMABINDING to the return value.

Create a function

CREATE FUNCTION MinDate()
RETURNS DATETIME WITH SCHEMABINDING
AS
BEGIN
    RETURN CONVERT(DATETIME, -53690)

END

Call the function

dbo.MinDate()

Example 1

PRINT dbo.MinDate()

Example 2

PRINT 'The minimimum date allowed in an SQL database is ' + CONVERT(VARCHAR(MAX), dbo.MinDate())

Example 3

SELECT * FROM Table WHERE DateValue > dbo.MinDate()

Example 4

SELECT dbo.MinDate() AS MinDate

Example 5

DECLARE @MinDate AS DATETIME = dbo.MinDate()

SELECT @MinDate AS MinDate

How to use multiprocessing pool.map with multiple arguments?

is there a variant of pool.map which support multiple arguments?

Python 3.3 includes pool.starmap() method:

#!/usr/bin/env python3
from functools import partial
from itertools import repeat
from multiprocessing import Pool, freeze_support

def func(a, b):
    return a + b

def main():
    a_args = [1,2,3]
    second_arg = 1
    with Pool() as pool:
        L = pool.starmap(func, [(1, 1), (2, 1), (3, 1)])
        M = pool.starmap(func, zip(a_args, repeat(second_arg)))
        N = pool.map(partial(func, b=second_arg), a_args)
        assert L == M == N

if __name__=="__main__":
    freeze_support()
    main()

For older versions:

#!/usr/bin/env python2
import itertools
from multiprocessing import Pool, freeze_support

def func(a, b):
    print a, b

def func_star(a_b):
    """Convert `f([1,2])` to `f(1,2)` call."""
    return func(*a_b)

def main():
    pool = Pool()
    a_args = [1,2,3]
    second_arg = 1
    pool.map(func_star, itertools.izip(a_args, itertools.repeat(second_arg)))

if __name__=="__main__":
    freeze_support()
    main()

Output

1 1
2 1
3 1

Notice how itertools.izip() and itertools.repeat() are used here.

Due to the bug mentioned by @unutbu you can't use functools.partial() or similar capabilities on Python 2.6, so the simple wrapper function func_star() should be defined explicitly. See also the workaround suggested by uptimebox.

How to take a screenshot programmatically on iOS

In Swift you can use following code.

if UIScreen.mainScreen().respondsToSelector(Selector("scale")) {
    UIGraphicsBeginImageContextWithOptions(self.window!.bounds.size, false, UIScreen.mainScreen().scale)
}
else{
    UIGraphicsBeginImageContext(self.window!.bounds.size)
}
self.window?.layer.renderInContext(UIGraphicsGetCurrentContext())
var image : UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

As everyone has mentioned http.server module is equivalent to python -m SimpleHTTPServer.
But as a warning from https://docs.python.org/3/library/http.server.html#module-http.server

Warning: http.server is not recommended for production. It only implements basic security checks.

Usage

http.server can also be invoked directly using the -m switch of the interpreter.

python -m http.server

The above command will run a server by default on port number 8000. You can also give the port number explicitly while running the server

python -m http.server 9000

The above command will run an HTTP server on port 9000 instead of 8000.

By default, server binds itself to all interfaces. The option -b/--bind specifies a specific address to which it should bind. Both IPv4 and IPv6 addresses are supported. For example, the following command causes the server to bind to localhost only:

python -m http.server 8000 --bind 127.0.0.1

or

python -m http.server 8000 -b 127.0.0.1

Python 3.8 version also supports IPv6 in the bind argument.

Directory Binding

By default, server uses the current directory. The option -d/--directory specifies a directory to which it should serve the files. For example, the following command uses a specific directory:

python -m http.server --directory /tmp/

Directory binding is introduced in python 3.7

getFilesDir() vs Environment.getDataDirectory()

Environment returns user data directory. And getFilesDir returns application data directory.

Python locale error: unsupported locale setting

if I understand correctly, the main source of error here is the exact syntax of the locale-name. Especially as it seems to differ between distributions. I've seen mentioned here in different answers/comments:

de_DE.utf8
de_DE.UTF-8

Even though this is obviously the same for a human being, the same does not hold for your standard deterministic algorithm.

So you will probably do something along the lines of:

DESIRED_LOCALE=de
DESIRED_LOCALE_COUNTRY=DE
DESIRED_CODEPAGE_RE=\.[Uu][Tt][Ff].?8
if [ $(locale -a | grep -cE "${DESIRED_LOCALE}_${DESIRED_LOCALE_COUNTRY}${DESIRED_CODEPAGE_RE}") -eq 1 ]
then
    export LC_ALL=$(locale -a | grep -m1 -E "${DESIRED_LOCALE}_${DESIRED_LOCALE_COUNTRY}${DESIRED_CODEPAGE_RE}")
    export LANG=$LC_ALL
else
    echo "Not exactly one desired locale definition found: $(locale -a | grep -E "${DESIRED_LOCALE}_${DESIRED_LOCALE_COUNTRY}${DESIRED_CODEPAGE_RE}")" >&2
fi

GitLab remote: HTTP Basic: Access denied and fatal Authentication

I beleive I'm little late here. But I think this would help the new peeps!

My Errors were: remote: HTTP Basic: Access denied

remote: You must use a personal access token with 'read_repository' or 'write_repository' scope for Git over HTTP.

remote: You can generate one at https://gitlab.com/profile/personal_access_tokens

fatal: Authentication failed for 'https://gitlab.com/PROFILE_NAME/REPO_NAME.git/'

I'm on Ubuntu but this worked for me:

  1. Goto https://gitlab.com/profile/personal_access_tokens
  2. Create new token and mark check to all.
  3. Copy your token
  4. Now go to your Terminal and paste it like this.

git clone https://oauth2:[email protected]/PROFILE_NAME/REPO_NAME.git/

How can I pass a list as a command-line argument with argparse?

You can parse the list as a string and use of the eval builtin function to read it as a list. In this case, you will have to put single quotes into double quote (or the way around) in order to ensure successful string parse.

# declare the list arg as a string
parser.add_argument('-l', '--list', type=str)

# parse
args = parser.parse()

# turn the 'list' string argument into a list object
args.list = eval(args.list)
print(list)
print(type(list))

Testing:

python list_arg.py --list "[1, 2, 3]"

[1, 2, 3]
<class 'list'>

I want to multiply two columns in a pandas DataFrame and add the result into a new column

If we're willing to sacrifice the succinctness of Hayden's solution, one could also do something like this:

In [22]: orders_df['C'] = orders_df.Action.apply(
               lambda x: (1 if x == 'Sell' else -1))

In [23]: orders_df   # New column C represents the sign of the transaction
Out[23]:
   Prices  Amount Action  C
0       3      57   Sell  1
1      89      42   Sell  1
2      45      70    Buy -1
3       6      43   Sell  1
4      60      47   Sell  1
5      19      16    Buy -1
6      56      89   Sell  1
7       3      28    Buy -1
8      56      69   Sell  1
9      90      49    Buy -1

Now we have eliminated the need for the if statement. Using DataFrame.apply(), we also do away with the for loop. As Hayden noted, vectorized operations are always faster.

In [24]: orders_df['Value'] = orders_df.Prices * orders_df.Amount * orders_df.C

In [25]: orders_df   # The resulting dataframe
Out[25]:
   Prices  Amount Action  C  Value
0       3      57   Sell  1    171
1      89      42   Sell  1   3738
2      45      70    Buy -1  -3150
3       6      43   Sell  1    258
4      60      47   Sell  1   2820
5      19      16    Buy -1   -304
6      56      89   Sell  1   4984
7       3      28    Buy -1    -84
8      56      69   Sell  1   3864
9      90      49    Buy -1  -4410

This solution takes two lines of code instead of one, but is a bit easier to read. I suspect that the computational costs are similar as well.

Pycharm/Python OpenCV and CV2 install error

When I was facing this issue I used to install OpenCV in pycharm installed package panel where we can find under the settings tab. Search "OpenCV-python" and install it in the installed package panel of right interpreter.

moment.js 24h format

Use this to get time from 00:00:00 to 23:59:59

If your time is having date from it by using 'LT or LTS'

var now = moment('23:59:59','HHmmss').format("HH:mm:ss")

** https://jsfiddle.net/a7qLhsgz/**

Why can I not create a wheel in python?

I tried everything said here without any luck, but found a workaround. After running this command (and failing) : bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg

Go to the temporary directory the tool made (given in the output of the last command), then execute python setup.py bdist_wheel. The .whl file is in the dist folder.

Throwing multiple exceptions in a method of an interface in java

You can declare as many Exceptions as you want for your interface method. But the class you gave in your question is invalid. It should read

public class MyClass implements MyInterface {
  public void find(int x) throws A_Exception, B_Exception{
    ----
    ----
    ---
  }
}

Then an interface would look like this

public interface MyInterface {
  void find(int x) throws A_Exception, B_Exception;
}

AttributeError: Module Pip has no attribute 'main'

Try this command.

python -m pip install --user pip==9.0.1

Why do I get an UnsupportedOperationException when trying to remove an element from a List?

Following is snippet of code from Arrays

public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }

    /**
     * @serial include
     */
    private static class ArrayList<E> extends AbstractList<E>
        implements RandomAccess, java.io.Serializable
    {
        private static final long serialVersionUID = -2764017481108945198L;
        private final E[] a;

so what happens is that when asList method is called then it returns list of its own private static class version which does not override add funcion from AbstractList to store element in array. So by default add method in abstract list throws exception.

So it is not regular array list.

How to count instances of character in SQL Column

The easiest way is by using Oracle function:

SELECT REGEXP_COUNT(COLUMN_NAME,'CONDITION') FROM TABLE_NAME

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

A little late but I did run across this thread when trying out solutions for myself. Assuming you're using modern browsers nowadays, I came up with a solution using CSS calc() to help guarantee widths met up.

_x000D_
_x000D_
.table-fixed-left table,_x000D_
.table-fixed-right table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
.table-fixed-right td,_x000D_
.table-fixed-right th,_x000D_
.table-fixed-left td,_x000D_
.table-fixed-left th {_x000D_
  border: 1px solid #ddd;_x000D_
  padding: 5px 5px;_x000D_
}_x000D_
.table-fixed-left {_x000D_
  width: 120px;_x000D_
  float: left;_x000D_
  position: fixed;_x000D_
  overflow-x: scroll;_x000D_
  white-space: nowrap;_x000D_
  text-align: left;_x000D_
  border: 1px solid #ddd;_x000D_
  z-index: 2;_x000D_
}_x000D_
.table-fixed-right {_x000D_
  width: calc(100% - 145px);_x000D_
  right: 15px;_x000D_
  position: fixed;_x000D_
  overflow-x: scroll;_x000D_
  border: 1px solid #ddd;_x000D_
  white-space: nowrap;_x000D_
}_x000D_
.table-fixed-right td,_x000D_
.table-fixed-right th {_x000D_
  padding: 5px 10px;_x000D_
}
_x000D_
<div class="table-fixed-left">_x000D_
  <table>_x000D_
    <tr>_x000D_
      <th>Normal Header</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <th>Header with extra line_x000D_
        <br/>&nbsp;</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <th>Normal Header</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <th>Normal with extra line_x000D_
        <br/>&nbsp;</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <th>Normal Header</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <th>Normal Header</th>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>_x000D_
<div class="table-fixed-right">_x000D_
  <table>_x000D_
    <tr>_x000D_
      <th>Header</th>_x000D_
      <th>Another header</th>_x000D_
      <th>Header</th>_x000D_
      <th>Header really really really really long</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Info Long</td>_x000D_
      <td>Info_x000D_
        <br/>with second line</td>_x000D_
      <td>Info_x000D_
        <br/>with second line</td>_x000D_
      <td>Info Long</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Info Long</td>_x000D_
      <td>Info Long</td>_x000D_
      <td>Info Long</td>_x000D_
      <td>Info Long</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Info_x000D_
        <br/>with second line</td>_x000D_
      <td>Info_x000D_
        <br/>with second line</td>_x000D_
      <td>Info_x000D_
        <br/>with second line</td>_x000D_
      <td>Info</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Info</td>_x000D_
      <td>Info</td>_x000D_
      <td>Info</td>_x000D_
      <td>Info</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Info</td>_x000D_
      <td>Info</td>_x000D_
      <td>Info</td>_x000D_
      <td>Info</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hope this helps someone!

Passing references to pointers in C++

EDIT: I experimented some, and discovered thing are a bit subtler than I thought. Here's what I now think is an accurate answer.

&s is not an lvalue so you cannot create a reference to it unless the type of the reference is reference to const. So for example, you cannot do

string * &r = &s;

but you can do

string * const &r = &s;

If you put a similar declaration in the function header, it will work.

void myfunc(string * const &a) { ... }

There is another issue, namely, temporaries. The rule is that you can get a reference to a temporary only if it is const. So in this case one might argue that &s is a temporary, and so must be declared const in the function prototype. From a practical point of view it makes no difference in this case. (It's either an rvalue or a temporary. Either way, the same rule applies.) However, strictly speaking, I think it is not a temporary but an rvalue. I wonder if there is a way to distinguish between the two. (Perhaps it is simply defined that all temporaries are rvalues, and all non-lvalues are temporaries. I'm not an expert on the standard.)

That being said, your problem is probably at a higher level. Why do you want a reference to the address of s? If you want a reference to a pointer to s, you need to define a pointer as in

string *p = &s;
myfunc(p);

If you want a reference to s or a pointer to s, do the straightforward thing.

Multiple github accounts on the same computer?

another easier way is using multiple desktop apps, like what i am doing, using account A on Github desktop, while using account B on Github Kraken

How can I format date by locale in Java?

Yes, using DateFormat.getDateInstance(int style, Locale aLocale) This displays the current date in a locale-specific way.

So, for example:

DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, yourLocale);
String formattedDate = df.format(yourDate);

See the docs for the exact meaning of the style parameter (SHORT, MEDIUM, etc)

Chrome not rendering SVG referenced via <img> tag

In my case this problem persisted when I created and saved the svg using Photoshop. What helped, was opening the file using Illustrator and exporting the svg afterwards.

How do I download a file using VBA (without Internet Explorer)

Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" _
(ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, _
ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long

Sub Example()
    DownloadFile$ = "someFile.ext" 'here the name with extension
    URL$ = "http://some.web.address/" & DownloadFile 'Here is the web address
    LocalFilename$ = "C:\Some\Path" & DownloadFile !OR! CurrentProject.Path & "\" & DownloadFile 'here the drive and download directory
    MsgBox "Download Status : " & URLDownloadToFile(0, URL, LocalFilename, 0, 0) = 0
End Sub

Source

I found the above when looking for downloading from FTP with username and address in URL. Users supply information and then make the calls.

This was helpful because our organization has Kaspersky AV which blocks active FTP.exe, but not web connections. We were unable to develop in house with ftp.exe and this was our solution. Hope this helps other looking for info!

Excel VBA Macro: User Defined Type Not Defined

Your error is caused by these:

Dim oTable As Table, oRow As Row,

These types, Table and Row are not variable types native to Excel. You can resolve this in one of two ways:

  1. Include a reference to the Microsoft Word object model. Do this from Tools | References, then add reference to MS Word. While not strictly necessary, you may like to fully qualify the objects like Dim oTable as Word.Table, oRow as Word.Row. This is called early-binding. enter image description here
  2. Alternatively, to use late-binding method, you must declare the objects as generic Object type: Dim oTable as Object, oRow as Object. With this method, you do not need to add the reference to Word, but you also lose the intellisense assistance in the VBE.

I have not tested your code but I suspect ActiveDocument won't work in Excel with method #2, unless you properly scope it to an instance of a Word.Application object. I don't see that anywhere in the code you have provided. An example would be like:

Sub DeleteEmptyRows()
Dim wdApp as Object
Dim oTable As Object, As Object, _
TextInRow As Boolean, i As Long

Set wdApp = GetObject(,"Word.Application")

Application.ScreenUpdating = False

For Each oTable In wdApp.ActiveDocument.Tables

IndexError: too many indices for array

The message that you are getting is not for the default Exception of Python:

For a fresh python list, IndexError is thrown only on index not being in range (even docs say so).

>>> l = []
>>> l[1]
IndexError: list index out of range

If we try passing multiple items to list, or some other value, we get the TypeError:

>>> l[1, 2]
TypeError: list indices must be integers, not tuple

>>> l[float('NaN')]
TypeError: list indices must be integers, not float

However, here, you seem to be using matplotlib that internally uses numpy for handling arrays. On digging deeper through the codebase for numpy, we see:

static NPY_INLINE npy_intp
unpack_tuple(PyTupleObject *index, PyObject **result, npy_intp result_n)
{
    npy_intp n, i;
    n = PyTuple_GET_SIZE(index);
    if (n > result_n) {
        PyErr_SetString(PyExc_IndexError,
                        "too many indices for array");
        return -1;
    }
    for (i = 0; i < n; i++) {
        result[i] = PyTuple_GET_ITEM(index, i);
        Py_INCREF(result[i]);
    }
    return n;
}

where, the unpack method will throw an error if it the size of the index is greater than that of the results.

So, Unlike Python which raises a TypeError on incorrect Indexes, Numpy raises the IndexError because it supports multidimensional arrays.

Batch files: List all files in a directory with relative paths

@echo on>out.txt
@echo off
setlocal enabledelayedexpansion
set "parentfolder=%CD%"
for /r . %%g in (*.*) do (
  set "var=%%g"
  set var=!var:%parentfolder%=!
  echo !var! >> out.txt
)

null vs empty string in Oracle

This is because Oracle internally changes empty string to NULL values. Oracle simply won't let insert an empty string.

On the other hand, SQL Server would let you do what you are trying to achieve.

There are 2 workarounds here:

  1. Use another column that states whether the 'description' field is valid or not
  2. Use some dummy value for the 'description' field where you want it to store empty string. (i.e. set the field to be 'stackoverflowrocks' assuming your real data will never encounter such a description value)

Both are, of course, stupid workarounds :)

Filter by process/PID in Wireshark

On Windows there is an experimental build that does this, as described on the mailing list, Filter by local process name

C# DropDownList with a Dictionary as DataSource

If the DropDownList is declared in your aspx page and not in the codebehind, you can do it like this.

.aspx:

<asp:DropDownList ID="ddlStatus" runat="server" DataSource="<%# Statuses %>"
     DataValueField="Key" DataTextField="Value"></asp:DropDownList>

.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{
    ddlStatus.DataBind();
    // or use Page.DataBind() to bind everything
}

public Dictionary<int, string> Statuses
{
    get 
    {
        // do database/webservice lookup here to populate Dictionary
    }
};

What is Teredo Tunneling Pseudo-Interface?

Is to do with IPv6

All the gory details here: http://www.microsoft.com/technet/network/ipv6/teredo.mspx

Some people have had issues with it, and disabled it, but as a general rule, if it aint broke...

How can I disable a tab inside a TabControl?

You could register the "Selecting" event and cancel the navigation to the tab page:

private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
{
    if (e.TabPage == tabPage2)
        e.Cancel = true;
}

Another idea is to put all the controls on the tabpage in a Panel control and disable the panel! Smiley

You could also remove the tabpage from the tabControl1.TabPages collection. That would hide the tabpage.

Credits go to littleguru @ Channel 9.

What is the problem with shadowing names defined in outer scopes?

data = [4, 5, 6] # Your global variable

def print_data(data): # <-- Pass in a parameter called "data"
    print data  # <-- Note: You can access global variable inside your function, BUT for now, which is which? the parameter or the global variable? Confused, huh?

print_data(data)

Ruby value of a hash key?

How about this?

puts "ok" if hash_variable["key"] == "X"

You can access hash values with the [] operator

AngularJS check if form is valid in controller

Try this

in view:

<form name="formName" ng-submit="submitForm(formName)">
 <!-- fields -->
</form>

in controller:

$scope.submitForm = function(form){
  if(form.$valid) {
   // Code here if valid
  }
};

or

in view:

<form name="formName" ng-submit="submitForm(formName.$valid)">
  <!-- fields -->
</form>

in controller:

$scope.submitForm = function(formValid){
  if(formValid) {
    // Code here if valid
  }
};

How to catch a click event on a button?

Just declare a method,e.g:if ur button id is button1 then,

button1.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(Context, "Hello", Toast.LENGTH_SHORT).show();
        }
    });

If you want to make the imageview1 visible then in that method write:

imageview1.setVisibility(ImageView.VISIBLE);

Angular 6: saving data to local storage

First you should understand how localStorage works. you are doing wrong way to set/get values in local storage. Please read this for more information : How to Use Local Storage with JavaScript

How to use not contains() in xpath?

I need to select every production with a category that doesn't contain "Business"

Although I upvoted @Arran's answer as correct, I would also add this... Strictly interpreted, the OP's specification would be implemented as

//production[category[not(contains(., 'Business'))]]

rather than

//production[not(contains(category, 'Business'))]

The latter selects every production whose first category child doesn't contain "Business". The two XPath expressions will behave differently when a production has no category children, or more than one.

It doesn't make any difference in practice as long as every <production> has exactly one <category> child, as in your short example XML. Whether you can always count on that being true or not, depends on various factors, such as whether you have a schema that enforces that constraint. Personally, I would go for the more robust option, since it doesn't "cost" much... assuming your requirement as stated in the question is really correct (as opposed to e.g. 'select every production that doesn't have a category that contains "Business"').

Resizing SVG in html?

I have found it best to add viewBox and preserveAspectRatio attributes to my SVGs. The viewbox should describe the full width and height of the SVG in the form 0 0 w h:

<svg preserveAspectRatio="xMidYMid meet" viewBox="0 0 700 550"></svg>

Jenkins "Console Output" log location in filesystem

For very large output logs it could be difficult to open (network delay, scrolling). This is the solution I'm using to check big log files:

    https://${URL}/jenkins/job/${jobName}/${buildNumber}/

in the left column you see: View as plain text. Do a right mouse click on it and choose save links as. Now you can save your big log as .txt file. Open it with notepad++ and you can go through your logs easily without network delays during scrolling.

Delete terminal history in Linux

You can clear your bash history like this:

history -cw

How to generate all permutations of a list?

def permutations(head, tail=''):
    if len(head) == 0:
        print(tail)
    else:
        for i in range(len(head)):
            permutations(head[:i] + head[i+1:], tail + head[i])

called as:

permutations('abc')

Data binding in React

With the new feature called Hooks from the React team which makes functional components to handle state changes.. your question can be solved easily

import React, { useState, useEffect } from 'react'
import ReactDOM from 'react-dom';

const Demo = props =>{
    const [text, setText] = useState("there");
    return props.logic(text, setText);
};

const App = () => {
    const [text, setText] = useState("hello");

    const componentDidMount = () =>{
        setText("hey");
    };
    useEffect(componentDidMount, []);

    const logic = (word, setWord) => (
        <div>
            <h1>{word}</h1>
            <input type="text" value={word} onChange={e => setWord(e.target.value)}></input>
            <h1>{text}</h1>
            <input type="text" value={text} onChange={e => setText(e.target.value)}></input>
        </div>
    );
    return <Demo logic={logic} />;
};

ReactDOM.render(<App />,document.getElementById("root"));

Specified cast is not valid.. how to resolve this

Use Convert.ToDouble(value) rather than (double)value. It takes an object and supports all of the types you asked for! :)

Also, your method is always returning a string in the code above; I'd recommend having the method indicate so, and give it a more obvious name (public string FormatLargeNumber(object value))

CSS3 gradient background set on body doesn't stretch but instead repeats?

Dirty; maybe could you just add a min-height: 100%; to the html, and body tags? That or at least set a default background color that is the end gradient color as well.

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

Why does the Visual Studio editor show dots in blank spaces?

Looks like you have the view white space option enabled. Go to Edit -> Advanced -> and uncheck "View Whitespace"

Can't bind to 'formGroup' since it isn't a known property of 'form'

Ok after some digging I found a solution for "Can't bind to 'formGroup' since it isn't a known property of 'form'."

For my case, I've been using multiple modules files, i added ReactiveFormsModule in app.module.ts

 import { FormsModule, ReactiveFormsModule } from '@angular/forms';`

@NgModule({
  declarations: [
    AppComponent,
  ]
  imports: [
    FormsModule,
    ReactiveFormsModule,
    AuthorModule,
],
...

But this wasn't working when I use a [formGroup] directive from a component added in another module, e.g. using [formGroup] in author.component.ts which is subscribed in author.module.ts file:

import { NgModule }       from '@angular/core';
import { CommonModule }   from '@angular/common';
import { AuthorComponent } from './author.component';

@NgModule({
  imports: [
    CommonModule,
  ],
  declarations: [
    AuthorComponent,
  ],
  providers: [...]
})

export class AuthorModule {}

I thought if i added ReactiveFormsModule in app.module.ts, by default ReactiveFormsModule would be inherited by all its children modules like author.module in this case... (wrong!). I needed to import ReactiveFormsModule in author.module.ts in order to make all directives to work:

...
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
...

@NgModule({
  imports: [
    ...,
    FormsModule,    //added here too
    ReactiveFormsModule //added here too
  ],
  declarations: [...],
  providers: [...]
})

export class AuthorModule {}

So, if you are using submodules, make sure to import ReactiveFormsModule in each submodule file. Hope this helps anyone.

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

use this filter:

(dns.flags.response == 0) and (ip.src == 159.25.78.7)

what this query does is it only gives dns queries originated from your ip

How to generate classes from wsdl using Maven and wsimport?

The key here is keep option of wsimport. And it is configured using element in About keep from the wsimport documentation :

-keep                     keep generated files

Parse usable Street Address, City, State, Zip from a string

Try www.address-parser.com. We use their web service, which you can test online

Remove specific characters from a string in Javascript

Regexp solution:

ref = ref.replace(/^F0/, "");

plain solution:

if (ref.substr(0, 2) == "F0")
     ref = ref.substr(2);

undefined reference to WinMain@16 (codeblocks)

Well I know this answer is not an experienced programmer's approach and of an Old It consultant , but it worked for me .

the answer is "TRY TURNING IT ON AND OFF" . restart codeblocks and it works well reminds me of the 2006 comedy show It Crowd .

What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?

From the Java JDBC tutorial:

In previous versions of JDBC, to obtain a connection, you first had to initialize your JDBC driver by calling the method Class.forName. Any JDBC 4.0 drivers that are found in your class path are automatically loaded. (However, you must manually load any drivers prior to JDBC 4.0 with the method Class.forName.)

So, if you're using the Oracle 11g (11.1) driver with Java 1.6, you don't need to call Class.forName. Otherwise, you need to call it to initialise the driver.

UL list style not applying

and you can also give a left-margin if the reset.css you are using make all margin null : that means :

li {
list-style: disc outside none;
display: list-item;
margin-left: 1em;
}

Assuming you apply this css after the reset, it should work !

Matthieu Ricaud

MySQL - Get row number on select

You can use MySQL variables to do it. Something like this should work (though, it consists of two queries).

SELECT 0 INTO @x;

SELECT itemID, 
       COUNT(*) AS ordercount, 
       (@x:=@x+1) AS rownumber 
FROM orders 
GROUP BY itemID 
ORDER BY ordercount DESC; 

Bad Request - Invalid Hostname IIS7

So, I solved this by going to my website in IIS Manager and changing the host name in site bindings from localhost to *. Started working immediately.

Site Bindings in IIS

Codeigniter - no input file specified

Godaddy hosting it seems fixed on .htaccess, myself it is working

RewriteRule ^(.*)$ index.php/$1 [L]

to

RewriteRule ^(.*)$ index.php?/$1 [QSA,L]

Threading pool similar to the multiprocessing Pool?

I just found out that there actually is a thread-based Pool interface in the multiprocessing module, however it is hidden somewhat and not properly documented.

It can be imported via

from multiprocessing.pool import ThreadPool

It is implemented using a dummy Process class wrapping a python thread. This thread-based Process class can be found in multiprocessing.dummy which is mentioned briefly in the docs. This dummy module supposedly provides the whole multiprocessing interface based on threads.

HttpServletRequest to complete URL

Combining the results of getRequestURL() and getQueryString() should get you the desired result.

Is there any difference between a GUID and a UUID?

GUID is Microsoft's implementation of the UUID standard.

Per Wikipedia:

The term GUID usually refers to Microsoft's implementation of the Universally Unique Identifier (UUID) standard.

An updated quote from that same Wikipedia article:

RFC 4122 itself states that UUIDs "are also known as GUIDs". All this suggests that "GUID", while originally referring to a variant of UUID used by Microsoft, has become simply an alternative name for UUID…

Sending a JSON HTTP POST request from Android

Posting parameters Using POST:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

How do I "select Android SDK" in Android Studio?

If your android SDK path is given and still you facing this issue then it might because your android studio not synced well, even you have clicked on "Sync now" link.

So for re sync it go to app gradle file and make any change or just give a space and now sync again. It will work perfectly.

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

I know why, you are using the file name "ping" and you are using the code "ping", it just keeps trying to run itself because its selected directory in where that file is, if you want it to actually ping, put this before the ping command: "cd C:\Windows\system32", the actual file that pings the server is in there!

Android SQLite Example

The DBHelper class is what handles the opening and closing of sqlite databases as well sa creation and updating, and a decent article on how it all works is here. When I started android it was very useful (however I've been objective-c lately, and forgotten most of it to be any use.

Automatically scroll down chat div

after append in JQuery,just add this line

<script>
    $("#messages").animate({ scrollTop: 20000000 }, "slow");
</script>

splitting a number into the integer and decimal parts

Use math.modf:

import math
x = 1234.5678
math.modf(x) # (0.5678000000000338, 1234.0)

How do you perform a left outer join using linq extension methods

Since this seems to be the de facto SO question for left outer joins using the method (extension) syntax, I thought I would add an alternative to the currently selected answer that (in my experience at least) has been more commonly what I'm after

// Option 1: Expecting either 0 or 1 matches from the "Right"
// table (Bars in this case):
var qry = Foos.GroupJoin(
          Bars,
          foo => foo.Foo_Id,
          bar => bar.Foo_Id,
          (f,bs) => new { Foo = f, Bar = bs.SingleOrDefault() });

// Option 2: Expecting either 0 or more matches from the "Right" table
// (courtesy of currently selected answer):
var qry = Foos.GroupJoin(
                  Bars, 
                  foo => foo.Foo_Id,
                  bar => bar.Foo_Id,
                  (f,bs) => new { Foo = f, Bars = bs })
              .SelectMany(
                  fooBars => fooBars.Bars.DefaultIfEmpty(),
                  (x,y) => new { Foo = x.Foo, Bar = y });

To display the difference using a simple data set (assuming we're joining on the values themselves):

List<int> tableA = new List<int> { 1, 2, 3 };
List<int?> tableB = new List<int?> { 3, 4, 5 };

// Result using both Option 1 and 2. Option 1 would be a better choice
// if we didn't expect multiple matches in tableB.
{ A = 1, B = null }
{ A = 2, B = null }
{ A = 3, B = 3    }

List<int> tableA = new List<int> { 1, 2, 3 };
List<int?> tableB = new List<int?> { 3, 3, 4 };

// Result using Option 1 would be that an exception gets thrown on
// SingleOrDefault(), but if we use FirstOrDefault() instead to illustrate:
{ A = 1, B = null }
{ A = 2, B = null }
{ A = 3, B = 3    } // Misleading, we had multiple matches.
                    // Which 3 should get selected (not arbitrarily the first)?.

// Result using Option 2:
{ A = 1, B = null }
{ A = 2, B = null }
{ A = 3, B = 3    }
{ A = 3, B = 3    }    

Option 2 is true to the typical left outer join definition, but as I mentioned earlier is often unnecessarily complex depending on the data set.

How to go to each directory and execute a command?

  #!/bin.bash
for folder_to_go in $(find . -mindepth 1 -maxdepth 1 -type d \( -name "*" \) ) ; 
                                    # you can add pattern insted of * , here it goes to any folder 
                                    #-mindepth / maxdepth 1 means one folder depth   
do
cd $folder_to_go
  echo $folder_to_go "########################################## "
  
  whatever you want to do is here

cd ../ # if maxdepth/mindepath = 2,  cd ../../
done

#you can try adding many internal for loops with many patterns, this will sneak anywhere you want

How to simulate a button click using code?

Android's callOnClick() (added in API 15) can sometimes be a better choice in my experience than performClick(). If a user has selection sounds enabled, then performClick() could cause the user to hear two continuous selection sounds that are somewhat layered on top of each other which can be jarring. (One selection sound for the user's first button click, and then another for the other button's OnClickListener that you're calling via code.)

remove kernel on jupyter notebook

In jupyter notebook run:

!echo y | jupyter kernelspec uninstall unwanted-kernel 

In anaconda prompt run:

jupyter kernelspec uninstall unwanted-kernel

Calculating Page Load Time In JavaScript

The answer mentioned by @HaNdTriX is a great, but we are not sure if DOM is completely loaded in the below code:

var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart; 

This works perfectly when used with onload as:

window.onload = function () {
    var loadTime = window.performance.timing.domContentLoadedEventEnd-window.performance.timing.navigationStart; 
    console.log('Page load time is '+ loadTime);
}

Edit 1: Added some context to answer

Note: loadTime is in milliseconds, you can divide by 1000 to get seconds as mentioned by @nycynik

How to Determine the Screen Height and Width in Flutter

MediaQuery.of(context).size.width and MediaQuery.of(context).size.height works great, but every time need to write expressions like width/20 to set specific height width.

I've created a new application on flutter, and I've had problems with the screen sizes when switching between different devices.

Yes, flutter_screenutil plugin available for adapting screen and font size. Let your UI display a reasonable layout on different screen sizes!

Usage:

Add dependency:

Please check the latest version before installation.

dependencies:
  flutter:
    sdk: flutter
  # add flutter_ScreenUtil
  flutter_screenutil: ^0.4.2

Add the following imports to your Dart code:

import 'package:flutter_screenutil/flutter_screenutil.dart';

Initialize and set the fit size and font size to scale according to the system's "font size" accessibility option

//fill in the screen size of the device in the design

//default value : width : 1080px , height:1920px , allowFontScaling:false
ScreenUtil.instance = ScreenUtil()..init(context);

//If the design is based on the size of the iPhone6 ??(iPhone6 ??750*1334)
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

//If you wang to set the font size is scaled according to the system's "font size" assist option
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334, allowFontScaling: true)..init(context);

Use:

//for example:
//rectangle
Container(
           width: ScreenUtil().setWidth(375),
           height: ScreenUtil().setHeight(200),
           ...
            ),

////If you want to display a square:
Container(
           width: ScreenUtil().setWidth(300),
           height: ScreenUtil().setWidth(300),
            ),

Please refer updated documentation for more details

Note: I tested and using this plugin, which really works great with all devices including iPad

Hope this will helps someone

C++ [Error] no matching function for call to

You are trying to call DeckOfCards::shuffle with a deckOfCards parameter:

deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck); // shuffle the cards in the deck

But the method takes a vector<Card>&:

void deckOfCards::shuffle(vector<Card>& deck)

The compiler error messages are quite clear on this. I'll paraphrase the compiler as it talks to you.

Error:

[Error] no matching function for call to 'deckOfCards::shuffle(deckOfCards&)'

Paraphrased:

Hey, pal. You're trying to call a function called shuffle which apparently takes a single parameter of type reference-to-deckOfCards, but there is no such function.

Error:

[Note] candidate is:

In file included from main.cpp

[Note] void deckOfCards::shuffle(std::vector&)

Paraphrased:

I mean, maybe you meant this other function called shuffle, but that one takes a reference-tovector<something>.

Error:

[Note] no known conversion for argument 1 from 'deckOfCards' to 'std::vector&'

Which I'd be happy to call if I knew how to convert from a deckOfCards to a vector; but I don't. So I won't.

JavaScript operator similar to SQL "like"

You can use regular expressions in Javascript to do pattern matching of strings.

For example:

var s = "hello world!";
if (s.match(/hello.*/)) {
  // do something
}

The match() test is much like WHERE s LIKE 'hello%' in SQL.

MySQL SELECT query string matching

You can use regular expressions like this:

SELECT * FROM pet WHERE name REGEXP 'Bob|Smith'; 

Can enums be subclassed to add new elements?

The recommended solution to this is the extensible enum pattern.

This involves creating an interface and using that where you currently use the enum. Then make the enum implement the interface. You can add more constants by making that new enum also extend the interface.

Fixed page header overlaps in-page anchors

Official Bootstrap Adopted Answer:

*[id]:before { 
  display: block; 
  content: " "; 
  margin-top: -75px; // Set the Appropriate Height
  height: 75px; // Set the Appropriate Height
  visibility: hidden; 
}

Credits

Merge

How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script?

Had just to ponder that same question (on Windows-side, but equally applicable to linux.) Suprisingly nobody mentioned a very much automated way of doing CRLF<->LF conversion for text-files using good old zip -ll option (Info-ZIP):

zip -ll textfiles-lf.zip files-with-crlf-eol.*
unzip textfiles-lf.zip 

NOTE: this would create a zip file preserving the original file names but converting the line endings to LF. Then unzip would extract the files as zip'ed, that is with their original names (but with LF-endings), thus prompting to overwrite the local original files if any.

Relevant excerpt from the zip --help:

zip --help
...
-l   convert LF to CR LF (-ll CR LF to LF)

How to use Python's "easy_install" on Windows ... it's not so easy

For one thing, it says you already have that module installed. If you need to upgrade it, you should do something like this:

easy_install -U packageName

Of course, easy_install doesn't work very well if the package has some C headers that need to be compiled and you don't have the right version of Visual Studio installed. You might try using pip or distribute instead of easy_install and see if they work better.

How to remove line breaks (no characters!) from the string?

Ben's solution is acceptable, but str_replace() is by far faster than preg_replace()

$buffer = str_replace(array("\r", "\n"), '', $buffer);

Using less CPU power, reduces the world carbon dioxide emissions.

Git vs Team Foundation Server

The whole Distributed thing of Git is really really great. it gives a few features Shelvesets don't have (in the current product) such as local rollback and commit options (such as Eclipse's localhistory feature). You could alleviate this using developer branches, but lets be honest, many developers don't like branching and merging one bit. I've been asked to turn on the old style "exclusive checkout" feature in TFS a few times too often (and denied it each and every time).

I think many large enterprises are quite scared to allow a dev to just bring the whole history into a local workspace and take it with them (to a new employer for example)... Stealing a snapshot is bad, but taking away a whole history is even more troublesome. (Not that you couldn't get a full history from TFS of you wanted it)...

It's mentioned that it's a great way to backup, which is great for open source again where the original maintainer might stop to care and removes his version, but for a enterprise plan this again falls short for many enterprises as there is no clear assignment of responsibility to keep backups. And it would be hard to figure out which version to use if the main 'project' vanishes somehow. Which would tend to appoint one repository as leading/central.

What I like most about Git is the Push/Pull option, where you can easily contribute code to a project without the need to have commit rights. I guess you could use very limited users and shelvesets in TFS to mimic this, but it isn't as powerful as the Git option. Branching across team projects might work as well, but from an administrative perspective it's not really feasible for many organisations as adding team projects adds a lot of administartive overhead.

I'd also like to add to the things mentioned in the non source control area. Features such as Work Item Tracking, Reporting and Build Automation (including lab management) greatly benefit from a central leading repository. These become a lot harder when you use a pure distributed model, unless you make one of the nodes leading (and thus go back to a less distributed model).

With TFS Basic coming with TFS 11, it might not be far off to expect a distributed TFS which allows you to sync your local TFS basic to a central TFS in the TFS 12+ era. I'll put my vote for that down in the uservoice!

JS jQuery - check if value is in array

Alternate solution of the values check

//Duplicate Title Entry 
    $.each(ar , function (i, val) {
        if ( jQuery("input:first").val()== val) alert('VALUE FOUND'+Valuecheck);
  });

What is the meaning of "operator bool() const"

I'd like to give more codes to make it clear.

struct A
{
    operator bool() const { return true; }
};

struct B
{
    explicit operator bool() const { return true; }
};

int main()
{
    A a1;
    if (a1) cout << "true" << endl; // OK: A::operator bool()
    bool na1 = a1; // OK: copy-initialization selects A::operator bool()
    bool na2 = static_cast<bool>(a1); // OK: static_cast performs direct-initialization

    B b1;     
    if (b1) cout << "true" << endl; // OK: B::operator bool()
    // bool nb1 = b1; // error: copy-initialization does not consider B::operator bool()
    bool nb2 = static_cast<bool>(b1); // OK: static_cast performs direct-initialization
}

R : how to simply repeat a command?

It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.

If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate and colMeans, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.

However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for loop.

> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 > 

So in your case, if you just wanted to print the mean of your Tandem object 5 times:

for (ii in 1:5) {     Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL)     TandemMean <- mean(Tandem)     print(TandemMean) } 

As mentioned above, replicate is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.

set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) {     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) }  tandem[1] tandem[100] tandem[20:25] 

...creates this output:

> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { +     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } >  > tandem[1] [[1]] [1] 1.511923  > tandem[100] [[1]] [1] 1.496777  > tandem[20:25] [[1]] [1] 1.500669  [[2]] [1] 1.487552  [[3]] [1] 1.503409  [[4]] [1] 1.501362  [[5]] [1] 1.499728  [[6]] [1] 1.492798  >  

How can I make Bootstrap 4 columns all the same height?

You just have to use class="row-eq-height" with your class="row" to get equal height columns for previous bootstrap versions.

but with bootstrap 4 this comes natively.

check this link --http://getbootstrap.com.vn/examples/equal-height-columns/

Service will not start: error 1067: the process terminated unexpectedly

In my case the error 1067 was caused with a specific version of Tomcat 7.0.96 32-bit in combination with AdoptOpenJDK. Spent two hours on it, un-installing, re-installing and trying different Java settings but Tomcat would not start. See... ASF Bugzilla – Bug 63625 seems to point at the issue though they refer to seeing a different error.

I tried 7.0.99 32-bit and it started straight away with the same AdoptOpenJDK 32-bit binary install.

Reading and writing binary file

sizeof(buffer) is the size of a pointer on your last line NOT the actual size of the buffer. You need to use "length" that you already established instead

Bash command to sum a column of numbers

I like the chosen answer. However, it tends to be slower than awk since 2 tools are needed to do the job.

$ wc -l file
49999998 file

$ time paste -sd+ file | bc
1448700364

real    1m36.960s
user    1m24.515s
sys     0m1.772s

$ time awk '{s+=$1}END{print s}' file
1448700364

real    0m45.476s
user    0m40.756s
sys     0m0.287s

How to remove whitespace from a string in typescript?

Problem

The trim() method removes whitespace from both sides of a string.

Source

Solution

You can use a Javascript replace method to remove white space like

"hello world".replace(/\s/g, "");

Example

_x000D_
_x000D_
var out = "hello world".replace(/\s/g, "");_x000D_
console.log(out);
_x000D_
_x000D_
_x000D_

CSS - make div's inherit a height

As already mentioned this can't be done with floats, they can't inherit heights, they're unaware of their siblings so for example the side two floats don't know the height of the centre content, so they can't inherit from anything.

Usually inherited height has to come from either an element which has an explicit height or if height: 100%; has been passed down through the display tree to it.. The only thing I'm aware of that passes on height which hasn't come from top of the "tree" is an absolutely positioned element - so you could for example absolutely position all the top right bottom left sides and corners (you know the height and width of the corners anyway) And as you seem to know the widths (of left/right borders) and heights of top/bottom) borders, and the widths of the top/bottom centers, are easy at 100% - the only thing that needs calculating is the height of the right/left sides if the content grows -

This you can do, even without using all four positioning co-ordinates which IE6 /7 doesn't support

I've put up an example based on what you gave, it does rely on a fixed width (your frame), but I think it could work with a flexible width too? the uses of this could be cool for those fancy image borders we can't get support for until multiple background images or image borders become fully available.. who knows, I was playing, so just sticking it out there!

proof of concept example is here

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

In WCF serive project this issue may be due to Reference of System.Web.Mvc.dll 's different version or may be any other DLL's different version issue. So this may be compatibility issue of DLL's different version

When I use

System.Web.Mvc.dll version 5.2.2.0 -> it thorows the Error The content type text/html; charset=utf-8 of the response message

but when I use

System.Web.Mvc.dll version 4.0.0.0 or lower -> That's works fine in my project and not have an Error.

I don't know the reason of this different version of DLL's issue but when I change the DLL's verison which is compatible with your WCF Project than it works fine.

This Error even generate when you add reference of other Project in your WCF Project and this reference project has different version of System.Web.Mvc DLL or could be any other DLL.

Options for initializing a string array

string[] str = new string[]{"1","2"};
string[] str = new string[4];

how does multiplication differ for NumPy Matrix vs Array classes?

the key things to know for operations on NumPy arrays versus operations on NumPy matrices are:

  • NumPy matrix is a subclass of NumPy array

  • NumPy array operations are element-wise (once broadcasting is accounted for)

  • NumPy matrix operations follow the ordinary rules of linear algebra

some code snippets to illustrate:

>>> from numpy import linalg as LA
>>> import numpy as NP

>>> a1 = NP.matrix("4 3 5; 6 7 8; 1 3 13; 7 21 9")
>>> a1
matrix([[ 4,  3,  5],
        [ 6,  7,  8],
        [ 1,  3, 13],
        [ 7, 21,  9]])

>>> a2 = NP.matrix("7 8 15; 5 3 11; 7 4 9; 6 15 4")
>>> a2
matrix([[ 7,  8, 15],
        [ 5,  3, 11],
        [ 7,  4,  9],
        [ 6, 15,  4]])

>>> a1.shape
(4, 3)

>>> a2.shape
(4, 3)

>>> a2t = a2.T
>>> a2t.shape
(3, 4)

>>> a1 * a2t         # same as NP.dot(a1, a2t) 
matrix([[127,  84,  85,  89],
        [218, 139, 142, 173],
        [226, 157, 136, 103],
        [352, 197, 214, 393]])

but this operations fails if these two NumPy matrices are converted to arrays:

>>> a1 = NP.array(a1)
>>> a2t = NP.array(a2t)

>>> a1 * a2t
Traceback (most recent call last):
   File "<pyshell#277>", line 1, in <module>
   a1 * a2t
   ValueError: operands could not be broadcast together with shapes (4,3) (3,4) 

though using the NP.dot syntax works with arrays; this operations works like matrix multiplication:

>> NP.dot(a1, a2t)
array([[127,  84,  85,  89],
       [218, 139, 142, 173],
       [226, 157, 136, 103],
       [352, 197, 214, 393]])

so do you ever need a NumPy matrix? ie, will a NumPy array suffice for linear algebra computation (provided you know the correct syntax, ie, NP.dot)?

the rule seems to be that if the arguments (arrays) have shapes (m x n) compatible with the a given linear algebra operation, then you are ok, otherwise, NumPy throws.

the only exception i have come across (there are likely others) is calculating matrix inverse.

below are snippets in which i have called a pure linear algebra operation (in fact, from Numpy's Linear Algebra module) and passed in a NumPy array

determinant of an array:

>>> m = NP.random.randint(0, 10, 16).reshape(4, 4)
>>> m
array([[6, 2, 5, 2],
       [8, 5, 1, 6],
       [5, 9, 7, 5],
       [0, 5, 6, 7]])

>>> type(m)
<type 'numpy.ndarray'>

>>> md = LA.det(m)
>>> md
1772.9999999999995

eigenvectors/eigenvalue pairs:

>>> LA.eig(m)
(array([ 19.703+0.j   ,   0.097+4.198j,   0.097-4.198j,   5.103+0.j   ]), 
array([[-0.374+0.j   , -0.091+0.278j, -0.091-0.278j, -0.574+0.j   ],
       [-0.446+0.j   ,  0.671+0.j   ,  0.671+0.j   , -0.084+0.j   ],
       [-0.654+0.j   , -0.239-0.476j, -0.239+0.476j, -0.181+0.j   ],
       [-0.484+0.j   , -0.387+0.178j, -0.387-0.178j,  0.794+0.j   ]]))

matrix norm:

>>>> LA.norm(m)
22.0227

qr factorization:

>>> LA.qr(a1)
(array([[ 0.5,  0.5,  0.5],
        [ 0.5,  0.5, -0.5],
        [ 0.5, -0.5,  0.5],
        [ 0.5, -0.5, -0.5]]), 
 array([[ 6.,  6.,  6.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]))

matrix rank:

>>> m = NP.random.rand(40).reshape(8, 5)
>>> m
array([[ 0.545,  0.459,  0.601,  0.34 ,  0.778],
       [ 0.799,  0.047,  0.699,  0.907,  0.381],
       [ 0.004,  0.136,  0.819,  0.647,  0.892],
       [ 0.062,  0.389,  0.183,  0.289,  0.809],
       [ 0.539,  0.213,  0.805,  0.61 ,  0.677],
       [ 0.269,  0.071,  0.377,  0.25 ,  0.692],
       [ 0.274,  0.206,  0.655,  0.062,  0.229],
       [ 0.397,  0.115,  0.083,  0.19 ,  0.701]])
>>> LA.matrix_rank(m)
5

matrix condition:

>>> a1 = NP.random.randint(1, 10, 12).reshape(4, 3)
>>> LA.cond(a1)
5.7093446189400954

inversion requires a NumPy matrix though:

>>> a1 = NP.matrix(a1)
>>> type(a1)
<class 'numpy.matrixlib.defmatrix.matrix'>

>>> a1.I
matrix([[ 0.028,  0.028,  0.028,  0.028],
        [ 0.028,  0.028,  0.028,  0.028],
        [ 0.028,  0.028,  0.028,  0.028]])
>>> a1 = NP.array(a1)
>>> a1.I

Traceback (most recent call last):
   File "<pyshell#230>", line 1, in <module>
   a1.I
   AttributeError: 'numpy.ndarray' object has no attribute 'I'

but the Moore-Penrose pseudoinverse seems to works just fine

>>> LA.pinv(m)
matrix([[ 0.314,  0.407, -1.008, -0.553,  0.131,  0.373,  0.217,  0.785],
        [ 1.393,  0.084, -0.605,  1.777, -0.054, -1.658,  0.069, -1.203],
        [-0.042, -0.355,  0.494, -0.729,  0.292,  0.252,  1.079, -0.432],
        [-0.18 ,  1.068,  0.396,  0.895, -0.003, -0.896, -1.115, -0.666],
        [-0.224, -0.479,  0.303, -0.079, -0.066,  0.872, -0.175,  0.901]])

>>> m = NP.array(m)

>>> LA.pinv(m)
array([[ 0.314,  0.407, -1.008, -0.553,  0.131,  0.373,  0.217,  0.785],
       [ 1.393,  0.084, -0.605,  1.777, -0.054, -1.658,  0.069, -1.203],
       [-0.042, -0.355,  0.494, -0.729,  0.292,  0.252,  1.079, -0.432],
       [-0.18 ,  1.068,  0.396,  0.895, -0.003, -0.896, -1.115, -0.666],
       [-0.224, -0.479,  0.303, -0.079, -0.066,  0.872, -0.175,  0.901]])

100% height minus header?

For "100% of the browser window", if you mean this literally, you should use fixed positioning. The top, bottom, right, and left properties are then used to offset the divs edges from the respective edges of the viewport:

#nav, #content{position:fixed;top:0px;bottom:0px;}
#nav{left:0px;right:235px;}
#content{left:235px;right:0px}

This will set up a screen with the left 235 pixels devoted to the nav, and the right rest of the screen to content.

Note, however, you won't be able to scroll the whole screen at once. Though you can set it to scroll either pane individually, by applying overflow:auto to either div.

Note also: fixed positioning is not supported in IE6 or earlier.

Firefox "ssl_error_no_cypher_overlap" error

Under advanced settings of firefox you should be able to set the encryption. By default SSL3.0 and TLS1.0 should be checked, so if firefox is trying to create ssl 3.0 connectons try unchecking the ssl 3.0s setting.

if that doesn't work, try searching the about:config page for "ssl2" My Firefox has settings with ssl2 set to false by default...

Text overflow ellipsis on two lines

Base on an answer I saw in stackoveflow, I created this LESS mixin (use this link to generate the CSS code):

.max-lines(@lines: 3; @line-height: 1.2) {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: @lines;
  line-height: @line-height;
  max-height: @line-height * @lines;
}

Usage

.example-1 {
    .max-lines();
}

.example-2 {
    .max-lines(3);
}

.example-3 {
    .max-lines(3, 1.5);
}

Highlight Bash/shell code in Markdown files

Using the knitr package:

```{r, engine='bash', code_block_name} ...

E.g.:

```{r, engine='bash', count_lines}
wc -l en_US.twitter.txt
```

You can also use:

  • engine='sh' for shell
  • engine='python' for Python
  • engine='perl', engine='haskell' and a bunch of other C-like languages and even gawk, AWK, etc.

Remove a CLASS for all child elements

You can also do like this :

  $("#table-filters li").parent().find('li').removeClass("active");

Windows CMD command for accessing usb?

firstly you have to change the drive, which is allocated to your usb.

follow these step to access your pendrive using CMD. 1- type drivename follow by the colon just like k: 2- type dir it will show all the files and directory in your usb 3- now you can access any file or directory of your usb.

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

I had the same issue and the following fixed my issue:

  1. Set the registry: npm config set registry "http://registry.npmjs.org/"
  2. Removed the entry in hosts file (using Windows 7) => C:\Windows\System32\drivers\etc\hosts

EditText, clear focus on touch outside

As @pcans suggested you can do this overriding dispatchTouchEvent(MotionEvent event) in your activity.

Here we get the touch coordinates and comparing them to view bounds. If touch is performed outside of a view then do something.

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        View yourView = (View) findViewById(R.id.view_id);
        if (yourView != null && yourView.getVisibility() == View.VISIBLE) {
            // touch coordinates
            int touchX = (int) event.getX();
            int touchY = (int) event.getY();
            // get your view coordinates
            final int[] viewLocation = new int[2];
            yourView.getLocationOnScreen(viewLocation);

            // The left coordinate of the view
            int viewX1 = viewLocation[0];
            // The right coordinate of the view
            int viewX2 = viewLocation[0] + yourView.getWidth();
            // The top coordinate of the view
            int viewY1 = viewLocation[1];
            // The bottom coordinate of the view
            int viewY2 = viewLocation[1] + yourView.getHeight();

            if (!((touchX >= viewX1 && touchX <= viewX2) && (touchY >= viewY1 && touchY <= viewY2))) {

                Do what you want...

                // If you don't want allow touch outside (for example, only hide keyboard or dismiss popup) 
                return false;
            }
        }
    }
    return super.dispatchTouchEvent(event);
}

Also it's not necessary to check view existance and visibility if your activity's layout doesn't change during runtime (e.g. you don't add fragments or replace/remove views from the layout). But if you want to close (or do something similiar) custom context menu (like in the Google Play Store when using overflow menu of the item) it's necessary to check view existance. Otherwise you will get a NullPointerException.

Serializing with Jackson (JSON) - getting "No serializer found"?

This error is also thrown if you forget to add the .build() method onto your return status.

return Response.status(Status.OK);         // fails
return Response.status(Status.OK).build(); // works

I got the following error without build() method:

org.codehaus.jackson.map.JsonMappingException: No serializer found for class com.sun.jersey.core.spi.factory.ResponseBuilderImpl

how to store Image as blob in Sqlite & how to retrieve it?

Here the code i used for my app

This code will take a image from url and convert is to a byte array

byte[] logoImage = getLogoImage(IMAGEURL);

private byte[] getLogoImage(String url){
     try {
             URL imageUrl = new URL(url);
             URLConnection ucon = imageUrl.openConnection();

             InputStream is = ucon.getInputStream();
             BufferedInputStream bis = new BufferedInputStream(is);

             ByteArrayBuffer baf = new ByteArrayBuffer(500);
             int current = 0;
             while ((current = bis.read()) != -1) {
                  baf.append((byte) current);
             }

             return baf.toByteArray();
     } catch (Exception e) {
          Log.d("ImageManager", "Error: " + e.toString());
     }
     return null;
}

To save the image to db i used this code.

 public void insertUser(){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String delSql = "DELETE FROM ACCOUNTS";
        SQLiteStatement delStmt = db.compileStatement(delSql);
        delStmt.execute();

        String sql = "INSERT INTO ACCOUNTS (account_id,account_name,account_image) VALUES(?,?,?)";
        SQLiteStatement insertStmt = db.compileStatement(sql);
        insertStmt.clearBindings();
        insertStmt.bindString(1, Integer.toString(this.accId));
        insertStmt.bindString(2,this.accName);
        insertStmt.bindBlob(3, this.accImage);
        insertStmt.executeInsert();
        db.close();
}

To retrieve the image back this is code i used.

public Account getCurrentAccount() {
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    String sql = "SELECT * FROM ACCOUNTS";
    Cursor cursor = db.rawQuery(sql, new String[] {});

    if(cursor.moveToFirst()){
        this.accId  = cursor.getInt(0);
        this.accName = cursor.getString(1);
        this.accImage = cursor.getBlob(2);
    }
    if (cursor != null && !cursor.isClosed()) {
        cursor.close();
    }
    db.close();
    if(cursor.getCount() == 0){
        return null;
    } else {
        return this;
    }
}

Finally to load this image to a imageview

logoImage.setImageBitmap(BitmapFactory.decodeByteArray( currentAccount.accImage, 
        0,currentAccount.accImage.length));

What is the difference between char * const and const char *?

The difference is that const char * is a pointer to a const char, while char * const is a constant pointer to a char.

The first, the value being pointed to can't be changed but the pointer can be. The second, the value being pointed at can change but the pointer can't (similar to a reference).

There is also a

const char * const

which is a constant pointer to a constant char (so nothing about it can be changed).

Note:

The following two forms are equivalent:

const char *

and

char const *

The exact reason for this is described in the C++ standard, but it's important to note and avoid the confusion. I know several coding standards that prefer:

char const

over

const char

(with or without pointer) so that the placement of the const element is the same as with a pointer const.

submit a form in a new tab

Since you've got this tagged jQuery, I'll assume you want something to stick in your success function?

success: function(data){
    window.open('http://www.mysite.com/', '_blank');
}

How do I create batch file to rename large number of files in a folder?

you can do this easily without manual editing or using fancy text editors. Here's a vbscript.

Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder="c:\test"
Set objFolder = objFS.GetFolder(strFolder)
For Each strFile In objFolder.Files
    If objFS.GetExtensionName(strFile) = "jpg" Then    
        strFileName = strFile.Name
        If InStr(strFileName,"Vacation2010") > 0 Then           
            strNewFileName = Replace(strFileName,"Vacation2010","December")
            strFile.Name = strNewFileName
        End If 
    End If  
Next 

save as myscript.vbs and

C:\test> cscript //nologo myscript.vbs 

How do you round to 1 decimal place in Javascript?

lodash has a round method:

_.round(4.006);
// => 4

_.round(4.006, 2);
// => 4.01

_.round(4060, -2);
// => 4100

Docs.

Source.

Calculate compass bearing / heading to location in Android

In this an arrow on compass shows the direction from your location to Kaaba(destination Location)

you can simple use bearingTo in this way.bearing to will give you the direct angle from your location to destination location

  Location userLoc=new Location("service Provider");
    //get longitudeM Latitude and altitude of current location with gps class and  set in userLoc
    userLoc.setLongitude(longitude); 
    userLoc.setLatitude(latitude);
    userLoc.setAltitude(altitude);

   Location destinationLoc = new Location("service Provider");
  destinationLoc.setLatitude(21.422487); //kaaba latitude setting
  destinationLoc.setLongitude(39.826206); //kaaba longitude setting
  float bearTo=userLoc.bearingTo(destinationLoc);

bearingTo will give you a range from -180 to 180, which will confuse things a bit. We will need to convert this value into a range from 0 to 360 to get the correct rotation.

This is a table of what we really want, comparing to what bearingTo gives us

+-----------+--------------+
| bearingTo | Real bearing |
+-----------+--------------+
| 0         | 0            |
+-----------+--------------+
| 90        | 90           |
+-----------+--------------+
| 180       | 180          |
+-----------+--------------+
| -90       | 270          |
+-----------+--------------+
| -135      | 225          |
+-----------+--------------+
| -180      | 180          |
+-----------+--------------+

so we have to add this code after bearTo

// If the bearTo is smaller than 0, add 360 to get the rotation clockwise.

  if (bearTo < 0) {
    bearTo = bearTo + 360;
    //bearTo = -100 + 360  = 260;
}

you need to implements the SensorEventListener and its functions(onSensorChanged,onAcurracyChabge) and write all the code inside onSensorChanged

Complete code is here for Direction of Qibla compass

 public class QiblaDirectionCompass extends Service implements SensorEventListener{
 public static ImageView image,arrow;

// record the compass picture angle turned
private float currentDegree = 0f;
private float currentDegreeNeedle = 0f;
Context context;
Location userLoc=new Location("service Provider");
// device sensor manager
private static SensorManager mSensorManager ;
private Sensor sensor;
public static TextView tvHeading;
   public QiblaDirectionCompass(Context context, ImageView compass, ImageView needle,TextView heading, double longi,double lati,double alti ) {

    image = compass;
    arrow = needle;


    // TextView that will tell the user what degree is he heading
    tvHeading = heading;
    userLoc.setLongitude(longi);
    userLoc.setLatitude(lati);
    userLoc.setAltitude(alti);

  mSensorManager =  (SensorManager) context.getSystemService(SENSOR_SERVICE);
    sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
    if(sensor!=null) {
        // for the system's orientation sensor registered listeners
        mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);//SensorManager.SENSOR_DELAY_Fastest
    }else{
        Toast.makeText(context,"Not Supported", Toast.LENGTH_SHORT).show();
    }
    // initialize your android device sensor capabilities
this.context =context;
@Override
public void onCreate() {
    // TODO Auto-generated method stub
    Toast.makeText(context, "Started", Toast.LENGTH_SHORT).show();
    mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME); //SensorManager.SENSOR_DELAY_Fastest
    super.onCreate();
}

@Override
public void onDestroy() {
    mSensorManager.unregisterListener(this);
Toast.makeText(context, "Destroy", Toast.LENGTH_SHORT).show();

    super.onDestroy();

}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {


Location destinationLoc = new Location("service Provider");

destinationLoc.setLatitude(21.422487); //kaaba latitude setting
destinationLoc.setLongitude(39.826206); //kaaba longitude setting
float bearTo=userLoc.bearingTo(destinationLoc);

  //bearTo = The angle from true north to the destination location from the point we're your currently standing.(asal image k N se destination taak angle )

  //head = The angle that you've rotated your phone from true north. (jaise image lagi hai wo true north per hai ab phone jitne rotate yani jitna image ka n change hai us ka angle hai ye)



GeomagneticField geoField = new GeomagneticField( Double.valueOf( userLoc.getLatitude() ).floatValue(), Double
        .valueOf( userLoc.getLongitude() ).floatValue(),
        Double.valueOf( userLoc.getAltitude() ).floatValue(),
        System.currentTimeMillis() );
head -= geoField.getDeclination(); // converts magnetic north into true north

if (bearTo < 0) {
    bearTo = bearTo + 360;
    //bearTo = -100 + 360  = 260;
}

//This is where we choose to point it
float direction = bearTo - head;

// If the direction is smaller than 0, add 360 to get the rotation clockwise.
if (direction < 0) {
    direction = direction + 360;
}
 tvHeading.setText("Heading: " + Float.toString(degree) + " degrees" );

RotateAnimation raQibla = new RotateAnimation(currentDegreeNeedle, direction, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
raQibla.setDuration(210);
raQibla.setFillAfter(true);

arrow.startAnimation(raQibla);

currentDegreeNeedle = direction;

// create a rotation animation (reverse turn degree degrees)
RotateAnimation ra = new RotateAnimation(currentDegree, -degree, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

// how long the animation will take place
ra.setDuration(210);


// set the animation after the end of the reservation status
ra.setFillAfter(true);

// Start the animation
image.startAnimation(ra);

currentDegree = -degree;
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {

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

xml code is here

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/flag_pakistan">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/heading"
    android:textColor="@color/colorAccent"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="100dp"
    android:layout_marginTop="20dp"
    android:text="Heading: 0.0" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/heading"
android:scaleType="centerInside"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true">

<ImageView
    android:id="@+id/imageCompass"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="centerInside"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:src="@drawable/images_compass"/>

<ImageView
    android:id="@+id/needle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:scaleType="centerInside"
    android:src="@drawable/arrow2"/>
</RelativeLayout>
</RelativeLayout>

__FILE__ macro shows full path

Since you are using GCC, you can take advantage of

__BASE_FILE__ This macro expands to the name of the main input file, in the form of a C string constant. This is the source file that was specified on the command line of the preprocessor or C compiler

and then control how you want to display the filename by changing the source file representation (full path/relative path/basename) at compilation time.

Is returning out of a switch statement considered a better practice than using break?

A break will allow you continue processing in the function. Just returning out of the switch is fine if that's all you want to do in the function.

Change value of variable with dplyr

We can use replace to change the values in 'mpg' to NA that corresponds to cyl==4.

mtcars %>%
     mutate(mpg=replace(mpg, cyl==4, NA)) %>%
     as.data.frame()

Why doesn't document.addEventListener('load', function) work in a greasemonkey script?

Apparently, document.addEventListener() is unreliable, and hence, my error. Use window.addEventListener() with the same parameters, instead.

$("#form1").validate is not a function

If you had a link I could look to see what the issue is but here are a couple questions and things to check:

  • Is the ID for your form named "form" in the HTML?
  • Check to see if messages are required, maybe there is some imbalance in parameters
  • You should also add the 'type="text/javascript"' attributes where you are getting jQuery from Google

Also, if you're going to use the Google CDN for getting jQuery you may as well use Microsoft's CDN for getting your validation file. Any of these URLs will work:

Listview Scroll to the end of the list after updating the list

The transcript mode is what you want and is used by Google Talk and the SMS/MMS application. Are you correctly calling notifyDatasetChanged() on your adapter when you add items?

Image resolution for mdpi, hdpi, xhdpi and xxhdpi

Please read the Android Documentation regarding screen sizes.

From a base image size, there is a 3:4:6:8:12:16 scaling ratio in drawable size by DPI.

LDPI - 0.75x
MDPI - Original size // means 1.0x here 
HDPI - 1.5x
XHDPI - 2.0x
XXHDPI - 3x
XXXHDPI - 4.0x

For example, 100x100px image on a MDPI will be the same size of a 200x200px on a XHDPI screen.

CREATE TABLE LIKE A1 as A2

Your attempt wasn't that bad. You have to do it with LIKE, yes.

In the manual it says:

Use LIKE to create an empty table based on the definition of another table, including any column attributes and indexes defined in the original table.

So you do:

CREATE TABLE New_Users  LIKE Old_Users;

Then you insert with

INSERT INTO New_Users SELECT * FROM Old_Users GROUP BY ID;

But you can not do it in one statement.

How to use unicode characters in Windows command line?

I got around a similar issue deleting Unicode-named files by referring to them in the batch file by their short (8 dot 3) names.

The short names can be viewed by doing dir /x. Obviously, this only works with Unicode file names that are already known.

Insert picture into Excel cell

While my recommendation is to take advantage of the automation available from Doality.com specifically Picture Manager for Excel

The following vba code should meet your criteria. Good Luck!

Add a Button Control to your Excel Workbook and then double click on the button in order to get to the VBA Code -->

Sub Button1_Click()
    Dim filePathCell As Range
    Dim imageLocationCell As Range
    Dim filePath As String

    Set filePathCell = Application.InputBox(Prompt:= _
        "Please select the cell that contains the reference path to your image file", _
            Title:="Specify File Path", Type:=8)

     Set imageLocationCell = Application.InputBox(Prompt:= _
        "Please select the cell where you would like your image to be inserted.", _
            Title:="Image Cell", Type:=8)

    If filePathCell Is Nothing Then
       MsgBox ("Please make a selection for file path")
       Exit Sub
    Else
      If filePathCell.Cells.Count > 1 Then
        MsgBox ("Please select only a single cell that contains the file location")
        Exit Sub
      Else
        filePath = Cells(filePathCell.Row, filePathCell.Column).Value
      End If
    End If

    If imageLocationCell Is Nothing Then
       MsgBox ("Please make a selection for image location")
       Exit Sub
    Else
      If imageLocationCell.Cells.Count > 1 Then
        MsgBox ("Please select only a single cell where you want the image to be populated")
        Exit Sub
      Else
        InsertPic filePath, imageLocationCell
        Exit Sub
      End If
    End If
End Sub

Then create your Insert Method as follows:

Private Sub InsertPic(filePath As String, ByVal insertCell As Range)
    Dim xlShapes As Shapes
    Dim xlPic As Shape
    Dim xlWorksheet As Worksheet

    If IsEmpty(filePath) Or Len(Dir(filePath)) = 0 Then
        MsgBox ("File Path invalid")
        Exit Sub
    End If

    Set xlWorksheet = ActiveSheet

    Set xlPic = xlWorksheet.Shapes.AddPicture(filePath, msoFalse, msoCTrue, insertCell.top, insertCell.left, insertCell.width, insertCell.height)
    xlPic.LockAspectRatio = msoCTrue
End Sub

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

How do I erase an element from std::vector<> by index?

I suggest to read this since I believe that is what are you looking for.https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom

If you use for example

 vec.erase(vec.begin() + 1, vec.begin() + 3);

you will erase n -th element of vector but when you erase second element, all other elements of vector will be shifted and vector sized will be -1. This can be problem if you loop through vector since vector size() is decreasing. If you have problem like this provided link suggested to use existing algorithm in standard C++ library. and "remove" or "remove_if".

Hope that this helped

is inaccessible due to its protection level

myClub.distance = Console.ReadLine();

should be

myClub.mydistance = Console.ReadLine(); 

use your public properties that you have defined for others as well instead of the protected field members.

How to save LogCat contents to file?

An additional tip if you want only the log shown in the past half hour with timestamps, or within another set time. Adjust date format to match your system. This one works on Ubuntu 16.04LTS:

adb shell logcat -d -v time -t "$(date '+%m-%d %H:%M:%S.%3N' -d '30 minutes ago')" > log_name.log

How to insert an image in python

Install PIL(Python Image Library) :

then:

from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();

How to know the version of pip itself

Any of the following should work

pip --version
# pip 19.0.3 from /usr/local/lib/python2.7/site-packages/pip (python 2.7)

or

pip -V       
# pip 19.0.3 from /usr/local/lib/python2.7/site-packages/pip (python 2.7)

or

pip3 -V      
# pip 19.0.3 from /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip (python 3.7)

iOS 7 - Failing to instantiate default view controller

First click on the View Controller in the right hand side Utilities bar. Next select the Attributes Inspector and make sure that under the View Controller section the 'Is Initial View Controller' checkbox is checked!

How to position text over an image in css

How about something like this: http://jsfiddle.net/EgLKV/3/

Its done by using position:absolute and z-index to place the text over the image.

_x000D_
_x000D_
#container {_x000D_
  height: 400px;_x000D_
  width: 400px;_x000D_
  position: relative;_x000D_
}_x000D_
#image {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
}_x000D_
#text {_x000D_
  z-index: 100;_x000D_
  position: absolute;_x000D_
  color: white;_x000D_
  font-size: 24px;_x000D_
  font-weight: bold;_x000D_
  left: 150px;_x000D_
  top: 350px;_x000D_
}
_x000D_
<div id="container">_x000D_
  <img id="image" src="http://www.noao.edu/image_gallery/images/d4/androa.jpg" />_x000D_
  <p id="text">_x000D_
    Hello World!_x000D_
  </p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Calculating average of an array list?

Why use a clumsy for loop with an index when you have the enhanced for loop?

private double calculateAverage(List <Integer> marks) {
  Integer sum = 0;
  if(!marks.isEmpty()) {
    for (Integer mark : marks) {
        sum += mark;
    }
    return sum.doubleValue() / marks.size();
  }
  return sum;
}

How do I set the default font size in Vim?

The other answers are what you asked about, but in case it’s useful to anyone else, here’s how to set the font conditionally from the screen DPI (Windows only):

set guifont=default
if has('windows')
    "get dpi, strip out utf-16 garbage and new lines
    "system() converts 0x00 to 0x01 for 'platform independence'
    "should return something like 'PixelsPerXLogicalInch=192'
    "get the part from the = to the end of the line (eg '=192') and strip
    "the first character
    "and convert to a number
    let dpi = str2nr(strpart(matchstr(substitute(
        \system('wmic desktopmonitor get PixelsPerXLogicalInch /value'),
        \'\%x01\|\%x0a\|\%x0a\|\%xff\|\%xfe', '', 'g'),
        \'=.*$'), 1))
    if dpi > 100
        set guifont=high_dpi_font
    endif
endif

Conditional WHERE clause with CASE statement in Oracle

You can write the where clause as:

where (case when (:stateCode = '') then (1)
            when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
            else 0)
       end) = 1;

Alternatively, remove the case entirely:

where (:stateCode = '') or
      ((:stateCode != '') and vw.state_cd in (:stateCode));

Or, even better:

where (:stateCode = '') or vw.state_cd in (:stateCode)

Laravel 5 PDOException Could Not Find Driver

Same thing happend to me after upgrading distro.

Running sudo apt-get install php7.0-mysql fixed it for me.

Generate Java class from JSON?

Let me show you how to dev the tool.you can do so:

  1. user javascript function Json.parse(),make string like-json trans to js object
  2. then use this object to genrate the javabean format.
  3. something,you shoud care.(1)value type mapping,forexample,how to figure out the string,is date type.(2)loweser_case to camelCase

I dev a tool solve the problem.it is well design and quick more. get the code from my github.

enjoy it from here,I have deploy it on webserver.

I try the top 2 answer's suggestion.one web is can not open.one is slower than my tool.hope you will enjoy my tool.

How to SELECT the last 10 rows of an SQL table which has no ID field?

A low-tech approach: Doing this with SQL might be overkill. According to your question you just need to do a one-time verification of the import.

Why not just do: SELECT * FROM ImportTable

and then scroll to the bottom of the results grid and visually verify the "last" few lines.

How to empty (clear) the logcat buffer in Android

The following command will clear only non-rooted buffers (main, system ..etc).

adb logcat -c

If you want to clear all the buffers (like radio, kernel..etc), Please use the following commands

adb root
adb logcat -b all -c

or

adb root
adb shell logcat -b all -c 

Use the following commands to know the list of buffers that device supports

adb logcat -g
adb logcat -b all -g
adb shell logcat -b all -g

How to make rectangular image appear circular with CSS

I presume that your problem with background-image is that it would be inefficient with a source for each image inside a stylesheet. My suggestion is to set the source inline:

<div style = 'background-image: url(image.gif)'></div>

div {
    background-repeat: no-repeat;
    background-position: 50%;
    border-radius: 50%;
    width: 100px;
    height: 100px;
}

Fiddle