Programs & Examples On #Intel mkl

Intel MKL (Math Kernel Library) is a high performance math library specifically optimised for Intel processors. Its core functions include BLAS and LAPACK linear algebra routines, fast Fourier transforms and vector math functions amongst others.

Set CSS property in Javascript?

For most styles do this:

var obj = document.createElement('select');
obj.style.width= "100px";

For styles that have hyphens in the name do this instead:

var obj = document.createElement('select');
obj.style["-webkit-background-size"] = "100px"

How to get docker-compose to always re-create containers from fresh images?

The only solution that worked for me was this command :

docker-compose build --no-cache

This will automatically pull fresh image from repo and won't use the cache version that is prebuild with any parameters you've been using before.

How to host a Node.Js application in shared hosting

You can run node.js server on a typical shared hosting with Linux, Apache and PHP (LAMP). I have successfully installed it, even with NPM, Express and Grunt working fine. Follow the steps:

1) Create a new PHP file on the server with the following code and run it:

<?php
//Download and extract the latest node
exec('curl http://nodejs.org/dist/latest/node-v0.10.33-linux-x86.tar.gz | tar xz');
//Rename the folder for simplicity
exec('mv node-v0.10.33-linux-x86 node');

2) The same way install your node app, e.g. jt-js-sample, using npm:

<?php
exec('node/bin/npm install jt-js-sample');

3) Run the node app from PHP:

<?php
//Choose JS file to run
$file = 'node_modules/jt-js-sample/index.js';
//Spawn node server in the background and return its pid
$pid = exec('PORT=49999 node/bin/node ' . $file . ' >/dev/null 2>&1 & echo $!');
//Wait for node to start up
usleep(500000);
//Connect to node server using cURL
$curl = curl_init('http://127.0.0.1:49999/');
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//Get the full response
$resp = curl_exec($curl);
if($resp === false) {
    //If couldn't connect, try increasing usleep
    echo 'Error: ' . curl_error($curl);
} else {
    //Split response headers and body
    list($head, $body) = explode("\r\n\r\n", $resp, 2);
    $headarr = explode("\n", $head);
    //Print headers
    foreach($headarr as $headval) {
        header($headval);
    }
    //Print body
    echo $body;
}
//Close connection
curl_close($curl);
//Close node server
exec('kill ' . $pid);

Voila! Have a look at the demo of a node app on PHP shared hosting.

EDIT: I started a Node.php project on GitHub.

Copy data from one existing row to another existing row in SQL?

This works well for coping entire records.

UPDATE your_table
SET new_field = sourse_field

Email Address Validation for ASP.NET

Preventing XSS is a different issue from validating input.

Regarding XSS: You should not try to check input for XSS or related exploits. You should prevent XSS exploits, SQL injection and so on by escaping correctly when inserting strings into a different language where some characters are "magic", eg, when inserting strings in HTML or SQL. For example a name like O'Reilly is perfectly valid input, but could cause a crash or worse if inserted unescaped into SQL. You cannot prevent that kind of problems by validating input.

Validation of user input makes sense to prevent missing or malformed data, eg. a user writing "asdf" in the zip-code field and so on. Wrt. e-mail adresses, the syntax is so complex though, that it doesnt provide much benefit to validate it using a regex. Just check that it contains a "@".

Reducing the gap between a bullet and text in a list item

I have <a> inside the <li>s.

To the <ul> elements, apply the following CSS:

ul {
    margin: 0;
    padding: 0;
    list-style: none;
}

To the <a> elements, apply the following CSS:

a:before {
    content: "";
    height: 6px;
    width: 6px;
    border-radius: 50%;
    background: #000;
    display: inline-block;
    margin: 0 6px 0 0;
    vertical-align: middle;
}

This creates pseudo elements for the bullets. They can be styled just like any other elements.

I've implemented it here: http://www.cssdesk.com/R2AvX

How to format strings in Java

If you choose not to use String.format, the other option is the + binary operator

String str = "Step " + a + " of " + b;

This is the equivalent of

new StringBuilder("Step ").append(String.valueOf(1)).append(" of ").append(String.valueOf(2));

Whichever you use is your choice. StringBuilder is faster, but the speed difference is marginal. I prefer to use the + operator (which does a StringBuilder.append(String.valueOf(X))) and find it easier to read.

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

This is what I use to get the minimum date in SQL Server. Please note that it is globalisation friendly:

CREATE FUNCTION [dbo].[DateTimeMinValue]()
RETURNS datetime
AS
BEGIN
  RETURN (SELECT
    CAST('17530101' AS datetime))
END

Call using:

SELECT [dbo].[DateTimeMinValue]()

CSS3 selector to find the 2nd div of the same class

First you must select the parent element and set :nth-of-type(n) for the parent and then select the element you want. something like this :

#topmenu li:nth-of-type(2) ul.childUl {

This will select the second submenu from topmenu. #topmenu li is the parent element.

HTML:

<ul id="topmenu">
    <li>
        <ul class="childUl">
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </li>
    <li>
        <ul class="childUl">
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </li>
    <li>
        <ul class="childUl">
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </li>

How to count digits, letters, spaces for a string in Python?

def match_string(words):
    nums = 0
    letter = 0
    other = 0
    for i in words :
        if i.isalpha():
            letter+=1
        elif i.isdigit():
            nums+=1
        else:
            other+=1
    return nums,letter,other

x = match_string("Hello World")
print(x)
>>>
(0, 10, 2)
>>>

Check file extension in upload form in PHP

To properly achieve this, you'd be better off by checking the mime type.

function get_mime($file) {
  if (function_exists("finfo_file")) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
    $mime = finfo_file($finfo, $file);
    finfo_close($finfo);
    return $mime;
  } else if (function_exists("mime_content_type")) {
    return mime_content_type($file);
  } else if (!stristr(ini_get("disable_functions"), "shell_exec")) {
    // http://stackoverflow.com/a/134930/1593459
    $file = escapeshellarg($file);
    $mime = shell_exec("file -bi " . $file);
    return $mime;
  } else {
    return false;
  }
}
//pass the file name as
echo(get_mime($_FILES['file_name']['tmp_name']));

Run command on the Ansible host

I'd like to share that Ansible can be run on localhost via shell:

ansible all -i "localhost," -c local -m shell -a 'echo hello world'

This could be helpful for simple tasks or for some hands-on learning of Ansible.

The example of code is taken from this good article:

Running ansible playbook in localhost

How to call a Parent Class's method from Child Class in Python?

Python also has super as well:

super(type[, object-or-type])

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.

Example:

class A(object):     # deriving from 'object' declares A as a 'new-style-class'
    def foo(self):
        print "foo"

class B(A):
    def foo(self):
        super(B, self).foo()   # calls 'A.foo()'

myB = B()
myB.foo()

How to set environment variable or system property in spring tests?

You can set the System properties as VM arguments.

If your project is a maven project then you can execute following command while running the test class:

mvn test -Dapp.url="https://stackoverflow.com"

Test class:

public class AppTest  {
@Test
public void testUrl() {
    System.out.println(System.getProperty("app.url"));
    }
}

If you want to run individual test class or method in eclipse then :

1) Go to Run -> Run Configuration

2) On left side select your Test class under the Junit section.

3) do the following :

enter image description here

XPath OR operator for different nodes

All title nodes with zipcode or book node as parent:

Version 1:

//title[parent::zipcode|parent::book]

Version 2:

//bookstore/book/title|//bookstore/city/zipcode/title

Version 3: (results are sorted based on source data rather than the order of book then zipcode)

//title[../../../*[book or magazine] or ../../../../*[city/zipcode]]

or - used within true/false - a Boolean operator in xpath

| - a Union operator in xpath that appends the query to the right of the operator to the result set from the left query.

Listing only directories in UNIX

Try this ls -d */ to list directories within the current directory

Inserting HTML into a div

And many lines may look like this. The html here is sample only.

var div = document.createElement("div");

div.innerHTML =
    '<div class="slideshow-container">\n' +
    '<div class="mySlides fade">\n' +
    '<div class="numbertext">1 / 3</div>\n' +
    '<img src="image1.jpg" style="width:100%">\n' +
    '<div class="text">Caption Text</div>\n' +
    '</div>\n' +

    '<div class="mySlides fade">\n' +
    '<div class="numbertext">2 / 3</div>\n' +
    '<img src="image2.jpg" style="width:100%">\n' +
    '<div class="text">Caption Two</div>\n' +
    '</div>\n' +

    '<div class="mySlides fade">\n' +
    '<div class="numbertext">3 / 3</div>\n' +
    '<img src="image3.jpg" style="width:100%">\n' +
    '<div class="text">Caption Three</div>\n' +
    '</div>\n' +

    '<a class="prev" onclick="plusSlides(-1)">&#10094;</a>\n' +
    '<a class="next" onclick="plusSlides(1)">&#10095;</a>\n' +
    '</div>\n' +
    '<br>\n' +

    '<div style="text-align:center">\n' +
    '<span class="dot" onclick="currentSlide(1)"></span> \n' +
    '<span class="dot" onclick="currentSlide(2)"></span> \n' +
    '<span class="dot" onclick="currentSlide(3)"></span> \n' +
    '</div>\n';

document.body.appendChild(div);

Take a full page screenshot with Firefox on the command-line

Firefox Screenshots is a new tool that ships with Firefox. It is not a developer tool, it is aimed at end-users of the browser.

To take a screenshot, click on the page actions menu in the address bar, and click "take a screenshot". If you then click "Save full page", it will save the full page, scrolling for you.


(source: mozilla.net)

Express.js req.body undefined

Simple example to get through all:

Express Code For Method='post' after Login:

This would not require any such bodyParser().

enter image description here

app.js

const express = require('express');
const mongoose = require('mongoose');
const mongoDB = require('mongodb');

const app = express();

app.set('view engine', 'ejs');

app.get('/admin', (req,res) => {
 res.render('admin');
});

app.post('/admin', (req,res) => {
 console.log(JSON.stringify(req.body.name));
 res.send(JSON.stringify(req.body.name));
});

app.listen(3000, () => {
 console.log('listening on 3000');
});

admin.ejs

<!DOCTYPE Html>
<html>
 <head>
  <title>Admin Login</title>
 </head>
 <body>
   <div>
    <center padding="100px">
       <form method="post" action="/admin">
          <div> Secret Key:
            <input name='name'></input>
          </div><br></br><br></br>
          <div>
            <button type="submit" onClick='smsAPI()'>Get OTP</button>
          </div>
       </form>
    </center>
    </div >
</body>
</html>

You get input. The 'name' in "" is a variable that carries data through method='post'. For multiple data input, name='name[]'.

Hence,

on name='name' 

input: Adu
backend: "Adu"

OR

input: Adu, Luv,
backend: "Adu, Luv,"

on

name='name[]'
input: Adu,45689, ugghb, Luv
backend: ["Adu,45689, ugghb, Luv"]

Query an object array using linq

Add:

using System.Linq;

to the top of your file.

And then:

Car[] carList = ...
var carMake = 
    from item in carList
    where item.Model == "bmw" 
    select item.Make;

or if you prefer the fluent syntax:

var carMake = carList
    .Where(item => item.Model == "bmw")
    .Select(item => item.Make);

Things to pay attention to:

  • The usage of item.Make in the select clause instead if s.Make as in your code.
  • You have a whitespace between item and .Model in your where clause

How can I make a CSS glass/blur effect work for an overlay?

I came up with this solution.

Click to view image of blurry effect

It is kind of a trick which uses an absolutely positioned child div, sets its background image same as the parent div and then uses the background-attachment:fixed CSS property together with the same background properties set on the parent element.

Then you apply filter:blur(10px) (or any value) on the child div.

_x000D_
_x000D_
*{
    margin:0;
    padding:0;
    box-sizing: border-box;
}
.background{
    position: relative;
    width:100%;
    height:100vh;
    background-image:url('https://images.unsplash.com/photo-1547937414-009abc449011?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80');
    background-size:cover;
    background-position: center;
    background-repeat:no-repeat;
}

.blur{
    position: absolute;
    top:0;
    left:0;
    width:50%;
    height:100%;
    background-image:url('https://images.unsplash.com/photo-1547937414-009abc449011?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80');
    background-position: center;
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size:cover;
    filter:blur(10px);
    transition:filter .5s ease;
    backface-visibility: hidden;
}

.background:hover .blur{
    filter:blur(0);
}
.text{
    display: inline-block;
    font-family: sans-serif;
    color:white;
    font-weight: 600;
    text-align: center;
    position: relative;
    left:25%;
    top:50%;
    transform:translate(-50%,-50%);
}
_x000D_
<head>
    <title>Blurry Effect</title>
</head>
<body>
    <div class="background">
        <div class="blur"></div>
        <h1 class="text">This is the <br>blurry side</h1>
    </div>
</body>
_x000D_
_x000D_
_x000D_

view on codepen

How to remove single character from a String

public String missingChar(String str, int n) {
  String front = str.substring(0, n);

// Start this substring at n+1 to omit the char.
// Can also be shortened to just str.substring(n+1)
// which goes through the end of the string.

String back = str.substring(n+1, str.length());
  return front + back;
}

How to handle floats and decimal separators with html5 input type number

According to w3.org the value attribute of the number input is defined as a floating-point number. The syntax of the floating-point number seems to only accept dots as decimal separators.

I've listed a few options below that might be helpful to you:

1. Using the pattern attribute

With the pattern attribute you can specify the allowed format with a regular expression in a HTML5 compatible way. Here you could specify that the comma character is allowed and a helpful feedback message if the pattern fails.

<input type="number" pattern="[0-9]+([,\.][0-9]+)?" name="my-num"
           title="The number input must start with a number and use either comma or a dot as a decimal character."/>

Note: Cross-browser support varies a lot. It may be complete, partial or non-existant..

2. JavaScript validation

You could try to bind a simple callback to for example the onchange (and/or blur) event that would either replace the comma or validate all together.

3. Disable browser validation ##

Thirdly you could try to use the formnovalidate attribute on the number inputs with the intention of disabling browser validation for that field all together.

<input type="number" formnovalidate />

4. Combination..?

<input type="number" pattern="[0-9]+([,\.][0-9]+)?" 
           name="my-num" formnovalidate
           title="The number input must start with a number and use either comma or a dot as a decimal character."/>

Using momentjs to convert date to epoch then back to date

There are a few things wrong here:

  • First, terminology. "Epoch" refers to the starting point of something. The "Unix Epoch" is Midnight, January 1st 1970 UTC. You can't convert an arbitrary "date string to epoch". You probably meant "Unix Time", which is often erroneously called "Epoch Time".

  • .unix() returns Unix Time in whole seconds, but the default moment constructor accepts a timestamp in milliseconds. You should instead use .valueOf() to return milliseconds. Note that calling .unix()*1000 would also work, but it would result in a loss of precision.

  • You're parsing a string without providing a format specifier. That isn't a good idea, as values like 1/2/2014 could be interpreted as either February 1st or as January 2nd, depending on the locale of where the code is running. (This is also why you get the deprecation warning in the console.) Instead, provide a format string that matches the expected input, such as:

    moment("10/15/2014 9:00", "M/D/YYYY H:mm")
    
  • .calendar() has a very specific use. If you are near to the date, it will return a value like "Today 9:00 AM". If that's not what you expected, you should use the .format() function instead. Again, you may want to pass a format specifier.

  • To answer your questions in comments, No - you don't need to call .local() or .utc().

Putting it all together:

var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").valueOf();
var m = moment(ts);
var s = m.format("M/D/YYYY H:mm");
alert("Values are: ts = " + ts + ", s = " + s);

On my machine, in the US Pacific time zone, it results in:

Values are: ts = 1413388800000, s = 10/15/2014 9:00

Since the input value is interpreted in terms of local time, you will get a different value for ts if you are in a different time zone.

Also note that if you really do want to work with whole seconds (possibly losing precision), moment has methods for that as well. You would use .unix() to return the timestamp in whole seconds, and moment.unix(ts) to parse it back to a moment.

var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").unix();
var m = moment.unix(ts);

How do I use extern to share variables between source files?

First off, the extern keyword is not used for defining a variable; rather it is used for declaring a variable. I can say extern is a storage class, not a data type.

extern is used to let other C files or external components know this variable is already defined somewhere. Example: if you are building a library, no need to define global variable mandatorily somewhere in library itself. The library will be compiled directly, but while linking the file, it checks for the definition.

illegal character in path

Try this:

string path = @"C:\Program Files (x86)\test software\myapp\demo.exe";

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

So far, the accepted answer has worked best for me. However, my concern has always been that there is a likely scenario where I might refactor the notebooks directory into subdirectories, requiring to change the module_path in every notebook. I decided to add a python file within each notebook directory to import the required modules.

Thus, having the following project structure:

project
|__notebooks
   |__explore
      |__ notebook1.ipynb
      |__ notebook2.ipynb
      |__ project_path.py
   |__ explain
       |__notebook1.ipynb
       |__project_path.py
|__lib
   |__ __init__.py
   |__ module.py

I added the file project_path.py in each notebook subdirectory (notebooks/explore and notebooks/explain). This file contains the code for relative imports (from @metakermit):

import sys
import os

module_path = os.path.abspath(os.path.join(os.pardir, os.pardir))
if module_path not in sys.path:
    sys.path.append(module_path)

This way, I just need to do relative imports within the project_path.py file, and not in the notebooks. The notebooks files would then just need to import project_path before importing lib. For example in 0.0-notebook.ipynb:

import project_path
import lib

The caveat here is that reversing the imports would not work. THIS DOES NOT WORK:

import lib
import project_path

Thus care must be taken during imports.

How to replace negative numbers in Pandas Data Frame by zero

If all your columns are numeric, you can use boolean indexing:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'a': [0, -1, 2], 'b': [-3, 2, 1]})

In [3]: df
Out[3]: 
   a  b
0  0 -3
1 -1  2
2  2  1

In [4]: df[df < 0] = 0

In [5]: df
Out[5]: 
   a  b
0  0  0
1  0  2
2  2  1

For the more general case, this answer shows the private method _get_numeric_data:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'a': [0, -1, 2], 'b': [-3, 2, 1],
                           'c': ['foo', 'goo', 'bar']})

In [3]: df
Out[3]: 
   a  b    c
0  0 -3  foo
1 -1  2  goo
2  2  1  bar

In [4]: num = df._get_numeric_data()

In [5]: num[num < 0] = 0

In [6]: df
Out[6]: 
   a  b    c
0  0  0  foo
1  0  2  goo
2  2  1  bar

With timedelta type, boolean indexing seems to work on separate columns, but not on the whole dataframe. So you can do:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'a': pd.to_timedelta([0, -1, 2], 'd'),
   ...:                    'b': pd.to_timedelta([-3, 2, 1], 'd')})

In [3]: df
Out[3]: 
        a       b
0  0 days -3 days
1 -1 days  2 days
2  2 days  1 days

In [4]: for k, v in df.iteritems():
   ...:     v[v < 0] = 0
   ...:     

In [5]: df
Out[5]: 
       a      b
0 0 days 0 days
1 0 days 2 days
2 2 days 1 days

Update: comparison with a pd.Timedelta works on the whole DataFrame:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'a': pd.to_timedelta([0, -1, 2], 'd'),
   ...:                    'b': pd.to_timedelta([-3, 2, 1], 'd')})

In [3]: df[df < pd.Timedelta(0)] = 0

In [4]: df
Out[4]: 
       a      b
0 0 days 0 days
1 0 days 2 days
2 2 days 1 days

How to concatenate two MP4 files using FFmpeg?

Here's a fast (takes less than 1 minute) and lossless way to do this without needing intermediate files:

ls Movie_Part_1.mp4 Movie_Part_2.mp4 | \
perl -ne 'print "file $_"' | \
ffmpeg -f concat -i - -c copy Movie_Joined.mp4

The "ls" contains the files to join The "perl" creates the concatenation file on-the-fly into a pipe The "-i -" part tells ffmpeg to read from the pipe

(note - my files had no spaces or weird stuff in them - you'll need appropriate shell-escaping if you want to do this idea with "hard" files).

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

I suggest you use TO_CHAR() when converting to string. In order to do that, you need to build a date first.

SELECT TO_CHAR(TO_DATE(DAY||'-'||MONTH||'-'||YEAR, 'dd-mm-yyyy'), 'dd-mm-yyyy') AS FORMATTED_DATE
FROM
    (SELECT EXTRACT( DAY FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy')
        FROM DUAL
        )) AS DAY, TO_NUMBER(EXTRACT( MONTH FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
        )), 09) AS MONTH, EXTRACT(YEAR FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
        )) AS YEAR
    FROM DUAL
    );

How to compile and run C files from within Notepad++ using NppExec plugin?

I've written just this to execute compiling and run the file after, plus fileinputname = fileoutputname on windowsmashines, if your compilerpath is registred in the windows PATH-var:

NPP_SAVE
cd "$(CURRENT_DIRECTORY)"
set LEN~ strrfind $(FILE_NAME) .
set EXENAME ~ substr 0 $(LEN) $(FILE_NAME)
set $(EXENAME) = $(EXENAME).exe
c++.exe "$(FILE_NAME)" -o "$(EXENAME)"
"$(EXENAME)"

should work for any compiler if you change c++.exe to what you want

How to include CSS file in Symfony 2 and Twig?

The other answers are valid, but the Official Symfony Best Practices guide suggests using the web/ folder to store all assets, instead of different bundles.

Scattering your web assets across tens of different bundles makes it more difficult to manage them. Your designers' lives will be much easier if all the application assets are in one location.

Templates also benefit from centralizing your assets, because the links are much more concise[...]

I'd add to this by suggesting that you only put micro-assets within micro-bundles, such as a few lines of styles only required for a button in a button bundle, for example.

How can I get the last 7 characters of a PHP string?

for last 7 characters

$newstring = substr($dynamicstring, -7);

$newstring : 5409els

for first 7 characters

$newstring = substr($dynamicstring, 0, 7);

$newstring : 2490slk

How can I output UTF-8 from Perl?

TMTOWTDI, chose the method that best fits how you work. I use the environment method so I don't have to think about it.

In the environment:

export PERL_UNICODE=SDL

on the command line:

perl -CSDL -le 'print "\x{1815}"';

or with binmode:

binmode(STDOUT, ":utf8");          #treat as if it is UTF-8
binmode(STDIN, ":encoding(utf8)"); #actually check if it is UTF-8

or with PerlIO:

open my $fh, ">:utf8", $filename
    or die "could not open $filename: $!\n";

open my $fh, "<:encoding(utf-8)", $filename
    or die "could not open $filename: $!\n";

or with the open pragma:

use open ":encoding(utf8)";
use open IN => ":encoding(utf8)", OUT => ":utf8";

Android list view inside a scroll view

This worked for me (link1, link2):

  • You Create Custom ListView Which is non Scrollable

    public class NonScrollListView extends ListView {
    
            public NonScrollListView(Context context) {
                super(context);
            }
            public NonScrollListView(Context context, AttributeSet attrs) {
                super(context, attrs);
            }
            public NonScrollListView(Context context, AttributeSet attrs, int defStyle) {
                super(context, attrs, defStyle);
            }
            @Override
            public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                int heightMeasureSpec_custom = View.MeasureSpec.makeMeasureSpec(
                        Integer.MAX_VALUE >> 2, View.MeasureSpec.AT_MOST);
                super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
                ViewGroup.LayoutParams params = getLayoutParams();
                params.height = getMeasuredHeight();
            }
        }
    
  • In Your Layout File

    <ScrollView 
     xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">
    
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
    
            <!-- com.Example Changed with your Package name -->
    
            <com.thedeveloperworldisyours.view.NonScrollListView
                android:id="@+id/lv_nonscroll_list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >
            </com.thedeveloperworldisyours.view.NonScrollListView>
    
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/lv_nonscroll_list" >
    
                <!-- Your another layout in scroll view -->
    
            </RelativeLayout>
        </RelativeLayout>
    
    </ScrollView>
    
  • Create a object of your customListview instead of ListView like :

     NonScrollListView non_scroll_list = (NonScrollListView) findViewById(R.id.lv_nonscroll_list);
    

Necessary to add link tag for favicon.ico?

To choose a different location or file type (e.g. PNG or SVG) for the favicon:
One reason can be that you want to have the icon in a specific location, perhaps in the images folder or something alike. For example:

<link rel="icon" href="_/img/favicon.png">

This diferent location may even be a CDN, just like SO seems to do with <link rel="shortcut icon" href="http://cdn.sstatic.net/stackoverflow/img/favicon.ico">.

To learn more about using other file types like PNG check out this question.

For cache busting purposes:
Add a query string to the path for cache-busting purposes:

<link rel="icon" href="/favicon.ico?v=1.1"> 

Favicons are very heavily cached and this a great way to ensure a refresh.


Footnote about default location:
As far as the first bit of the question: all modern browsers would detect a favicon at the default location, so that's not a reason to use a link for it.


Footnote about rel="icon":
As indicated by @Semanino's answer, using rel="shortcut icon" is an old technique which was required by older versions of Internet Explorer, but in most cases can be replaced by the more correct rel="icon" instruction. The article @Semanino based this on properly links to the appropriate spec which shows a rel value of shortcut isn't a valid option.

How to store NULL values in datetime fields in MySQL?

For what it is worth: I was experiencing a similar issue trying to update a MySQL table via Perl. The update would fail when an empty string value (translated from a null value from a read from another platform) was passed to the date column ('dtcol' in the code sample below). I was finally successful getting the data updated by using an IF statement embedded in my update statement:

    ...
    my $stmnt='update tbl set colA=?,dtcol=if(?="",null,?) where colC=?';
    my $status=$dbh->do($stmt,undef,$iref[1],$iref[2],$iref[2],$ref[0]);
    ...

Can RDP clients launch remote applications and not desktops

At least on 2008R2 if the accounts are only used for RDP and not for local logins then you can set this on a per-account basis. That should work for thin clients. If the accounts are also used on local desktops then this would also affect those logins.

In ADUsers&Computers, open the properties for the account and go to the Environment tab. On that tab, check "Start the following program at logon" and specify the path and executable for the program.

How do I get the current time only in JavaScript

This is the shortest way.

var now = new Date().toLocaleTimeString();
console.log(now)

Here is also a way through string manipulation that was not mentioned.

var now = new Date()
console.log(now.toString().substr(16,8))

What does "control reaches end of non-void function" mean?

add to your code:

"#include < stdlib.h>"

return EXIT_SUCCESS;

at the end of main()

Is there a Subversion command to reset the working copy?

To revert tracked files

svn revert . -R

To clean untracked files

svn status | rm -rf $(awk '/^?/{$1 = ""; print $0}')

The -rf may/should look scary at first, but once understood it will not be for these reasons:

  1. Only wholly-untracked directories will match the pattern passed to rm
  2. The -rf is required, else these directories will not be removed

To revert then clean (the OP question)

svn revert . -R && svn status | rm -rf $(awk '/^?/{$1 = ""; print $0}')

For consistent ease of use

Add permanent alias to your .bash_aliases

alias svn.HardReset='read -p "destroy all local changes?[y/N]" && [[ $REPLY =~ ^[yY] ]] && svn revert . -R && rm -rf $(awk -f <(echo "/^?/{print \$2}") <(svn status) ;)'

What is the difference between \r and \n?

In short \r has ASCII value 13 (CR) and \n has ASCII value 10 (LF). Mac uses CR as line delimiter (at least, it did before, I am not sure for modern macs), *nix uses LF and Windows uses both (CRLF).

Changing background color of selected item in recyclerview

in the Kotlin you can do this simply: all you need is to create a static variable like this:

companion object {
     var last_position = 0
}

then in your onBindViewHolder add this code:

holder.item.setOnClickListener{
        holder.item.setBackgroundResource(R.drawable.selected_item)
        notifyItemChanged(last_position)
        last_position=position
    }

which item is the child of recyclerView which you want to change its background after clicking on it.

ReactNative: how to center text?

used

textalign:center

at the view

How to create loading dialogs in Android?

It's a ProgressDialog, with setIndeterminate(true).

From http://developer.android.com/guide/topics/ui/dialogs.html#ProgressDialog

ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "", 
                    "Loading. Please wait...", true);

An indeterminate progress bar doesn't actually show a bar, it shows a spinning activity circle thing. I'm sure you know what I mean :)

How to use execvp()

In cpp, you need to pay special attention to string types when using execvp:

#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
#include <unistd.h>
using namespace std;

const size_t MAX_ARGC = 15; // 1 command + # of arguments
char* argv[MAX_ARGC + 1]; // Needs +1 because of the null terminator at the end
// c_str() converts string to const char*, strdup converts const char* to char*
argv[0] = strdup(command.c_str());

// start filling up the arguments after the first command
size_t arg_i = 1;
while (cin && arg_i < MAX_ARGC) {
    string arg;
    cin >> arg;
    if (arg.empty()) {
        argv[arg_i] = nullptr;
        break;
    } else {
        argv[arg_i] = strdup(arg.c_str());
    }
    ++arg_i;
}

// Run the command with arguments
if (execvp(command.c_str(), argv) == -1) {
    // Print error if command not found
    cerr << "command '" << command << "' not found\n";
}

Reference: execlp?execvp?????

Python nonlocal statement

a = 0    #1. global variable with respect to every function in program

def f():
    a = 0          #2. nonlocal with respect to function g
    def g():
        nonlocal a
        a=a+1
        print("The value of 'a' using nonlocal is ", a)
    def h():
        global a               #3. using global variable
        a=a+5
        print("The value of a using global is ", a)
    def i():
        a = 0              #4. variable separated from all others
        print("The value of 'a' inside a function is ", a)

    g()
    h()
    i()
print("The value of 'a' global before any function", a)
f()
print("The value of 'a' global after using function f ", a)

Break when a value changes using the Visual Studio debugger

I remember the way you described it using Visual Basic 6.0. In Visual Studio, the only way I have found so far is by specifying a breakpoint condition.

Install sbt on ubuntu

No command sbt found

It's saying that sbt is not on your path. Try to run ./sbt from ~/bin/sbt/bin or wherever the sbt executable is to verify that it runs correctly. Also check that you have execute permissions on the sbt executable. If this works , then add ~/bin/sbt/bin to your path and sbt should run from anywhere.

See this question about adding a directory to your path.

To verify the path is set correctly use the which command on LINUX. The output will look something like this:

$ which sbt
/usr/bin/sbt

Lastly, to verify sbt is working try running sbt -help or likewise. The output with -help will look something like this:

$ sbt -help
Usage: sbt [options]

  -h | -help         print this message
  ...

What is a regular expression which will match a valid domain name without a subdomain?

For new gTLDs

/^((?!-)[\p{L}\p{N}-]+(?<!-)\.)+[\p{L}\p{N}]{2,}$/iu

Dump a mysql database to a plaintext (CSV) backup from the command line

Check out mk-parallel-dump which is part of the ever-useful maatkit suite of tools. This can dump comma-separated files with the --csv option.

This can do your whole db without specifying individual tables, and you can specify groups of tables in a backupset table.

Note that it also dumps table definitions, views and triggers into separate files. In addition providing a complete backup in a more universally accessible form, it also immediately restorable with mk-parallel-restore

mysql: see all open connections to a given database?

If you're running a *nix system, also consider mytop.

To limit the results to one database, press "d" when it's running then type in the database name.

frequent issues arising in android view, Error parsing XML: unbound prefix

It usually happens to me when I misspell android - I just type andorid or alike, and it's not obvious at first sight especially after many hours of programming, so I just do a search for "android" one by one and see if search skips one tag - if it does then I have a close look and I see where was typo.

Check whether a path is valid

Just Simply Use

if (System.IO.Directory.Exists(path))
{
    ...
}

How to find out if an installed Eclipse is 32 or 64 bit version?

Hit Ctrl+Alt+Del to open the Windows Task manager and switch to the processes tab.

32-bit programs should be marked with *32.

Shell equality operators (=, ==, -eq)

Several answers show dangerous examples. OP's example [ $a == $b ] specifically used unquoted variable substitution (as of Oct '17 edit). For [...] that is safe for string equality.

But if you're going to enumerate alternatives like [[...]], you must inform also that the right-hand-side must be quoted. If not quoted, it is a pattern match! (From bash man page: "Any part of the pattern may be quoted to force it to be matched as a string.").

Here in bash, the two statements yielding "yes" are pattern matching, other three are string equality:

$ rht="A*"
$ lft="AB"
$ [ $lft = $rht ] && echo yes
$ [ $lft == $rht ] && echo yes
$ [[ $lft = $rht ]] && echo yes
yes
$ [[ $lft == $rht ]] && echo yes
yes
$ [[ $lft == "$rht" ]] && echo yes
$

Printing Lists as Tabular Data

Python actually makes this quite easy.

Something like

for i in range(10):
    print '%-12i%-12i' % (10 ** i, 20 ** i)

will have the output

1           1           
10          20          
100         400         
1000        8000        
10000       160000      
100000      3200000     
1000000     64000000    
10000000    1280000000  
100000000   25600000000
1000000000  512000000000

The % within the string is essentially an escape character and the characters following it tell python what kind of format the data should have. The % outside and after the string is telling python that you intend to use the previous string as the format string and that the following data should be put into the format specified.

In this case I used "%-12i" twice. To break down each part:

'-' (left align)
'12' (how much space to be given to this part of the output)
'i' (we are printing an integer)

From the docs: https://docs.python.org/2/library/stdtypes.html#string-formatting

How to set image in imageview in android?

Instead of setting drawable resource through code in your activity class you can also set in XML layout:

Code is as follows:

<ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/apple" />

JQuery Ajax Post results in 500 Internal Server Error

in case if someone using the codeigniter framework, the problem may be caused by the csrf protection config enabled.

Using git to get just the latest revision

Alternate solution to doing shallow clone (git clone --depth=1 <URL>) would be, if remote side supports it, to use --remote option of git archive:

$ git archive --format=tar --remote=<repository URL> HEAD | tar xf -

Or, if remote repository in question is browse-able using some web interface like gitweb or GitHub, then there is a chance that it has 'snapshot' feature, and you can download latest version (without versioning information) from web interface.

How to return XML in ASP.NET?

Below is the server side code that would call the handler and recieve the stream data and loads into xml doc

 Stream stream = null;
       **Create a web request with the specified URL**
        WebRequest myWebRequest = WebRequest.Create(@"http://localhost/XMLProvider/XMLProcessorHandler.ashx");
        **Senda a web request and wait for response.**
        WebResponse webResponse = myWebRequest.GetResponse();
        **Get the stream object from response object**
        stream = webResponse.GetResponseStream();

       XmlDocument xmlDoc = new XmlDocument();
      **Load stream data into xml**
       xmlDoc.Load(stream);

DateTime.MinValue and SqlDateTime overflow

Simply put, don't use DateTime.MinVaue as a default value.

There are a couple of different MinValues out there, depending which environment you are in.

I once had a project, where I was implementing a Windows CE project, I was using the Framework's DateTime.MinValue (year 0001), the database MinValue (1753) and a UI control DateTimePicker (i think it was 1970). So there were at least 3 different MinValues that were leading to strange behavior and unexpected results. (And I believe that there was even a fourth (!) version, I just do not recall where it came from.).

Use a nullable database field and change your value into a Nullable<DateTime> instead. Where there is no valid value in your code, there should not be a value in the database as well. :-)

What does localhost:8080 mean?

A TCP/IP connection is always made to an IP address (you can think of an IP-address as the address of a certain computer, even if that is not always the case) and a specific (logical, not physical) port on that address.

Usually one port is coupled to a specific process or "service" on the target computer. Some port numbers are standardized, like 80 for http, 25 for smtp and so on. Because of that standardization you usually don't need to put port numbers into your web adresses.

So if you say something like http://www.stackoverflow.com, the part "stackoverflow.com" resolves to an IP address (in my case 64.34.119.12) and because my browser knows the standard it tries to connect to port 80 on that address. Thus this is the same as http://www.stackoverflow.com:80.

But there is nothing that stops a process to listen for http requests on another port, like 12434, 4711 or 8080. Usually (as in your case) this is used for debugging purposes to not intermingle with another process (like IIS) already listening to port 80 on the same machine.

What's the best way to break from nested loops in JavaScript?

var str = "";
for (var x = 0; x < 3; x++) {
    (function() {  // here's an anonymous function
        for (var y = 0; y < 3; y++) {
            for (var z = 0; z < 3; z++) {
                // you have access to 'x' because of closures
                str += "x=" + x + "  y=" + y + "  z=" + z + "<br />";
                if (x == z && z == 2) {
                    return;
                }
            }
        }
    })();  // here, you execute your anonymous function
}

How's that? :)

How to get everything after a certain character?

The strpos() finds the offset of the underscore, then substr grabs everything from that index plus 1, onwards.

$data = "123_String";    
$whatIWant = substr($data, strpos($data, "_") + 1);    
echo $whatIWant;

If you also want to check if the underscore character (_) exists in your string before trying to get it, you can use the following:

if (($pos = strpos($data, "_")) !== FALSE) { 
    $whatIWant = substr($data, $pos+1); 
}

Should I add the Visual Studio .suo and .user files to source control?

You don't need to add these -- they contain per-user settings, and other developers won't want your copy.

Why does 'git commit' not save my changes?

if you have a subfolder, which was cloned from other git-Repository, first you have to remove the $.git$ file from the child-Repository: rm -rf .git after that you can change to parent folder and use git add -A.

How do I make a comment in a Dockerfile?

Use the # syntax for comments

From: https://docs.docker.com/engine/reference/builder/#format

# My comment here
RUN echo 'we are running some cool things'

Get JavaScript object from array of objects by value of property

Try Array filter method for filter the array of objects with property.

var jsObjects = [
   {a: 1, b: 2}, 
   {a: 3, b: 4}, 
   {a: 5, b: 6}, 
   {a: 7, b: 8}
];

using array filter method:

var filterObj = jsObjects.filter(function(e) {
  return e.b == 6;
});

using for in loop :

for (var i in jsObjects) {
  if (jsObjects[i].b == 6) {
    console.log(jsObjects[i]); // {a: 5, b: 6}
  }
}

Working fiddle : https://jsfiddle.net/uq9n9g77/

Tab separated values in awk

Make sure they're really tabs! In bash, you can insert a tab using C-v TAB

$ echo "LOAD_SETTLED    LOAD_INIT       2011-01-13 03:50:01" | awk -F$'\t' '{print $1}'
LOAD_SETTLED

Check if string contains only digits

String.prototype.isNumber = function(){return /^\d+$/.test(this);}
console.log("123123".isNumber()); // outputs true
console.log("+12".isNumber()); // outputs false

How do I delete everything in Redis?

There are different approaches. If you want to do this from remote, issue flushall to that instance, through command line tool redis-cli or whatever tools i.e. telnet, a programming language SDK. Or just log in that server, kill the process, delete its dump.rdb file and appendonly.aof(backup them before deletion).

Where to find 64 bit version of chromedriver.exe for Selenium WebDriver?

In the below mentioned link, ChromeDriver.exe for Windows 32 bit exist.

http://chromedriver.storage.googleapis.com/index.html?path=2.24/

It is working for me in Win7 64 bit.

How to write one new line in Bitbucket markdown?

Feb 3rd 2020:

  • Atlassian Bitbucket v5.8.3 local installation.
  • I wanted to add a new line around an horizontal line. --- did produce the line, but I could not get new lines to work with suggestions above.
  • note: I did not want to use the [space][space] suggestion, since my editor removes trailing spaces on save, and I like this feature on.

I ended up doing this:

TEXT...
<br><hr><br>
TEXT...

Resulting in:

TEXT...
<AN EMPTY LINE>
----------------- AN HORIZONTAL LINE ----------------
<AN EMPTY LINE>
TEXT...

How to set HTTP headers (for cache-control)?

OWASP recommends the following,

Whenever possible ensure the cache-control HTTP header is set with no-cache, no-store, must-revalidate, private; and that the pragma HTTP header is set with no-cache.

<IfModule mod_headers.c>
    Header set Cache-Control "private, no-cache, no-store, proxy-revalidate, no-transform"
    Header set Pragma "no-cache"
</IfModule>

Making href (anchor tag) request POST instead of GET?

To do POST you'll need to have a form.

<form action="employee.action" method="post">
    <input type="submit" value="Employee1" />
</form>

There are some ways to post data with hyperlinks, but you'll need some javascript, and a form.

Some tricks: Make a link use POST instead of GET and How do you post data with a link

Edit: to load response on a frame you can target your form to your frame:

<form action="employee.action" method="post" target="myFrame">

Foreign Key to multiple tables

You have a few options, all varying in "correctness" and ease of use. As always, the right design depends on your needs.

  • You could simply create two columns in Ticket, OwnedByUserId and OwnedByGroupId, and have nullable Foreign Keys to each table.

  • You could create M:M reference tables enabling both ticket:user and ticket:group relationships. Perhaps in future you will want to allow a single ticket to be owned by multiple users or groups? This design does not enforce that a ticket must be owned by a single entity only.

  • You could create a default group for every user and have tickets simply owned by either a true Group or a User's default Group.

  • Or (my choice) model an entity that acts as a base for both Users and Groups, and have tickets owned by that entity.

Heres a rough example using your posted schema:

create table dbo.PartyType
(   
    PartyTypeId tinyint primary key,
    PartyTypeName varchar(10)
)

insert into dbo.PartyType
    values(1, 'User'), (2, 'Group');


create table dbo.Party
(
    PartyId int identity(1,1) primary key,
    PartyTypeId tinyint references dbo.PartyType(PartyTypeId),
    unique (PartyId, PartyTypeId)
)

CREATE TABLE dbo.[Group]
(
    ID int primary key,
    Name varchar(50) NOT NULL,
    PartyTypeId as cast(2 as tinyint) persisted,
    foreign key (ID, PartyTypeId) references Party(PartyId, PartyTypeID)
)  

CREATE TABLE dbo.[User]
(
    ID int primary key,
    Name varchar(50) NOT NULL,
    PartyTypeId as cast(1 as tinyint) persisted,
    foreign key (ID, PartyTypeId) references Party(PartyID, PartyTypeID)
)

CREATE TABLE dbo.Ticket
(
    ID int primary key,
    [Owner] int NOT NULL references dbo.Party(PartyId),
    [Subject] varchar(50) NULL
)

.prop() vs .attr()

1) A property is in the DOM; an attribute is in the HTML that is parsed into the DOM.

2) $( elem ).attr( "checked" ) (1.6.1+) "checked" (String) Will change with checkbox state

3) $( elem ).attr( "checked" ) (pre-1.6) true (Boolean) Changed with checkbox state

  • Mostly we want to use for DOM object rather then custom attribute like data-img, data-xyz.

  • Also some of difference when accessing checkbox value and href with attr() and prop() as thing change with DOM output with prop() as full link from origin and Boolean value for checkbox (pre-1.6)

  • We can only access DOM elements with prop other then it gives undefined

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <title>prop demo</title>_x000D_
  <style>_x000D_
    p {_x000D_
      margin: 20px 0 0;_x000D_
    }_x000D_
    b {_x000D_
      color: blue;_x000D_
    }_x000D_
  </style>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
  <input id="check1" type="checkbox" checked="checked">_x000D_
  <label for="check1">Check me</label>_x000D_
  <p></p>_x000D_
_x000D_
  <script>_x000D_
    $("input").change(function() {_x000D_
      var $input = $(this);_x000D_
      $("p").html(_x000D_
        ".attr( \"checked\" ): <b>" + $input.attr("checked") + "</b><br>" +_x000D_
        ".prop( \"checked\" ): <b>" + $input.prop("checked") + "</b><br>" +_x000D_
        ".is( \":checked\" ): <b>" + $input.is(":checked")) + "</b>";_x000D_
    }).change();_x000D_
  </script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to copy a file to another path?

Old Question,but I would like to add complete Console Application example, considering you have files and proper permissions for the given folder, here is the code

 class Program
 {
    static void Main(string[] args)
    {
        //path of file
        string pathToOriginalFile = @"E:\C-sharp-IO\test.txt";

        
        //duplicate file path 
        string PathForDuplicateFile = @"E:\C-sharp-IO\testDuplicate.txt";
         
          //provide source and destination file paths
        File.Copy(pathToOriginalFile, PathForDuplicateFile);

        Console.ReadKey();

    }
}

Source: File I/O in C# (Read, Write, Delete, Copy file using C#)

Create list of single item repeated N times

Create List of Single Item Repeated n Times in Python

Depending on your use-case, you want to use different techniques with different semantics.

Multiply a list for Immutable items

For immutable items, like None, bools, ints, floats, strings, tuples, or frozensets, you can do it like this:

[e] * 4

Note that this is usually only used with immutable items (strings, tuples, frozensets, ) in the list, because they all point to the same item in the same place in memory. I use this frequently when I have to build a table with a schema of all strings, so that I don't have to give a highly redundant one to one mapping.

schema = ['string'] * len(columns)

Multiply the list where we want the same item repeated

Multiplying a list gives us the same elements over and over. The need for this is rare:

[iter(iterable)] * 4

This is sometimes used to map an iterable into a list of lists:

>>> iterable = range(12)
>>> a_list = [iter(iterable)] * 4
>>> [[next(l) for l in a_list] for i in range(3)]
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]

We can see that a_list contains the same range iterator four times:

>>> a_list
[<range_iterator object at 0x7fde73a5da20>, <range_iterator object at 0x7fde73a5da20>, <range_iterator object at 0x7fde73a5da20>, <range_iterator object at 0x7fde73a5da20>]

Mutable items

I've used Python for a long time now, and I have seen very few use-cases where I would do the above with mutable objects.

Instead, to get, say, a mutable empty list, set, or dict, you should do something like this:

list_of_lists = [[] for _ in columns]

The underscore is simply a throwaway variable name in this context.

If you only have the number, that would be:

list_of_lists = [[] for _ in range(4)]

The _ is not really special, but your coding environment style checker will probably complain if you don't intend to use the variable and use any other name.


Caveats for using the immutable method with mutable items:

Beware doing this with mutable objects, when you change one of them, they all change because they're all the same object:

foo = [[]] * 4
foo[0].append('x')

foo now returns:

[['x'], ['x'], ['x'], ['x']]

But with immutable objects, you can make it work because you change the reference, not the object:

>>> l = [0] * 4
>>> l[0] += 1
>>> l
[1, 0, 0, 0]

>>> l = [frozenset()] * 4
>>> l[0] |= set('abc')
>>> l
[frozenset(['a', 'c', 'b']), frozenset([]), frozenset([]), frozenset([])]

But again, mutable objects are no good for this, because in-place operations change the object, not the reference:

l = [set()] * 4
>>> l[0] |= set('abc')    
>>> l
[set(['a', 'c', 'b']), set(['a', 'c', 'b']), set(['a', 'c', 'b']), set(['a', 'c', 'b'])]

'ls' in CMD on Windows is not recognized

enter image description here

First

Make a dir c:\command

Second Make a ll.bat

ll.bat

dir

Third Add to Path C:/commands enter image description here

Mockito: Mock private field initialization

In case you use Spring Test try org.springframework.test.util.ReflectionTestUtils

 ReflectionTestUtils.setField(testObject, "person", mockedPerson);

$_POST not working. "Notice: Undefined index: username..."

undefined index means that somewhere in the $_POST array, there isn't an index (key) for the key username.

You should be setting your posted values into variables for a more clean solution, and it's a good habit to get into.

If I was having a similar error, I'd do something like this:

$username = $_POST['username']; // you should really do some more logic to see if it's set first
echo $username;

If username didn't turn up, that'd mean I was screwing up somewhere. You can also,

var_dump($_POST);

To see what you're posting. var_dump is really useful as far as debugging. Check it out: var_dump

How to sort multidimensional array by column?

below solution worked for me in case of required number is float. Solution:

table=sorted(table,key=lambda x: float(x[5]))
for row in table[:]:
    Ntable.add_row(row)

'

SQL Server IN vs. EXISTS Performance

There are many misleading answers answers here, including the highly upvoted one (although I don't believe their ops meant harm). The short answer is: These are the same.

There are many keywords in the (T-)SQL language, but in the end, the only thing that really happens on the hardware is the operations as seen in the execution query plan.

The relational (maths theory) operation we do when we invoke [NOT] IN and [NOT] EXISTS is the semi join (anti-join when using NOT). It is not a coincidence that the corresponding sql-server operations have the same name. There is no operation that mentions IN or EXISTS anywhere - only (anti-)semi joins. Thus, there is no way that a logically-equivalent IN vs EXISTS choice could affect performance because there is one and only way, the (anti)semi join execution operation, to get their results.

An example:

Query 1 ( plan )

select * from dt where dt.customer in (select c.code from customer c where c.active=0)

Query 2 ( plan )

select * from dt where exists (select 1 from customer c where c.code=dt.customer and c.active=0)

Incrementing a date in JavaScript

Timezone/daylight savings aware date increment for JavaScript dates:

function nextDay(date) {
    const sign = v => (v < 0 ? -1 : +1);
    const result = new Date(date.getTime());
    result.setDate(result.getDate() + 1);
    const offset = result.getTimezoneOffset();
    return new Date(result.getTime() + sign(offset) * offset * 60 * 1000);
}

java: run a function after a specific number of seconds

My code is as follows:

new java.util.Timer().schedule(

    new java.util.TimerTask() {
        @Override
        public void run() {
            // your code here, and if you have to refresh UI put this code: 
           runOnUiThread(new   Runnable() {
                  public void run() {
                            //your code

                        }
                   });
        }
    }, 
    5000 
);

cURL POST command line on WINDOWS RESTful service

I ran into the same issue on my win7 x64 laptop and was able to get it working using the curl release that is labeled Win64 - Generic w SSL by using the very similar command line format:

C:\Projects\curl-7.23.1-win64-ssl-sspi>curl -H "Content-Type: application/json" -X POST http://localhost/someapi -d "{\"Name\":\"Test Value\"}"

Which only differs from your 2nd escape version by using double-quotes around the escaped ones and the header parameter value. Definitely prefer the linux shell syntax more.

Where is the application.properties file in a Spring Boot project?

In the your first journey in spring boot project I recommend you to start with Spring Starter Try this link here.

enter image description here

It will auto generate the project structure for you like this.application.perperties it will be under /resources.

application.properties important change,

server.port = Your PORT(XXXX) by default=8080
server.servlet.context-path=/api (SpringBoot version 2.x.)
server.contextPath-path=/api (SpringBoot version < 2.x.)

Any way you can use application.yml in case you don't want to make redundancy properties setting.

Example
application.yml

server:
   port: 8080 
   contextPath: /api

application.properties

server.port = 8080
server.contextPath = /api

Start redis-server with config file

To start redis with a config file all you need to do is specifiy the config file as an argument:

redis-server /root/config/redis.rb

Instead of using and killing PID's I would suggest creating an init script for your service

I would suggest taking a look at the Installing Redis more properly section of http://redis.io/topics/quickstart. It will walk you through setting up an init script with redis so you can just do something like service redis_server start and service redis_server stop to control your server.

I am not sure exactly what distro you are using, that article describes instructions for a Debian based distro. If you are are using a RHEL/Fedora distro let me know, I can provide you with instructions for the last couple of steps, the config file and most of the other steps will be the same.

Bootstrap carousel width and height

I have created a responsive sample that works well for me and I find it to be quite simple have a look at my carousel-fill:

.carousel-fill {
    height: -o-calc(100vh - 165px) !important;
    height: -webkit-calc(100vh - 165px) !important;
    height: -moz-calc(100vh - 165px) !important;
    height: calc(100vh - 165px) !important;
    width: auto !important;
    overflow: hidden;
    display: inline-block;
    text-align: center;
}

.carousel-item {
    text-align: center !important;
}

my navigation height+footer are a hair less then 165px so that value works for me. take off a value that fits for you, I overrdide the .carousel-item from bootstrap so make sure by videos are centered.

my carousel looks like this, note the "carousel-fill" on the video tag.

<div>
        <div id="myCarousel" class="carousel slide carousel-fade text-center" data-ride="carousel">
            <!-- Indicators -->
            <ol class="carousel-indicators">
                <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
                <li data-target="#myCarousel" data-slide-to="1"></li>
                <li data-target="#myCarousel" data-slide-to="2"></li>
                <li data-target="#myCarousel" data-slide-to="3"></li>
            </ol>

            <!-- Wrapper for slides -->
            <div class="carousel-inner">
                <div class="carousel-item active">
                    <video autoplay muted class="carousel-fill">
                        <source src="~/Video/CATSTrade.mp4" type="video/mp4">
                        Your browser does not support the video tag.
                    </video>
                    <div class="carousel-caption">
                        <h2>CATS IV Trade engine</h2>
                        <p>Automated trading for high ROI</p>
                    </div>
                </div>
                <div class="carousel-item">
                    <video muted loop class="carousel-fill">
                        <source src="~/Video/itrs.mp4" type="video/mp4">
                    </video>
                    <div class="carousel-caption">
                        <h2>Machine learning</h2>
                        <p>Machine learning specialist</p>
                    </div>
                </div>
                <div class="carousel-item">
                    <video muted loop class="carousel-fill">
                        <source src="~/Video/frequency.mp4" type="video/mp4">
                    </video>
                    <div class="carousel-caption">
                        <h3>Low latency development</h3>
                        <p>Create ultra fast systems with our consultants</p>
                    </div>
                </div>
                <div class="carousel-item">
                    <img src="~/Images/data pipeline faded.png" class="carousel-fill" />

                    <div class="carousel-caption">
                        <h3>Big Data</h3>
                        <p>Maintain, generate, and host big data</p>
                    </div>
                </div>
            </div>

            <!-- Left and right controls -->
            <a class="carousel-control-prev" href="#myCarousel" data-slide="prev">
                <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                <span class="sr-only">Previous</span>
            </a>
            <a class="carousel-control-next" href="#myCarousel" data-slide="next">
                <span class="carousel-control-next-icon" aria-hidden="true"></span>
                <span class="sr-only">Next</span>
            </a>
        </div>
    </div>

in case some one needs to control the videos like i do, I start and stop the videos like this:

<script language="JavaScript" type="text/javascript">
        $(document).ready(function () {
            $('.carousel').carousel({ interval: 8000 })
            $('#myCarousel').on('slide.bs.carousel', function (args) {
                var videoList = document.getElementsByTagName("video");
                switch (args.from) {
                    case 0:
                        videoList[0].pause();
                        break;
                    case 1:
                        videoList[1].pause();
                        break;
                    case 2:
                        videoList[2].pause();
                        break;
                }
                switch (args.to) {
                    case 0:
                        videoList[0].play();

                        break;
                    case 1:
                        videoList[1].play();
                        break;
                    case 2:
                        videoList[2].play();
                        break;
                }
            })

        });
</script>

Android selector & text color

I got by doing several tests until one worked, so: res/color/button_dark_text.xml

<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true"
           android:color="#000000" /> <!-- pressed -->
     <item android:state_focused="true"
           android:color="#000000" /> <!-- focused -->
     <item android:color="#FFFFFF" /> <!-- default -->
 </selector>

res/layout/view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   >
    <Button
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="EXIT"
       android:textColor="@color/button_dark_text" />
</LinearLayout>

Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails

Many of the other answers pertain to settings in the various config files, and the ones pertaining to the pg_hba.conf do apply and are 100% correct. However, make sure you are modifying the correct config files.

As others have mentioned the config file locations can be overridden with various settings inside the main config file, as well as supplying a path to the main config file on the command line with the -D option.

You can use the following command while in a psql session to show where your config files are being read (assuming you can launch psql). This is just a troubleshooting step that can help some people:

select * from pg_settings where setting~'pgsql';  

You should also make sure that the home directory for your postgres user is where you expect it to be. I say this because it is quite easy to overlook this due to the fact that your prompt will display '~' instead of the actual path of your home directory, making it not so obvious. Many installations default the postgres user home directory to /var/lib/pgsql.

If it is not set to what it is supposed to be, stop the postgresql service and use the following command while logged in as root. Also make sure the postgres user is not logged into another session:

usermod -d /path/pgsql postgres

Finally make sure your PGDATA variable is set correctly by typing echo $PGDATA, which should output something similar to:

/path/pgsql/data

If it is not set, or shows something different from what you expect it to be, examine your startup or RC files such as .profile or .bash.rc - this will vary greatly depending on your OS and your shell. Once you have determined the correct startup script for your machine, you can insert the following:

export PGDATA=/path/pgsql/data

For my system, I placed this in /etc/profile.d/profile.local.sh so it was accessible for all users.

You should now be able to init the database as usual and all your psql path settings should be correct!

How to detect if numpy is installed

I think you also may use this

>> import numpy
>> print numpy.__version__

Update: for python3 use print(numpy.__version__)

ORA-00972 identifier is too long alias column name

I'm using Argos reporting system as a front end and Oracle in back. I just encountered this error and it was caused by a string with a double quote at the start and a single quote at the end. Replacing the double quote with a single solved the issue.

How can I find non-ASCII characters in MySQL?

It depends exactly what you're defining as "ASCII", but I would suggest trying a variant of a query like this:

SELECT * FROM tableName WHERE columnToCheck NOT REGEXP '[A-Za-z0-9]';

That query will return all rows where columnToCheck contains any non-alphanumeric characters. If you have other characters that are acceptable, add them to the character class in the regular expression. For example, if periods, commas, and hyphens are OK, change the query to:

SELECT * FROM tableName WHERE columnToCheck NOT REGEXP '[A-Za-z0-9.,-]';

The most relevant page of the MySQL documentation is probably 12.5.2 Regular Expressions.

Why do I get PLS-00302: component must be declared when it exists?

I came here because I had the same problem.
What was the problem for me was that the procedure was defined in the package body, but not in the package header.
I was executing my function with a lose BEGIN END statement.

Bypass invalid SSL certificate errors when calling web services in .Net

I solved it this way:

Call the following just before calling your ssl webservice that cause that error:

using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

/// <summary>
/// solution for exception
/// System.Net.WebException: 
/// The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
/// </summary>
public static void BypassCertificateError()
{
    ServicePointManager.ServerCertificateValidationCallback +=

        delegate(
            Object sender1,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors)
        {
            return true;
        };
}

How to suppress Pandas Future warning ?

Warnings are annoying. As mentioned in other answers, you can suppress them using:

import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

But if you want to handle them one by one and you are managing a bigger codebase, it will be difficult to find the line of code which is causing the warning. Since warnings unlike errors don't come with code traceback. In order to trace warnings like errors, you can write this at the top of the code:

import warnings
warnings.filterwarnings("error")

But if the codebase is bigger and it is importing bunch of other libraries/packages, then all sort of warnings will start to be raised as errors. In order to raise only certain type of warnings (in your case, its FutureWarning) as error, you can write:

import warnings
warnings.simplefilter(action='error', category=FutureWarning)

How can I find the first occurrence of a sub-string in a python string?

def find_pos(chaine,x):

    for i in range(len(chaine)):
        if chaine[i] ==x :
            return 'yes',i 
    return 'no'

How to play an android notification sound

I had pretty much the same question. After some research, I think that if you want to play the default system "notification sound", you pretty much have to display a notification and tell it to use the default sound. And there's something to be said for the argument in some of the other answers that if you're playing a notification sound, you should be presenting some notification message as well.

However, a little tweaking of the notification API and you can get close to what you want. You can display a blank notification and then remove it automatically after a few seconds. I think this will work for me; maybe it will work for you.

I've created a set of convenience methods in com.globalmentor.android.app.Notifications.java which allow you create a notification sound like this:

Notifications.notify(this);

The LED will also flash and, if you have vibrate permission, a vibration will occur. Yes, a notification icon will appear in the notification bar but will disappear after a few seconds.

At this point you may realize that, since the notification will go away anyway, you might as well have a scrolling ticker message in the notification bar; you can do that like this:

Notifications.notify(this, 5000, "This text will go away after five seconds.");

There are many other convenience methods in this class. You can download the whole library from its Subversion repository and build it with Maven. It depends on the globalmentor-core library, which can also be built and installed with Maven.

How to export table as CSV with headings on Postgresql?

instead of just table name, you can also write a query for getting only selected column data.

COPY (select id,name from tablename) TO 'filepath/aa.csv' DELIMITER ',' CSV HEADER;

with admin privilege

\COPY (select id,name from tablename) TO 'filepath/aa.csv' DELIMITER ',' CSV HEADER;

How can I define colors as variables in CSS?

CSS itself doesn't use variables. However, you can use another language like SASS to define your styling using variables, and automatically produce CSS files, which you can then put up on the web. Note that you would have to re-run the generator every time you made a change to your CSS, but that isn't so hard.

How to edit an Android app?

You would need to decompile the apk as Davis suggested, can use tools such as apkTool , then if you need to change the source code you would need other tools to do that.

You would then need to put the apk back together and sign it, if you don't have the original key used to sign the apk this means the new apk will have a different signature.

If the developer employed any obfuscation or other techniques to protect the app then it gets more complicated.

In short its a pretty complex and technical procedure, so if the developer is really just out of reach, its better to wait until he is in reach. And ask for the source code next time.

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

If you have run php artisan config:cache on your server, then your Laravel app could cache outdated config settings that you've put in the .env file.

Run php artisan config:clear to fix that.

psql - save results of command to a file

This approach will work with any psql command from the simplest to the most complex without requiring any changes or adjustments to the original command.

NOTE: For Linux servers.


  • Save the contents of your command to a file

MODEL

read -r -d '' FILE_CONTENT << 'HEREDOC'
[COMMAND_CONTENT]

HEREDOC
echo -n "$FILE_CONTENT" > sqlcmd

EXAMPLE

read -r -d '' FILE_CONTENT << 'HEREDOC'
DO $f$
declare
    curid INT := 0;
    vdata BYTEA;
    badid VARCHAR;
    loc VARCHAR;
begin
FOR badid IN SELECT some_field FROM public.some_base LOOP
    begin
    select 'ctid - '||ctid||'pagenumber - '||(ctid::text::point) [0]::bigint
        into loc
        from public.some_base where some_field = badid;
        SELECT file||' '
        INTO vdata
        FROM public.some_base where some_field = badid;
    exception
        when others then
        raise notice 'Block/PageNumber - % ',loc;
            raise notice 'Corrupted id - % ', badid;
            --return;
    end;
end loop;
end;
$f$;

HEREDOC
echo -n "$FILE_CONTENT" > sqlcmd
  • Run the command

MODEL

sudo -u postgres psql [some_db] -c "$(cat sqlcmd)" >>sqlop 2>&1

EXAMPLE

sudo -u postgres psql some_db -c "$(cat sqlcmd)" >>sqlop 2>&1

  • View/track your command output

cat sqlop

Done! Thanks! =D

Git 'fatal: Unable to write new index file'

did you try 'git add .' . will it all the changes? (you can remove unnecessary added files by git reset HEAD )

How do I use DateTime.TryParse with a Nullable<DateTime>?

As Jason says, you can create a variable of the right type and pass that. You might want to encapsulate it in your own method:

public static DateTime? TryParse(string text)
{
    DateTime date;
    if (DateTime.TryParse(text, out date))
    {
        return date;
    }
    else
    {
        return null;
    }
}

... or if you like the conditional operator:

public static DateTime? TryParse(string text)
{
    DateTime date;
    return DateTime.TryParse(text, out date) ? date : (DateTime?) null;
}

Or in C# 7:

public static DateTime? TryParse(string text) =>
    DateTime.TryParse(text, out var date) ? date : (DateTime?) null;

How can I specify a local gem in my Gemfile?

In addition to specifying the path (as Jimmy mentioned) you can also force Bundler to use a local gem for your environment only by using the following configuration option:

$ bundle config local.GEM_NAME /path/to/local/git/repository

This is extremely helpful if you're developing two gems or a gem and a rails app side-by-side.

Note though, that this only works when you're already using git for your dependency, for example:

# In Gemfile
gem 'rack', :github => 'rack/rack', :branch => 'master'

# In your terminal
$ bundle config local.rack ~/Work/git/rack

As seen on the docs.

How can you check for a #hash in a URL using JavaScript?

Throwing this in here as a method for abstracting location properties from arbitrary URI-like strings. Although window.location instanceof Location is true, any attempt to invoke Location will tell you that it's an illegal constructor. You can still get to things like hash, query, protocol etc by setting your string as the href property of a DOM anchor element, which will then share all the address properties with window.location.

Simplest way of doing this is:

var a = document.createElement('a');
a.href = string;

string.hash;

For convenience, I wrote a little library that utilises this to replace the native Location constructor with one that will take strings and produce window.location-like objects: Location.js

Merge two (or more) lists into one, in C# .NET

you can combine them using LINQ:

  list = list1.Concat(list2).Concat(list3).ToList();

the more traditional approach of using List.AddRange() might be more efficient though.

Git branching: master vs. origin/master vs. remotes/origin/master

I would try to make @ErichBSchulz's answer simpler for beginners:

  • origin/master is the state of master branch on remote repository
  • master is the state of master branch on local repository

In Python, how do I loop through the dictionary and change the value if it equals something?

You could create a dict comprehension of just the elements whose values are None, and then update back into the original:

tmp = dict((k,"") for k,v in mydict.iteritems() if v is None)
mydict.update(tmp)

Update - did some performance tests

Well, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.

Replace all non-alphanumeric characters in a string

Try:

s = filter(str.isalnum, s)

in Python3:

s = ''.join(filter(str.isalnum, s))

Edit: realized that the OP wants to replace non-chars with '*'. My answer does not fit

How to capture multiple repeated groups?

You actually have one capture group that will match multiple times. Not multiple capture groups.

javascript (js) solution:

let string = "HI,THERE,TOM";
let myRegexp = /([A-Z]+),?/g;       //modify as you like
let match = myRegexp.exec(string);  //js function, output described below
while(match!=null){                 //loops through matches
    console.log(match[1]);          //do whatever you want with each match
    match = myRegexp.exec(bob);     //find next match
}

Output:

HI
THERE
TOM

Syntax:

// matched text: match[0]
// match start: match.index
// capturing group n: match[n]

As you can see, this will work for any number of matches.

How to sort a list of strings?

It is simple: https://trinket.io/library/trinkets/5db81676e4

scores = '54 - Alice,35 - Bob,27 - Carol,27 - Chuck,05 - Craig,30 - Dan,27 - Erin,77 - Eve,14 - Fay,20 - Frank,48 - Grace,61 - Heidi,03 - Judy,28 - Mallory,05 - Olivia,44 - Oscar,34 - Peggy,30 - Sybil,82 - Trent,75 - Trudy,92 - Victor,37 - Walter'

scores = scores.split(',') for x in sorted(scores): print(x)

How do I connect to a MySQL Database in Python?

first install the driver

pip install MySQL-python   

Then a basic code goes like this:

#!/usr/bin/python
import MySQLdb

try:
    db = MySQLdb.connect(host="localhost",      # db server, can be a remote one 
                     db="mydb"                  # database
                     user="mydb",               # username
                     passwd="mydb123",          # password for this username
                     )        

    # Create a Cursor object
    cur = db.cursor()

    # Create a query string. It can contain variables
    query_string = "SELECT * FROM MY_TABLE"

    # Execute the query
    cur.execute(query_string)

    # Get all the rows present the database
    for each_row in cur.fetchall():
        print each_row

    # Close the connection
    db.close()
except Exception, e:
    print 'Error ', e 

Node.js setting up environment specific configs to be used with everyauth

In brief

This kind of a setup is simple and elegant :

env.json

{
  "development": {
      "facebook_app_id": "facebook_dummy_dev_app_id",
      "facebook_app_secret": "facebook_dummy_dev_app_secret",
  }, 
  "production": {
      "facebook_app_id": "facebook_dummy_prod_app_id",
      "facebook_app_secret": "facebook_dummy_prod_app_secret",
  }
}

common.js

var env = require('env.json');

exports.config = function() {
  var node_env = process.env.NODE_ENV || 'development';
  return env[node_env];
};

app.js

var common = require('./routes/common')
var config = common.config();

var facebook_app_id = config.facebook_app_id;
// do something with facebook_app_id

To run in production mode : $ NODE_ENV=production node app.js


In detail

This solution is from : http://himanshu.gilani.info/blog/2012/09/26/bootstraping-a-node-dot-js-app-for-dev-slash-prod-environment/, check it out for more detail.

Python basics printing 1 to 100

because if you change your code with

def gukan(count):
    while count!=100:
      print(count)
      count=count+3;
gukan(0)

count reaches 99 and then, at the next iteration 102.

So

count != 100

never evaluates true and the loop continues forever

If you want to count up to 100 you may use

def gukan(count):
    while count <= 100:
      print(count)
      count=count+3;
gukan(0)

or (if you want 100 always printed)

def gukan(count):
    while count <= 100:
      print(count)
      count=count+3;
      if count > 100:
          count = 100
gukan(0)

Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

As for your update, I was confused for the reasoning behind in. Dug a little deeper and found this gem:

  • yoursite.com becomes yoursite.com/
  • yoursite.com/ is a directory, so the welcome-file-list is scanned
  • yoursite.com/CMS is the first welcome-file ("CMS" in the welcome-file-list), and there is a mapping of /CMS to the MyCMS servlet, so that servlet is accessed.

Source: http://wiki.metawerx.net/wiki/HowToUseAServletAsYourMainWebPage

So, the mapping then does make sense.

And one can now freely use ${pageContext.request.contextPath}/path/ as src/href for relative links!

Django check for any exists for a query

As of Django 1.2, you can use exists():

https://docs.djangoproject.com/en/dev/ref/models/querysets/#exists

if some_queryset.filter(pk=entity_id).exists():
    print("Entry contained in queryset")

Check whether number is even or odd

if((x%2)==0)
   // even
else
   // odd

Maximize a window programmatically and prevent the user from changing the windows state

When your form is maximized, set its minimum size = max size, so user cannot resize it.

    this.WindowState = FormWindowState.Maximized;
    this.MinimumSize = this.Size;
    this.MaximumSize = this.Size;

How to make a div center align in HTML

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <head>_x000D_
    <title>Center</title>_x000D_
  </head>_x000D_
  <body>_x000D_
_x000D_
    <div style="text-align: center;">_x000D_
      <div style="width: 500px; margin: 0 auto; background: #000; color: #fff;">This DIV is centered</div>_x000D_
    </div>_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Tested and worked in IE, Firefox, Chrome, Safari and Opera. I did not test IE6. The outer text-align is needed for IE. Other browsers (and IE9?) will work when you give the DIV margin (left and right) value of auto. Margin "0 auto" is a shorthand for margin "0 auto 0 auto" (top right bottom left).

Note: the text is also centered inside the inner DIV, if you want it to remain on the left side just specify text-align: left; for the inner DIV.

Edit: IE 6, 7, 8 and 9 running on the Standards Mode will work with margins set to auto.

Fastest method to escape HTML tags as HTML entities?

Martijn's method as a prototype function:

String.prototype.escape = function() {
    var tagsToReplace = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;'
    };
    return this.replace(/[&<>]/g, function(tag) {
        return tagsToReplace[tag] || tag;
    });
};

var a = "<abc>";
var b = a.escape(); // "&lt;abc&gt;"

How to create custom config section in app.config?

Import namespace :

using System.Configuration;

Create ConfigurationElement Company :

public class Company : ConfigurationElement
{

        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return this["name"] as string;
            }
        }
            [ConfigurationProperty("code", IsRequired = true)]
        public string Code
        {
            get
            {
                return this["code"] as string;
            }
        }
}

ConfigurationElementCollection:

public class Companies
        : ConfigurationElementCollection
    {
        public Company this[int index]
        {
            get
            {
                return base.BaseGet(index) as Company ;
            }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }

       public new Company this[string responseString]
       {
            get { return (Company) BaseGet(responseString); }
            set
            {
                if(BaseGet(responseString) != null)
                {
                    BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
                }
                BaseAdd(value);
            }
        }

        protected override System.Configuration.ConfigurationElement CreateNewElement()
        {
            return new Company();
        }

        protected override object GetElementKey(System.Configuration.ConfigurationElement element)
        {
            return ((Company)element).Name;
        }
    }

and ConfigurationSection:

public class RegisterCompaniesConfig
        : ConfigurationSection
    {

        public static RegisterCompaniesConfig GetConfig()
        {
            return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
        }

        [System.Configuration.ConfigurationProperty("Companies")]
            [ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
        public Companies Companies
        {
            get
            {
                object o = this["Companies"];
                return o as Companies ;
            }
        }

    }

and you must also register your new configuration section in web.config (app.config):

<configuration>       
    <configSections>
          <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>

then you load your config with

var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
   do something ..
}

Html.DropdownListFor selected value not being set

Make sure that you have trim the selected value before you assigning.

//Model

public class SelectType
{
    public string Text { get; set; }
    public string Value { get; set; }
}

//Controller

var types = new List<SelectType>();
types.Add(new SelectType() { Value =  0, Text = "Select a Type" });
types.Add(new SelectType() { Value =  1, Text = "Family Trust" });
types.Add(new SelectType() { Value =  2, Text = "Unit Trust"});
ViewBag.PartialTypes = types;

//View

@Html.DropDownListFor(m => m.PartialType, new SelectList(ViewBag.PartialTypes, "Value", "Text"), new { id = "Type" })

Format numbers in JavaScript similar to C#

You can do it in the following way: So you will not only format the number but you can also pass as a parameter how many decimal digits to display, you set a custom decimal and mile separator.

function format(number, decimals = 2, decimalSeparator = '.', thousandsSeparator = ',') {
    const roundedNumber = number.toFixed(decimals);
    let integerPart = '', fractionalPart = '';
    if (decimals == 0) {
        integerPart = roundedNumber;
        decimalSeparator = '';
    } else {
        let numberParts = roundedNumber.split('.');
        integerPart = numberParts[0];
        fractionalPart = numberParts[1];
    }
    integerPart = integerPart.replace(/(\d)(?=(\d{3})+(?!\d))/g, `$1${thousandsSeparator}`);
    return `${integerPart}${decimalSeparator}${fractionalPart}`;
}

Use:

let min = 1556454.0001;
let max = 15556982.9999;
console.time('number format');
for (let i = 0; i < 15000; i++) {
    let randomNumber = Math.random() * (max - min) + min;

    let formated = format(randomNumber, 4, ',', '.'); // formated number

    console.debug('number: ', randomNumber, 'formated: ', formated);
}
console.timeEnd('number format');

No connection could be made because the target machine actively refused it (PHP / WAMP)

Just Go to your Control-panel and start Apache & MySQL Services.

CSS Animation onClick

You just use the :active pseudo-class. This is set when you click on any element.

.classname:active {
    /* animation css */
}

How to properly upgrade node using nvm

You can more simply run one of the following commands:

Latest version:
nvm install node --reinstall-packages-from=node
Stable (LTS) version:
nvm install lts/* --reinstall-packages-from=node

This will install the appropriate version and reinstall all packages from the currently used node version. This saves you from manually handling the specific versions.

Edit - added command for installing LTS version according to @m4js7er comment.

Getting year in moment.js

The year() function just retrieves the year component of the underlying Date object, so it returns a number.

Calling format('YYYY') will invoke moment's string formatting functions, which will parse the format string supplied, and build a new string containing the appropriate data. Since you only are passing YYYY, then the result will be a string containing the year.

If all you need is the year, then use the year() function. It will be faster, as there is less work to do.

Do note that while years are the same in this regard, months are not! Calling format('M') will return months in the range 1-12. Calling month() will return months in the range 0-11. This is due to the same behavior of the underlying Date object.

Can an html element have multiple ids?

http://www.w3.org/TR/REC-html40/struct/global.html#h-7.5.2

The id attribute assigns a unique identifier to an element (which may be verified by an SGML parser).

and

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

So "id" must be unique and can't contain a space.

Passing the argument to CMAKE via command prompt

In the CMakeLists.txt file, create a cache variable, as documented here:

SET(FAB "po" CACHE STRING "Some user-specified option")

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#command:set

Then, either use the GUI (ccmake or cmake-gui) to set the cache variable, or specify the value of the variable on the cmake command line:

cmake -DFAB:STRING=po

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#opt:-Dvar:typevalue

Modify your cache variable to a boolean if, in fact, your option is boolean.

Rails: update_attribute vs update_attributes

Great answers. notice that as for ruby 1.9 and above you could (and i think should) use the new hash syntax for update_attributes:

Model.update_attributes(column1: "data", column2: "data")

How to create named and latest tag in Docker?

You can have multiple tags when building the image:

$ docker build -t whenry/fedora-jboss:latest -t whenry/fedora-jboss:v2.1 .

Reference: https://docs.docker.com/engine/reference/commandline/build/#tag-image-t

Gradle task - pass arguments to Java application

If you want to use the same set of arguments all the time, the following is all you need.

run {
    args = ["--myarg1", "--myarg2"]
}

How to show an alert box in PHP?

echo "<script>alert('same message');</script>";

This may help.

Python class inherits object

Python 3

  • class MyClass(object): = New-style class
  • class MyClass: = New-style class (implicitly inherits from object)

Python 2

  • class MyClass(object): = New-style class
  • class MyClass: = OLD-STYLE CLASS

Explanation:

When defining base classes in Python 3.x, you’re allowed to drop the object from the definition. However, this can open the door for a seriously hard to track problem…

Python introduced new-style classes back in Python 2.2, and by now old-style classes are really quite old. Discussion of old-style classes is buried in the 2.x docs, and non-existent in the 3.x docs.

The problem is, the syntax for old-style classes in Python 2.x is the same as the alternative syntax for new-style classes in Python 3.x. Python 2.x is still very widely used (e.g. GAE, Web2Py), and any code (or coder) unwittingly bringing 3.x-style class definitions into 2.x code is going to end up with some seriously outdated base objects. And because old-style classes aren’t on anyone’s radar, they likely won’t know what hit them.

So just spell it out the long way and save some 2.x developer the tears.

What is the difference between __str__ and __repr__?

__repr__ is used everywhere, except by print and str methods (when a __str__is defined !)

How to select a single column with Entity Framework?

You can use LINQ's .Select() to do that. In your case it would go something like:

string Name = yourDbContext
  .MyTable
  .Where(u => u.UserId == 1)
  .Select(u => u.Name)
  .SingleOrDefault(); // This is what actually executes the request and return a response

If you are expecting more than one entry in response, you can use .ToList() instead, to execute the request. Something like this, to get the Name of everyone with age 30:

string[] Names = yourDbContext
  .MyTable
  .Where(u => u.Age == 30)
  .Select(u => u.Name)
  .ToList();

Is this how you define a function in jQuery?

That is how you define an anonymous function that gets called when the document is ready.

How to do sed like text replace with python?

You could do something like:

p = re.compile("^\# *deb", re.MULTILINE)
text = open("sources.list", "r").read()
f = open("sources.list", "w")
f.write(p.sub("deb", text))
f.close()

Alternatively (imho, this is better from organizational standpoint) you could split your sources.list into pieces (one entry/one repository) and place them under /etc/apt/sources.list.d/

Change HTML email body font type and size in VBA

FYI I did a little research as well and if the name of the font-family you want to apply contains spaces (as an example I take Gill Alt One MT Light), you should write it this way :

strbody= "<BODY style=" & Chr(34) & "font-family:Gill Alt One MT Light" & Chr(34) & ">" & YOUR_TEXT & "</BODY>"

Set a DateTime database field to "Now"

An alternative to GETDATE() is CURRENT_TIMESTAMP. Does the exact same thing.

How to get length of a list of lists in python

"The above text file used has 3 lines of 4 elements separated by commas. The variable numLines prints out as '4' not '3'. So, len(myLines) is returning the number of elements in each list not the length of the list of lists."

It sounds like you're reading in a .csv with 3 rows and 4 columns. If this is the case, you can find the number of rows and lines by using the .split() method:

text = open("filetest.txt", "r").read()
myRows = text.split("\n")      #this method tells Python to split your filetest object each time it encounters a line break 
print len(myRows)              #will tell you how many rows you have
for row in myRows:
  myColumns = row.split(",")   #this method will consider each of your rows one at a time. For each of those rows, it will split that row each time it encounters a comma.  
  print len(myColumns)         #will tell you, for each of your rows, how many columns that row contains

How to execute XPath one-liners from shell?

One package that is very likely to be installed on a system already is python-lxml. If so, this is possible without installing any extra package:

python -c "from lxml.etree import parse; from sys import stdin; print('\n'.join(parse(stdin).xpath('//element/@attribute')))"

How do I update a GitHub forked repository?

If, like me, you never commit anything directly to master, which you should really, you can do the following.

From the local clone of your fork, create your upstream remote. You only need to do that once:

git remote add upstream https://github.com/whoever/whatever.git

Then whenever you want to catch up with the upstream repository master branch you need to:

git checkout master
git pull upstream master

Assuming you never committed anything on master yourself you should be done already. Now you can push your local master to your origin remote GitHub fork. You could also rebase your development branch on your now up-to-date local master.

Past the initial upstream setup and master checkout, all you need to do is run the following command to sync your master with upstream: git pull upstream master.

How to check if ping responded or not in a batch file

I know this is an old thread, but I wanted to test if a machine was up on my system and unless I have misunderstood, none of the above works if my router reports that an address is unreachable. I am using a batch file rather than a script because I wanted to "KISS" on pretty much any WIN machine. So the approach I used was to do more than one ping and test for "Lost = 0" as follows

ping -n 2 %pingAddr% | find /I "Lost = 0"  
if %errorlevel% == 0 goto OK

I haven't tested this rigorously but so far it does the job for me

Remove last character from string. Swift language

Short answer (valid as of 2015-04-16): removeAtIndex(myString.endIndex.predecessor())

Example:

var howToBeHappy = "Practice compassion, attention and gratitude. And smile!!"
howToBeHappy.removeAtIndex(howToBeHappy.endIndex.predecessor())
println(howToBeHappy)
// "Practice compassion, attention and gratitude. And smile!"

Meta:

The language continues its rapid evolution, making the half-life for many formerly-good S.O. answers dangerously brief. It's always best to learn the language and refer to real documentation.

Increment a value in Postgres

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill';

If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill'
  AND total = 203;

Convert a object into JSON in REST service by Spring MVC

You can always add the @Produces("application/json") above your web method or specify produces="application/json" to return json. Then on top of the Student class you can add @XmlRootElement from javax.xml.bind.annotation package.

Please note, it might not be a good idea to directly return model classes. Just a suggestion.

HTH.

Use jQuery to scroll to the bottom of a div with lots of text

Make a jQuery function more flexible.

$.fn.scrollDown=function(){
    let el=$(this)
    el.scrollTop(el[0].scrollHeight)
}

$('div').scrollDown()

https://jsfiddle.net/Thielicious/82ar7db2/

How to print last two columns using awk

You can make use of variable NF which is set to the total number of fields in the input record:

awk '{print $(NF-1),"\t",$NF}' file

this assumes that you have at least 2 fields.

Import txt file and having each line as a list

with open('path/to/file') as infile: # try open('...', 'rb') as well
    answer = [line.strip().split(',') for line in infile]

If you want the numbers as ints:

with open('path/to/file') as infile:
    answer = [[int(i) for i in line.strip().split(',')] for line in infile]

Python regex findall

import re
regex = ur"\[P\] (.+?) \[/P\]+?"
line = "President [P] Barack Obama [/P] met Microsoft founder [P] Bill Gates [/P], yesterday."
person = re.findall(regex, line)
print(person)

yields

['Barack Obama', 'Bill Gates']

The regex ur"[\u005B1P\u005D.+?\u005B\u002FP\u005D]+?" is exactly the same unicode as u'[[1P].+?[/P]]+?' except harder to read.

The first bracketed group [[1P] tells re that any of the characters in the list ['[', '1', 'P'] should match, and similarly with the second bracketed group [/P]].That's not what you want at all. So,

  • Remove the outer enclosing square brackets. (Also remove the stray 1 in front of P.)
  • To protect the literal brackets in [P], escape the brackets with a backslash: \[P\].
  • To return only the words inside the tags, place grouping parentheses around .+?.

Finding three elements in an array whose sum is closest to a given number

Program to get those three elements. I have just sorted the array/list first and them updated minCloseness based upon each triplet.

public int[] threeSumClosest(ArrayList<Integer> A, int B) {
    Collections.sort(A);
    int ansSum = 0;
    int ans[] = new int[3];
    int minCloseness = Integer.MAX_VALUE;
    for (int i = 0; i < A.size()-2; i++){
        int j = i+1;
        int k = A.size()-1;
        while (j < k){
            int sum = A.get(i) + A.get(j) + A.get(k);
            if (sum < B){
                j++;
            }else{
                k--;
            }
            if (minCloseness >  Math.abs(sum - B)){
                minCloseness = Math.abs(sum - B);
                ans[0] = A.get(i); ans[1] = A.get(j); ans[2] = A.get(k);
            }
        }
    }
    return ans;
}

Python xml ElementTree from a string source?

io.StringIO is another option for getting XML into xml.etree.ElementTree:

import io
f = io.StringIO(xmlstring)
tree = ET.parse(f)
root = tree.getroot()

Hovever, it does not affect the XML declaration one would assume to be in tree (although that's needed for ElementTree.write()). See How to write XML declaration using xml.etree.ElementTree.

How do you get the string length in a batch file?

@echo off & setlocal EnableDelayedExpansion
set Var=finding the length of strings
for /l %%A in (0,1,10000) do if not "%Var%"=="!Var:~0,%%A!" (set /a Length+=1) else (echo !Length! & pause & exit /b)

set the var to whatever you want to find the length of it or change it to set /p var= so that the user inputs it. Putting this here for future reference.

What is a blob URL and why it is used?

This Javascript function purports to show the difference between the Blob File API and the Data API to download a JSON file in the client browser:

_x000D_
_x000D_
/**_x000D_
 * Save a text as file using HTML <a> temporary element and Blob_x000D_
 * @author Loreto Parisi_x000D_
 */_x000D_
_x000D_
var saveAsFile = function(fileName, fileContents) {_x000D_
    if (typeof(Blob) != 'undefined') { // Alternative 1: using Blob_x000D_
        var textFileAsBlob = new Blob([fileContents], {type: 'text/plain'});_x000D_
        var downloadLink = document.createElement("a");_x000D_
        downloadLink.download = fileName;_x000D_
        if (window.webkitURL != null) {_x000D_
            downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);_x000D_
        } else {_x000D_
            downloadLink.href = window.URL.createObjectURL(textFileAsBlob);_x000D_
            downloadLink.onclick = document.body.removeChild(event.target);_x000D_
            downloadLink.style.display = "none";_x000D_
            document.body.appendChild(downloadLink);_x000D_
        }_x000D_
        downloadLink.click();_x000D_
    } else { // Alternative 2: using Data_x000D_
        var pp = document.createElement('a');_x000D_
        pp.setAttribute('href', 'data:text/plain;charset=utf-8,' +_x000D_
            encodeURIComponent(fileContents));_x000D_
        pp.setAttribute('download', fileName);_x000D_
        pp.onclick = document.body.removeChild(event.target);_x000D_
        pp.click();_x000D_
    }_x000D_
} // saveAsFile_x000D_
_x000D_
/* Example */_x000D_
var jsonObject = {"name": "John", "age": 30, "car": null};_x000D_
saveAsFile('out.json', JSON.stringify(jsonObject, null, 2));
_x000D_
_x000D_
_x000D_

The function is called like saveAsFile('out.json', jsonString);. It will create a ByteStream immediately recognized by the browser that will download the generated file directly using the File API URL.createObjectURL.

In the else, it is possible to see the same result obtained via the href element plus the Data API, but this has several limitations that the Blob API has not.

How to check if a String contains any letter from a to z?

What about:

//true if it doesn't contain letters
bool result = hello.Any(x => !char.IsLetter(x));

How to create a folder with name as current date in batch (.bat) files

This works for me, try:

ECHO %DATE:~7,2%_%DATE:~4,2%_%DATE:~12,2%

Reset select2 value and show placeholder

Use this :

$('.select').val([]).trigger('change');

What is the difference between "expose" and "publish" in Docker?

You expose ports using the EXPOSE keyword in the Dockerfile or the --expose flag to docker run. Exposing ports is a way of documenting which ports are used, but does not actually map or open any ports. Exposing ports is optional.

Source: github commit

Make <body> fill entire screen?

I had to apply 100% to both html and body.

How do I replace whitespaces with underscore?

You can try this instead:

mystring.replace(r' ','-')

alter the size of column in table containing data

Case 1 : Yes, this works fine.

Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.

Share and enjoy.

How do I make a Mac Terminal pop-up/alert? Applescript?

This would restore focus to the previous application and exit the script if the answer was empty.

a=$(osascript -e 'try
tell app "SystemUIServer"
set answer to text returned of (display dialog "" default answer "")
end
end
activate app (path to frontmost application as text)
answer' | tr '\r' ' ')
[[ -z "$a" ]] && exit

If you told System Events to display the dialog, there would be a small delay if it wasn't running before.

For documentation about display dialog, open the dictionary of Standard Additions in AppleScript Editor or see the AppleScript Language Guide.

How do android screen coordinates work?

This picture will remove everyone's confusion hopefully which is collected from there.

Android screen coordinate

A server with the specified hostname could not be found

For me it was an issue with enabling Outgoing connections in Capabilities tab.

enter image description here

How do you make a deep copy of an object?

I used Dozer for cloning java objects and it's great at that , Kryo library is another great alternative.

Strip / trim all strings of a dataframe

You can try:

df[0] = df[0].str.strip()

or more specifically for all string columns

non_numeric_columns = list(set(df.columns)-set(df._get_numeric_data().columns))
df[non_numeric_columns] = df[non_numeric_columns].apply(lambda x : str(x).strip())

SQL selecting rows by most recent date with two unique columns

So this isn't what the requester was asking for but it is the answer to "SQL selecting rows by most recent date".

Modified from http://wiki.lessthandot.com/index.php/Returning_The_Maximum_Value_For_A_Row

SELECT t.chargeId, t.chargeType, t.serviceMonth FROM( 
    SELECT chargeId,MAX(serviceMonth) AS serviceMonth
    FROM invoice
    GROUP BY chargeId) x 
    JOIN invoice t ON x.chargeId =t.chargeId
    AND x.serviceMonth = t.serviceMonth

Configure Flask dev server to be visible across the network

If none of the above solutions are working, try manually adding "http://" to the beginning of the url.

Chrome can distinguish "[ip-address]:5000" from a search query. But sometimes that works for a while, and then stops connecting, seemingly without me changing anything. My hypothesis is that the browser might sometimes automatically prepend https:// (which it shouldn't, but this fixed it in my case).

select and echo a single field from mysql db using PHP

Read the manual, it covers it very well: http://php.net/manual/en/function.mysql-query.php

Usually you do something like this:

while ($row = mysql_fetch_assoc($result)) {
  echo $row['firstname'];
  echo $row['lastname'];
  echo $row['address'];
  echo $row['age'];
}

How can I break from a try/catch block without throwing an exception in Java

This is the code I usually do:

 try
 {
    ...........
    throw null;//this line just works like a 'break'
    ...........   
  }
  catch (NullReferenceException)
  { 
  }
  catch (System.Exception ex)
  {
      .........
  }

How to get scrollbar position with Javascript?

You can use element.scrollTop and element.scrollLeft to get the vertical and horizontal offset, respectively, that has been scrolled. element can be document.body if you care about the whole page. You can compare it to element.offsetHeight and element.offsetWidth (again, element may be the body) if you need percentages.

Generate unique random numbers between 1 and 100

The best earlier answer is the answer by sje397. You will get as good random numbers as you can get, as quick as possible.

My solution is very similar to his solution. However, sometimes you want the random numbers in random order, and that is why I decided to post an answer. In addition, I provide a general function.

function selectKOutOfN(k, n) {
  if (k>n) throw "k>n";
  var selection = [];
  var sorted = [];
  for (var i = 0; i < k; i++) {
    var rand = Math.floor(Math.random()*(n - i));
    for (var j = 0; j < i; j++) {
      if (sorted[j]<=rand)
        rand++;
      else
        break;
    }
    selection.push(rand);
    sorted.splice(j, 0, rand);
  }
  return selection;
}

alert(selectKOutOfN(8, 100));

Text File Parsing with Python

There are a few ways to go about this. One option would be to use inputfile.read() instead of inputfile.readlines() - you'd need to write separate code to strip the first four lines, but if you want the final output as a single string anyway, this might make the most sense.

A second, simpler option would be to rejoin the strings after striping the first four lines with my_text = ''.join(my_text). This is a little inefficient, but if speed isn't a major concern, the code will be simplest.

Finally, if you actually want the output as a list of strings instead of a single string, you can just modify your data parser to iterate over the list. That might looks something like this:

def data_parser(lines, dic):
    for i, j in dic.iteritems():
        for (k, line) in enumerate(lines):
            lines[k] = line.replace(i, j)
    return lines

Sending E-mail using C#

You can send email using SMTP or CDO

using SMTP:

mail.From = new MailAddress("[email protected]");
mail.To.Add("to_address");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";

SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;

using CDO

CDO.Message oMsg = new CDO.Message();
CDO.IConfiguration iConfg;
iConfg = oMsg.Configuration;
ADODB.Fields oFields;
oFields = iConfg.Fields;
ADODB.Field oField = oFields["http://schemas.microsoft.com/cdo/configuration/sendusing"];
oFields.Update();
oMsg.Subject = "Test CDO";
oMsg.From = "from_address";
oMsg.To = "to_address";
oMsg.TextBody = "CDO Mail test";
oMsg.Send();

Source : C# SMTP Email

Source: C# CDO Email

How do I add a custom script to my package.json file that runs a javascript file?

Suppose I have this line of scripts in my "package.json"

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "export_advertisements": "node export.js advertisements",
    "export_homedata": "node export.js homedata",
    "export_customdata": "node export.js customdata",
    "export_rooms": "node export.js rooms"
  },

Now to run the script "export_advertisements", I will simply go to the terminal and type

npm run export_advertisements

You are most welcome

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

Problem solved! I'm using Ctrl + Alt + E to open Exception Window, and I checked all throw checkbox. So the debuger can stop at the exactly the error code.

Creating and writing lines to a file

Set objFSO=CreateObject("Scripting.FileSystemObject")

' How to write file
outFile="c:\test\autorun.inf"
Set objFile = objFSO.CreateTextFile(outFile,True)
objFile.Write "test string" & vbCrLf
objFile.Close

'How to read a file
strFile = "c:\test\file"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
    strLine= objFile.ReadLine
    Wscript.Echo strLine
Loop
objFile.Close

'to get file path without drive letter, assuming drive letters are c:, d:, etc
strFile="c:\test\file"
s = Split(strFile,":")
WScript.Echo s(1)

CSS transition between left -> right and top -> bottom positions

This worked for me on Chromium. The % for translate is in reference to the size of the bounding box of the element it is applied to so it perfectly gets the element to the lower right edge while not having to switch which property is used to specify it's location.

topleft {
  top: 0%;
  left: 0%;
}
bottomright {
  top: 100%;
  left: 100%;
  -webkit-transform: translate(-100%,-100%);
}

Getting all names in an enum as a String[]

The easiest way:

Category[] category = Category.values();
for (int i = 0; i < cat.length; i++) {
     System.out.println(i  + " - " + category[i]);
}

Where Category is Enum name

Android set height and width of Custom view programmatically

You can set height and width like this:

myGraphView.setLayoutParams(new LayoutParams(width, height));

python numpy/scipy curve fitting

You'll first need to separate your numpy array into two separate arrays containing x and y values.

x = [1, 2, 3, 9]
y = [1, 4, 1, 3]

curve_fit also requires a function that provides the type of fit you would like. For instance, a linear fit would use a function like

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

scipy.optimize.curve_fit(func, x, y) will return a numpy array containing two arrays: the first will contain values for a and b that best fit your data, and the second will be the covariance of the optimal fit parameters.

Here's an example for a linear fit with the data you provided.

import numpy as np
from scipy.optimize import curve_fit

x = np.array([1, 2, 3, 9])
y = np.array([1, 4, 1, 3])

def fit_func(x, a, b):
    return a*x + b

params = curve_fit(fit_func, x, y)

[a, b] = params[0]

This code will return a = 0.135483870968 and b = 1.74193548387

Here's a plot with your points and the linear fit... which is clearly a bad one, but you can change the fitting function to obtain whatever type of fit you would like.

enter image description here

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

java.lang.IllegalArgumentException: contains a path separator

I solved this type of error by making a directory in the onCreate event, then accessing the directory by creating a new file object in a method that needs to do something such as save or retrieve a file in that directory, hope this helps!

 public class MyClass {    

 private String state;
 public File myFilename;

 @Override
 protected void onCreate(Bundle savedInstanceState) {//create your directory the user will be able to find
    super.onCreate(savedInstanceState);
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        myFilename = new File(Environment.getExternalStorageDirectory().toString() + "/My Directory");
        if (!myFilename.exists()) {
            myFilename.mkdirs();
        }
    }
 }

 public void myMethod {

 File fileTo = new File(myFilename.toString() + "/myPic.png");  
 // use fileTo object to save your file in your new directory that was created in the onCreate method
 }
}

How to split a line into words separated by one or more spaces in bash?

$ line="these are words"
$ ll=($line)
$ declare -p ll  # dump the array
declare -a ll='([0]="these" [1]="are" [2]="words")'
$ for w in ${ll[@]}; do echo $w; done
these
are
words

jQuery: how to get which button was clicked upon form submission?

Here is a sample, that uses this.form to get the correct form the submit is into, and data fields to store the last clicked/focused element. I also wrapped submit code inside a timeout to be sure click events happen before it is executed (some users reported in comments that on Chrome sometimes a click event is fired after a submit).

Works when navigating both with keys and with mouse/fingers without counting on browsers to send a click event on RETURN key (doesn't hurt though), I added an event handler for focus events for buttons and fields.

You might add buttons of type="submit" to the items that save themselves when clicked.

In the demo I set a red border to show the selected item and an alert that shows name and value/label.

Here is the FIDDLE

And here is the (same) code:

Javascript:

$("form").submit(function(e) {
  e.preventDefault();
  // Use this for rare/buggy cases when click event is sent after submit
  setTimeout(function() {

    var $this=$(this);
    var lastFocus = $this.data("lastFocus");
    var $defaultSubmit=null;

    if(lastFocus) $defaultSubmit=$(lastFocus);

    if(!$defaultSubmit || !$defaultSubmit.is("input[type=submit]")) {
      // If for some reason we don't have a submit, find one (the first)
      $defaultSubmit=$(this).find("input[type=submit]").first();
    }

    if($defaultSubmit) {
      var submitName=$defaultSubmit.attr("name");
      var submitLabel=$defaultSubmit.val();

       // Just a demo, set hilite and alert
      doSomethingWith($defaultSubmit);
      setTimeout(function() {alert("Submitted "+submitName+": '"+submitLabel+"'")},1000);
    } else {
      // There were no submit in the form
    }

  }.bind(this),0);

});

$("form input").focus(function() {
  $(this.form).data("lastFocus", this);
});
$("form input").click(function() {
  $(this.form).data("lastFocus", this);
});

// Just a demo, setting hilite
function doSomethingWith($aSelectedEl) {
  $aSelectedEl.css({"border":"4px solid red"});
  setTimeout(function() { $aSelectedEl.removeAttr("style"); },1000);
}

DUMMY HTML:

<form>
<input type="text" name="testtextortexttest" value="Whatever you write, sir."/>
<input type="text" name="moretesttextormoretexttest" value="Whatever you write, again, sir."/>

<input type="submit" name="test1" value="Action 1"/>
<input type="submit" name="test2" value="Action 2"/>
<input type="submit" name="test3" value="Action 3"/>
<input type="submit" name="test4" value="Action 4"/>
<input type="submit" name="test5" value="Action 5"/>
</form>

DUMB CSS:

input {display:block}

Mysql 1050 Error "Table already exists" when in fact, it does not

My CREATE statement was part of staging env dump.

I did try everything that has been mentioned above. I DID NOT get solution. However my path to redemption was:

  1. I stumble upon the fact that (one of many in) the CREATE statement did get through when I rectified the database name case sensitivity. This clicked something. I repeated the same for the other tables.

  2. However a new error came into the scene. The straight quotes for 'comments' were throwing syntax error. I was shocked. replaced them but the new error started popping up. Finally i knew the solution.

SOLUTION: The dump i was using might have been from a different version of MySql. I got permission to connect to the staging MYsql using the local(installed on my machine) mysql workbench. I did not rdp into the staging server to login to staging mysql workbench. Created a dump from there. Ran the dump and it worked like a sweet.

Node.js on multi-core machines

It's possible to scale NodeJS out to multiple boxes using a pure TCP load balancer (HAProxy) in front of multiple boxes running one NodeJS process each.

If you then have some common knowledge to share between all instances you could use a central Redis store or similar which can then be accessed from all process instances (e.g. from all boxes)

How to read data from excel file using c#

I don't have a machine available to test this but it should work. First you will probably need to install the either the 2007 Office System Driver: Data Connectivity Components or the Microsoft Access Database Engine 2010 Redistributable. Then try the following code, note you will need to change the name of the Sheet in the Select statement below to match sheetname in your excel file:

using System.Data;
using System.Data.OleDb;

namespace Data_Migration_Process_Creator
{
    class Class1
    {
        private DataTable GetDataTable(string sql, string connectionString)
        {
            DataTable dt = null;

            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                conn.Open();
                using (OleDbCommand cmd = new OleDbCommand(sql, conn))
                {
                    using (OleDbDataReader rdr = cmd.ExecuteReader())
                    {
                        dt.Load(rdr);
                        return dt;
                    }
                }
            }
        }

        private void GetExcel()
        {
            string fullPathToExcel = "<Path to Excel file>"; //ie C:\Temp\YourExcel.xls
            string connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=yes'", fullPathToExcel);
            DataTable dt = GetDataTable("SELECT * from [SheetName$]", connString);

            foreach (DataRow dr in dt.Rows)
            {
                //Do what you need to do with your data here
            }
        }
    }
}

Note: I don't have an environment to test this in (One with Office installed) so I can't say if it will work in your environment or not but I don't see why it shouldn't work.