Programs & Examples On #Modifier key

Search for value in DataGridView in a column

Filter the data directly from DataTable or Dataset:

"MyTable".DefaultView.RowFilter = "<DataTable Field> LIKE '%" + textBox1.Text + "%'";
   this.dataGridView1.DataSource = "MyTable".DefaultView;

Use this code on event KeyUp of Textbox, replace "MyTable" for you table name or dataset, replace for the field where you want make the search.

Sql script to find invalid email addresses

I know the post is old but after a 3 months time and with various email combinations I came across, able to make this sql for validating Email IDs.

CREATE FUNCTION [dbo].[isValidEmailFormat]
(
    @EmailAddress varchar(500)
)
RETURNS bit
AS
BEGIN
    DECLARE @Result bit

    SET @EmailAddress = LTRIM(RTRIM(@EmailAddress));
    SELECT @Result =
    CASE WHEN
    CHARINDEX(' ',LTRIM(RTRIM(@EmailAddress))) = 0
    AND LEFT(LTRIM(@EmailAddress),1) <> '@'
    AND RIGHT(RTRIM(@EmailAddress),1) <> '.'
    AND LEFT(LTRIM(@EmailAddress),1) <> '-'
    AND CHARINDEX('.',@EmailAddress,CHARINDEX('@',@EmailAddress)) - CHARINDEX('@',@EmailAddress) > 2    
    AND LEN(LTRIM(RTRIM(@EmailAddress))) - LEN(REPLACE(LTRIM(RTRIM(@EmailAddress)),'@','')) = 1
    AND CHARINDEX('.',REVERSE(LTRIM(RTRIM(@EmailAddress)))) >= 3
    AND (CHARINDEX('.@',@EmailAddress) = 0 AND CHARINDEX('..',@EmailAddress) = 0)
    AND (CHARINDEX('-@',@EmailAddress) = 0 AND CHARINDEX('..',@EmailAddress) = 0)
    AND (CHARINDEX('_@',@EmailAddress) = 0 AND CHARINDEX('..',@EmailAddress) = 0)
    AND ISNUMERIC(SUBSTRING(@EmailAddress, 1, 1)) = 0
    AND CHARINDEX(',', @EmailAddress) = 0
    AND CHARINDEX('!', @EmailAddress) = 0
    AND CHARINDEX('-.', @EmailAddress)=0
    AND CHARINDEX('%', @EmailAddress)=0
    AND CHARINDEX('#', @EmailAddress)=0
    AND CHARINDEX('$', @EmailAddress)=0
    AND CHARINDEX('&', @EmailAddress)=0
    AND CHARINDEX('^', @EmailAddress)=0
    AND CHARINDEX('''', @EmailAddress)=0
    AND CHARINDEX('\', @EmailAddress)=0
    AND CHARINDEX('/', @EmailAddress)=0
    AND CHARINDEX('*', @EmailAddress)=0
    AND CHARINDEX('+', @EmailAddress)=0
    AND CHARINDEX('(', @EmailAddress)=0
    AND CHARINDEX(')', @EmailAddress)=0
    AND CHARINDEX('[', @EmailAddress)=0
    AND CHARINDEX(']', @EmailAddress)=0
    AND CHARINDEX('{', @EmailAddress)=0
    AND CHARINDEX('}', @EmailAddress)=0
    AND CHARINDEX('?', @EmailAddress)=0
    AND CHARINDEX('<', @EmailAddress)=0
    AND CHARINDEX('>', @EmailAddress)=0
    AND CHARINDEX('=', @EmailAddress)=0
    AND CHARINDEX('~', @EmailAddress)=0
    AND CHARINDEX('`', @EmailAddress)=0 
    AND CHARINDEX('.', SUBSTRING(@EmailAddress, CHARINDEX('@', @EmailAddress)+1, 2))=0
    AND CHARINDEX('.', SUBSTRING(@EmailAddress, CHARINDEX('@', @EmailAddress)-1, 2))=0
    AND LEN(SUBSTRING(@EmailAddress, 0, CHARINDEX('@', @EmailAddress)))>1
    AND CHARINDEX('.', REVERSE(@EmailAddress)) > 2
    AND CHARINDEX('.', REVERSE(@EmailAddress)) < 5  
    THEN 1 ELSE  0 END


    RETURN @Result
END

Any suggestions are welcomed!

How to disable Compatibility View in IE

<meta http-equiv="X-UA-Compatible" content="IE=8" /> 

should force your page to render in IE8 standards. The user may add the site to compatibility list but this tag will take precedence.

A quick way to check would be to load the page and type the following the address bar :

javascript:alert(navigator.userAgent) 

If you see IE7 in the string, it is loading in compatibility mode, otherwise not.

MySQL: Invalid use of group function

First, the error you're getting is due to where you're using the COUNT function -- you can't use an aggregate (or group) function in the WHERE clause.

Second, instead of using a subquery, simply join the table to itself:

SELECT a.pid 
FROM Catalog as a LEFT JOIN Catalog as b USING( pid )
WHERE a.sid != b.sid
GROUP BY a.pid

Which I believe should return only rows where at least two rows exist with the same pid but there is are at least 2 sids. To make sure you get back only one row per pid I've applied a grouping clause.

How to find patterns across multiple lines using grep?

Sadly, you can't. From the grep docs:

grep searches the named input FILEs (or standard input if no files are named, or if a single hyphen-minus (-) is given as file name) for lines containing a match to the given PATTERN.

How to fix error Base table or view not found: 1146 Table laravel relationship table?

try checking in the app if you are using the tables before it's created such as appServiceProvider.php

you might be calling the table without being created it, if you are, comment it then run php artisan migrate.

port forwarding in windows

I've solved it, it can be done executing:

netsh interface portproxy add v4tov4 listenport=4422 listenaddress=192.168.1.111 connectport=80 connectaddress=192.168.0.33

To remove forwarding:

netsh interface portproxy delete v4tov4 listenport=4422 listenaddress=192.168.1.111

Official docs

how to hide a vertical scroll bar when not needed

overflow: auto (or overflow-y: auto) is the correct way to go.

The problem is that your text area is taller than your div. The div ends up cutting off the textbox, so even though it looks like it should start scrolling when the text is taller than 159px it won't start scrolling until the text is taller than 400px which is the height of the textbox.

Try this: http://jsfiddle.net/G9rfq/1/

I set overflow:auto on the text box, and made the textbox the same size as the div.

Also I don't believe it's valid to have a div inside a label, the browser will render it, but it might cause some funky stuff to happen. Also your div isn't closed.

C# Example of AES256 encryption using System.Security.Cryptography.Aes

public class AesCryptoService
{
    private static byte[] Key = Encoding.ASCII.GetBytes(@"qwr{@^h`h&_`50/ja9!'dcmh3!uw<&=?");
    private static byte[] IV = Encoding.ASCII.GetBytes(@"9/\~V).A,lY&=t2b");


    public static string EncryptStringToBytes_Aes(string plainText)
    {
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");
        byte[] encrypted;


        using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;
            aesAlg.Mode = CipherMode.CBC;
            aesAlg.Padding = PaddingMode.PKCS7;

            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }
        
        return Convert.ToBase64String(encrypted);
    }


    
    public static string DecryptStringFromBytes_Aes(string Text)
    {
        if (Text == null || Text.Length <= 0)
            throw new ArgumentNullException("cipherText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");

        string plaintext = null;
        byte[] cipherText = Convert.FromBase64String(Text.Replace(' ', '+'));

        using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;
            aesAlg.Mode = CipherMode.CBC;
            aesAlg.Padding = PaddingMode.PKCS7;


            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }

        }

        return plaintext;
    }
}

Getting value of HTML text input

If you want to use the value of the email input somewhere else on the same page, for example to do some sort of validation, you could use JavaScript. First I would assign an "id" attribute to your email textbox:

<input type="text" name="email" id="email"/>

and then I would retrieve the value with JavaScript:

var email = document.getElementById('email').value;

From there, you can do additional processing on the value of 'email'.

opening a window form from another form programmatically

This is an old question, but answering for gathering knowledge. We have an original form with a button to show the new form.

enter image description here

The code for the button click is below

private void button1_Click(object sender, EventArgs e)
{
    New_Form new_Form = new New_Form();
    new_Form.Show();
}

Now when click is made, New Form is shown. Since, you want to hide after 2 seconds we are adding a onload event to the new form designer

this.Load += new System.EventHandler(this.OnPageLoad);

This OnPageLoad function runs when that form is loaded

In NewForm.cs ,

public partial class New_Form : Form
{
    private Timer formClosingTimer;

    private void OnPageLoad(object sender, EventArgs e)
    {
        formClosingTimer = new Timer();  // Creating a new timer 
        formClosingTimer.Tick += new EventHandler(CloseForm); // Defining tick event to invoke after a time period
        formClosingTimer.Interval = 2000; // Time Interval in miliseconds
        formClosingTimer.Start(); // Starting a timer
    }
    private void CloseForm(object sender, EventArgs e)
    {
        formClosingTimer.Stop(); // Stoping timer. If we dont stop, function will be triggered in regular intervals
        this.Close(); // Closing the current form
    }
}

In this new form , a timer is used to invoke a method which closes that form.

Here is the new form which automatically closes after 2 seconds, we will be able operate on both the forms where no interference between those two forms.

enter image description here

For your knowledge,

form.close() will free the memory and we can never interact with that form again form.hide() will just hide the form, where the code part can still run

For more details about timer refer this link, https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.7.2

How to generate unique IDs for form labels in React?

This solutions works fine for me.

utils/newid.js:

let lastId = 0;

export default function(prefix='id') {
    lastId++;
    return `${prefix}${lastId}`;
}

And I can use it like this:

import newId from '../utils/newid';

React.createClass({
    componentWillMount() {
        this.id = newId();
    },
    render() {
        return (
            <label htmlFor={this.id}>My label</label>
            <input id={this.id} type="text"/>
        );
    }
});

But it won’t work in isomorphic apps.

Added 17.08.2015. Instead of custom newId function you can use uniqueId from lodash.

Updated 28.01.2016. It’s better to generate ID in componentWillMount.

View RDD contents in Python Spark?

You can simply collect the entire RDD (which will return a list of rows) and print said list:

print(wc.collect())

How do I group Windows Form radio buttons?

Put radio buttons inside GroupBox (or other panel)

enter image description here

Is it possible to use jQuery to read meta tags

I just tried this, and this could be a jQuery version-specific error, but

$("meta[property=twitter:image]").attr("content");

resulted in the following syntax error for me:

Error: Syntax error, unrecognized expression: meta[property=twitter:image]

Apparently it doesn't like the colon. I was able to fix it by using double and single quotes like this:

$("meta[property='twitter:image']").attr("content");

(jQuery version 1.8.3 -- sorry, I would have made this a comment to @Danilo, but it won't let me comment yet)

How do I run a batch script from within a batch script?

You can just invoke the batch script by name, as if you're running on the command line.

So, suppose you have a file bar.bat that says echo This is bar.bat! and you want to call it from a file foo.bat, you can write this in foo.bat:

if "%1"=="blah" bar

Run foo blah from the command line, and you'll see:

C:\>foo blah

C:\>if "blah" == "blah" bar

C:\>echo This is bar.bat!
This is bar.bat!

But beware: When you invoke a batch script from another batch script, the original batch script will stop running. If you want to run the secondary batch script and then return to the previous batch script, you'll have to use the call command. For example:

if "%1"=="blah" call bar
echo That's all for foo.bat!

If you run foo blah on that, you'd see:

C:\>foo blah

C:\>if "blah" == "blah" call bar

C:\>echo This is bar.bat!
This is bar.bat!

C:\>echo That's all for foo.bat!
That's all for foo.bat!

Git: How configure KDiff3 as merge tool and diff tool

Just to extend the @Joseph's answer:

After applying these commands your global .gitconfig file will have the following lines (to speed up the process you can just copy them in the file):

[merge]
    tool = kdiff3
[mergetool "kdiff3"]
    path = C:/Program Files/KDiff3/kdiff3.exe
    trustExitCode = false
[diff]
    guitool = kdiff3
[difftool "kdiff3"]
    path = C:/Program Files/KDiff3/kdiff3.exe
    trustExitCode = false

Add new line in text file with Windows batch file

DISCLAIMER: The below solution does not preserve trailing tabs.


If you know the exact number of lines in the text file, try the following method:

@ECHO OFF
SET origfile=original file
SET tempfile=temporary file
SET insertbefore=4
SET totallines=200
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
  SETLOCAL EnableDelayedExpansion
  SET /P L=
  IF %%i==%insertbefore% ECHO(
  ECHO(!L!
  ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%

The loop reads lines from the original file one by one and outputs them. The output is redirected to a temporary file. When a certain line is reached, an empty line is output before it.

After finishing, the original file is deleted and the temporary one gets assigned the original name.


UPDATE

If the number of lines is unknown beforehand, you can use the following method to obtain it:

FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C

(This line simply replaces the SET totallines=200 line in the above script.)

The method has one tiny flaw: if the file ends with an empty line, the result will be the actual number of lines minus one. If you need a workaround (or just want to play safe), you can use the method described in this answer.

How do I get the absolute directory of a file in bash?

To get the full path use:

readlink -f relative/path/to/file

To get the directory of a file:

dirname relative/path/to/file

You can also combine the two:

dirname $(readlink -f relative/path/to/file)

If readlink -f is not available on your system you can use this*:

function myreadlink() {
  (
  cd "$(dirname $1)"         # or  cd "${1%/*}"
  echo "$PWD/$(basename $1)" # or  echo "$PWD/${1##*/}"
  )
}

Note that if you only need to move to a directory of a file specified as a relative path, you don't need to know the absolute path, a relative path is perfectly legal, so just use:

cd $(dirname relative/path/to/file)

if you wish to go back (while the script is running) to the original path, use pushd instead of cd, and popd when you are done.


* While myreadlink above is good enough in the context of this question, it has some limitation relative to the readlink tool suggested above. For example it doesn't correctly follow a link to a file with different basename.

Deserialize JSON array(or list) in C#

Download Json.NET from here http://james.newtonking.com/projects/json-net.aspx

name deserializedName = JsonConvert.DeserializeObject<name>(jsonData);

react change class name on state change

Below is a fully functional example of what I believe you're trying to do (with a functional snippet).

Explanation

Based on your question, you seem to be modifying 1 property in state for all of your elements. That's why when you click on one, all of them are being changed.

In particular, notice that the state tracks an index of which element is active. When MyClickable is clicked, it tells the Container its index, Container updates the state, and subsequently the isActive property of the appropriate MyClickables.

Example

_x000D_
_x000D_
class Container extends React.Component {_x000D_
  state = {_x000D_
    activeIndex: null_x000D_
  }_x000D_
_x000D_
  handleClick = (index) => this.setState({ activeIndex: index })_x000D_
_x000D_
  render() {_x000D_
    return <div>_x000D_
      <MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
      <MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
      <MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
    </div>_x000D_
  }_x000D_
}_x000D_
_x000D_
class MyClickable extends React.Component {_x000D_
  handleClick = () => this.props.onClick(this.props.index)_x000D_
  _x000D_
  render() {_x000D_
    return <button_x000D_
      type='button'_x000D_
      className={_x000D_
        this.props.isActive ? 'active' : 'album'_x000D_
      }_x000D_
      onClick={ this.handleClick }_x000D_
    >_x000D_
      <span>{ this.props.name }</span>_x000D_
    </button>_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Container />, document.getElementById('app'))
_x000D_
button {_x000D_
  display: block;_x000D_
  margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
.album>span:after {_x000D_
  content: ' (an album)';_x000D_
}_x000D_
_x000D_
.active {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.active>span:after {_x000D_
  content: ' ACTIVE';_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

Update: "Loops"

In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.

// New render method for `Container`
render() {
  const clickables = [
    { name: "a" },
    { name: "b" },
    { name: "c" },
  ]

  return <div>
      { clickables.map(function(clickable, i) {
          return <MyClickable key={ clickable.name }
            name={ clickable.name }
            index={ i }
            isActive={ this.state.activeIndex === i }
            onClick={ this.handleClick }
          />
        } )
      }
  </div>
}

Body set to overflow-y:hidden but page is still scrollable in Chrome

Use:

overflow: hidden;
height: 100%;
position: fixed;
width: 100%;

How to get the root dir of the Symfony2 application?

You can also use regular expression in addition to this:

    $directoryPath = $this->container->getParameter('kernel.root_dir') . '/../web/bundles/yourbundle/';
    $directoryPath = preg_replace("/app..../i", "", $directoryPath);
    echo $directoryPath;

Converting string format to datetime in mm/dd/yyyy

I did like this

var datetoEnter= DateTime.ParseExact(createdDate, "dd/mm/yyyy", CultureInfo.InvariantCulture);

What is an .axd file?

Those are not files (they don't exist on disk) - they are just names under which some HTTP handlers are registered. Take a look at the web.config in .NET Framework's directory (e.g. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config):

<configuration>
  <system.web>
    <httpHandlers>
      <add path="eurl.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
      <add path="trace.axd" verb="*" type="System.Web.Handlers.TraceHandler" validate="True" />
      <add path="WebResource.axd" verb="GET" type="System.Web.Handlers.AssemblyResourceLoader" validate="True" />
      <add verb="*" path="*_AppService.axd" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False" />
      <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False"/>
      <add path="*.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
    </httpHandlers>
  </system.web>
<configuration>

You can register your own handlers with a whatever.axd name in your application's web.config. While you can bind your handlers to whatever names you like, .axd has the upside of working on IIS6 out of the box by default (IIS6 passes requests for *.axd to the ASP.NET runtime by default). Using an arbitrary path for the handler, like Document.pdf (or really anything except ASP.NET-specific extensions), requires more configuration work. In IIS7 in integrated pipeline mode this is no longer a problem, as all requests are processed by the ASP.NET stack.

How to initialize an array in Kotlin with values?

In Kotlin There are Several Ways.

var arr = IntArray(size) // construct with only size

Then simply initial value from users or from another collection or wherever you want.

var arr = IntArray(size){0}  // construct with size and fill array with 0
var arr = IntArray(size){it} // construct with size and fill with its index

We also can create array with built in function like-

var arr = intArrayOf(1, 2, 3, 4, 5) // create an array with 5 values

Another way

var arr = Array(size){0} // it will create an integer array
var arr = Array<String>(size){"$it"} // this will create array with "0", "1", "2" and so on.

You also can use doubleArrayOf() or DoubleArray() or any primitive type instead of Int.

How to use jQuery with Angular?

Why is everyone making it a rocket science? For anyone else who needs to do some basic stuff on static elements, for example, body tag, just do this:

  1. In index.html add script tag with the path to your jquery lib, doesn't matter where (this way you can also use IE conditional tags to load lower version of jquery for IE9 and less).
  2. In your export component block have a function that calls your code: $("body").addClass("done"); Normaly this causes declaration error, so just after all imports in this .ts file, add declare var $:any; and you are good to go!

Add my custom http header to Spring RestTemplate request / extend RestTemplate

Add a "User-Agent" header to your request.

Some servers attempt to block spidering programs and scrapers from accessing their server because, in earlier days, requests did not send a user agent header.

You can either try to set a custom user agent value or use some value that identifies a Browser like "Mozilla/5.0 Firefox/26.0"

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();

headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("user-agent", "Mozilla/5.0 Firefox/26.0");
headers.set("user-key", "your-password-123"); // optional - in case you auth in headers
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<Game[]> respEntity = restTemplate.exchange(url, HttpMethod.GET, entity, Game[].class);

logger.info(respEntity.toString());

How can I execute Shell script in Jenkinsfile?

Previous answers are correct but here is one more way of doing this and some tips:

Option #1 Go to you Jenkins job and search for "add build step" and then just copy and paste your script there

Option #2 Go to Jenkins and do the same again "add build step" but this time put the fully qualified path for your script in there example : ./usr/somewhere/helloWorld.sh

enter image description here enter image description here

things to watch for /tips:

  • Environment variables, if your job is running at the same time then you need to worry about concurrency issues. One job may be setting the value of environment variables and the next may use the value or take some action based on that incorrectly.
  • Make sure all paths are fully qualified
  • Think about logging /var/log or somewhere so you would also have something to go to on the server (optional)
  • thing about space issue and permissions, running out of space and permission issues are very common in linux environment
  • Alerting and make sure your script/job fails the jenkin jobs when your script fails

VBA Go to last empty row

This does it:

Do
   c = c + 1
Loop While Cells(c, "A").Value <> ""

'prints the last empty row
Debug.Print c

What is the difference between HTTP 1.1 and HTTP 2.0?

HTTP/2 supports queries multiplexing, headers compression, priority and more intelligent packet streaming management. This results in reduced latency and accelerates content download on modern web pages.

More details here.

Where and why do I have to put the "template" and "typename" keywords?

(See here also for my C++11 answer)

In order to parse a C++ program, the compiler needs to know whether certain names are types or not. The following example demonstrates that:

t * f;

How should this be parsed? For many languages a compiler doesn't need to know the meaning of a name in order to parse and basically know what action a line of code does. In C++, the above however can yield vastly different interpretations depending on what t means. If it's a type, then it will be a declaration of a pointer f. However if it's not a type, it will be a multiplication. So the C++ Standard says at paragraph (3/7):

Some names denote types or templates. In general, whenever a name is encountered it is necessary to determine whether that name denotes one of these entities before continuing to parse the program that contains it. The process that determines this is called name lookup.

How will the compiler find out what a name t::x refers to, if t refers to a template type parameter? x could be a static int data member that could be multiplied or could equally well be a nested class or typedef that could yield to a declaration. If a name has this property - that it can't be looked up until the actual template arguments are known - then it's called a dependent name (it "depends" on the template parameters).

You might recommend to just wait till the user instantiates the template:

Let's wait until the user instantiates the template, and then later find out the real meaning of t::x * f;.

This will work and actually is allowed by the Standard as a possible implementation approach. These compilers basically copy the template's text into an internal buffer, and only when an instantiation is needed, they parse the template and possibly detect errors in the definition. But instead of bothering the template's users (poor colleagues!) with errors made by a template's author, other implementations choose to check templates early on and give errors in the definition as soon as possible, before an instantiation even takes place.

So there has to be a way to tell the compiler that certain names are types and that certain names aren't.

The "typename" keyword

The answer is: We decide how the compiler should parse this. If t::x is a dependent name, then we need to prefix it by typename to tell the compiler to parse it in a certain way. The Standard says at (14.6/2):

A name used in a template declaration or definition and that is dependent on a template-parameter is assumed not to name a type unless the applicable name lookup finds a type name or the name is qualified by the keyword typename.

There are many names for which typename is not necessary, because the compiler can, with the applicable name lookup in the template definition, figure out how to parse a construct itself - for example with T *f;, when T is a type template parameter. But for t::x * f; to be a declaration, it must be written as typename t::x *f;. If you omit the keyword and the name is taken to be a non-type, but when instantiation finds it denotes a type, the usual error messages are emitted by the compiler. Sometimes, the error consequently is given at definition time:

// t::x is taken as non-type, but as an expression the following misses an
// operator between the two names or a semicolon separating them.
t::x f;

The syntax allows typename only before qualified names - it is therefor taken as granted that unqualified names are always known to refer to types if they do so.

A similar gotcha exists for names that denote templates, as hinted at by the introductory text.

The "template" keyword

Remember the initial quote above and how the Standard requires special handling for templates as well? Let's take the following innocent-looking example:

boost::function< int() > f;

It might look obvious to a human reader. Not so for the compiler. Imagine the following arbitrary definition of boost::function and f:

namespace boost { int function = 0; }
int main() { 
  int f = 0;
  boost::function< int() > f; 
}

That's actually a valid expression! It uses the less-than operator to compare boost::function against zero (int()), and then uses the greater-than operator to compare the resulting bool against f. However as you might well know, boost::function in real life is a template, so the compiler knows (14.2/3):

After name lookup (3.4) finds that a name is a template-name, if this name is followed by a <, the < is always taken as the beginning of a template-argument-list and never as a name followed by the less-than operator.

Now we are back to the same problem as with typename. What if we can't know yet whether the name is a template when parsing the code? We will need to insert template immediately before the template name, as specified by 14.2/4. This looks like:

t::template f<int>(); // call a function template

Template names can not only occur after a :: but also after a -> or . in a class member access. You need to insert the keyword there too:

this->template f<int>(); // call a function template

Dependencies

For the people that have thick Standardese books on their shelf and that want to know what exactly I was talking about, I'll talk a bit about how this is specified in the Standard.

In template declarations some constructs have different meanings depending on what template arguments you use to instantiate the template: Expressions may have different types or values, variables may have different types or function calls might end up calling different functions. Such constructs are generally said to depend on template parameters.

The Standard defines precisely the rules by whether a construct is dependent or not. It separates them into logically different groups: One catches types, another catches expressions. Expressions may depend by their value and/or their type. So we have, with typical examples appended:

  • Dependent types (e.g: a type template parameter T)
  • Value-dependent expressions (e.g: a non-type template parameter N)
  • Type-dependent expressions (e.g: a cast to a type template parameter (T)0)

Most of the rules are intuitive and are built up recursively: For example, a type constructed as T[N] is a dependent type if N is a value-dependent expression or T is a dependent type. The details of this can be read in section (14.6.2/1) for dependent types, (14.6.2.2) for type-dependent expressions and (14.6.2.3) for value-dependent expressions.

Dependent names

The Standard is a bit unclear about what exactly is a dependent name. On a simple read (you know, the principle of least surprise), all it defines as a dependent name is the special case for function names below. But since clearly T::x also needs to be looked up in the instantiation context, it also needs to be a dependent name (fortunately, as of mid C++14 the committee has started to look into how to fix this confusing definition).

To avoid this problem, I have resorted to a simple interpretation of the Standard text. Of all the constructs that denote dependent types or expressions, a subset of them represent names. Those names are therefore "dependent names". A name can take different forms - the Standard says:

A name is a use of an identifier (2.11), operator-function-id (13.5), conversion-function-id (12.3.2), or template-id (14.2) that denotes an entity or label (6.6.4, 6.1)

An identifier is just a plain sequence of characters / digits, while the next two are the operator + and operator type form. The last form is template-name <argument list>. All these are names, and by conventional use in the Standard, a name can also include qualifiers that say what namespace or class a name should be looked up in.

A value dependent expression 1 + N is not a name, but N is. The subset of all dependent constructs that are names is called dependent name. Function names, however, may have different meaning in different instantiations of a template, but unfortunately are not caught by this general rule.

Dependent function names

Not primarily a concern of this article, but still worth mentioning: Function names are an exception that are handled separately. An identifier function name is dependent not by itself, but by the type dependent argument expressions used in a call. In the example f((T)0), f is a dependent name. In the Standard, this is specified at (14.6.2/1).

Additional notes and examples

In enough cases we need both of typename and template. Your code should look like the following

template <typename T, typename Tail>
struct UnionNode : public Tail {
    // ...
    template<typename U> struct inUnion {
        typedef typename Tail::template inUnion<U> dummy;
    };
    // ...
};

The keyword template doesn't always have to appear in the last part of a name. It can appear in the middle before a class name that's used as a scope, like in the following example

typename t::template iterator<int>::value_type v;

In some cases, the keywords are forbidden, as detailed below

  • On the name of a dependent base class you are not allowed to write typename. It's assumed that the name given is a class type name. This is true for both names in the base-class list and the constructor initializer list:

     template <typename T>
     struct derive_from_Has_type : /* typename */ SomeBase<T>::type 
     { };
    
  • In using-declarations it's not possible to use template after the last ::, and the C++ committee said not to work on a solution.

     template <typename T>
     struct derive_from_Has_type : SomeBase<T> {
        using SomeBase<T>::template type; // error
        using typename SomeBase<T>::type; // typename *is* allowed
     };
    

Chrome's remote debugging (USB debugging) not working for Samsung Galaxy S3 running android 4.3

After looking around a little longer I came across this. Apparently, there isn't a solution to this issue yet, but there is a workaround - going back to the legacy workflow.

The legacy workflow did work for me, and the only additional thing I had to do was to go to the platform-tools folder from android SDK download, open a command window here and run command "adb devices". This caused the computer RSA key fingerprint panel to pop on my mobile screen, and after granting permission, the device showed up under Chrome's Inspect page.

Turns out that it was not an issue caused by mobile OS upgrade but by Chrome (I was thrown off by the fact that it worked on my Nexus4 somehow). In the older versions of Chrome there was't a need to download the 500 odd mb Android SDK, as it supported an ADB plugin. But with latest version of Chrome, I guess, going legacy is the only way to go.

How to extract public key using OpenSSL?

If your looking how to copy an Amazon AWS .pem keypair into a different region do the following:

openssl rsa -in .ssh/amazon-aws.pem -pubout > .ssh/amazon-aws.pub

Then

aws ec2 import-key-pair --key-name amazon-aws --public-key-material '$(cat .ssh/amazon-aws.pub)' --region us-west-2

Convert UTC to local time in Rails 3

Rails has its own names. See them with:

rake time:zones:us

You can also run rake time:zones:all for all time zones. To see more zone-related rake tasks: rake -D time

So, to convert to EST, catering for DST automatically:

Time.now.in_time_zone("Eastern Time (US & Canada)")

javascript pushing element at the beginning of an array

Use unshift, which modifies the existing array by adding the arguments to the beginning:

TheArray.unshift(TheNewObject);

Trying to read cell 1,1 in spreadsheet using Google Script API

You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of

function email() {

// Opens SS by its ID

var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");

// Get the name of this SS

var name = ss.getName();  // Not necessary 

// Read cell 1,1 * Line below does't work *

// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet 
var range = sheet.getRange(1,1); 
var data = range.getValue();

}

The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.

How does the SQL injection from the "Bobby Tables" XKCD comic work?

The ' character in SQL is used for string constants. In this case it is used for ending the string constant and not for comment.

PHP float with 2 decimal places: .00

try this

$result = number_format($FloatNumber, 2);

Best way to check if a drop down list contains a value?

You could try checking to see if this method returns a null:

if (ddlCustomerNumber.Items.FindByText(GetCustomerNumberCookie().ToString()) != null)
    ddlCustomerNumber.SelectedIndex = 0;

converting multiple columns from character to numeric format in r

I think I figured it out. Here's what I did (perhaps not the most elegant solution - suggestions on how to imp[rove this are very much welcome)

#names of columns in data frame
cols <- names(DF)
# character variables
cols.char <- c("fx_code","date")
#numeric variables
cols.num <- cols[!cols %in% cols.char]

DF.char <- DF[cols.char]
DF.num <- as.data.frame(lapply(DF[cols.num],as.numeric))
DF2 <- cbind(DF.char, DF.num)

How to reference static assets within vue javascript

Of course src="@/assets/images/x.jpg works, but better way is: src="~assets/images/x.jpg

Create WordPress Page that redirects to another URL

I'm not familiar with Wordpress templates, but I'm assuming that headers are sent to the browser by WP before your template is even loaded. Because of that, the common redirection method of:

header("Location: new_url");

won't work. Unless there's a way to force sending headers through a template before WP does anything, you'll need to use some Javascript like so:

<script language="javascript" type="text/javascript">
document.location = "new_url";
</script>

Put that in the section and it'll be run when the page loads. This method won't be instant, and it also won't work for people with Javascript disabled.

How to debug apk signed for release?

I know this is old question, but future references. In Android Studio with Gradle:

buildTypes {
    release {
        debuggable true
        runProguard true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
}

The line debuggable true was the trick for me.

Update:

Since gradle 1.0 it's minifyEnabled instead of runProguard. Look at here

Check if an element is a child of a parent

.has() seems to be designed for this purpose. Since it returns a jQuery object, you have to test for .length as well:

if ($('div#hello').has(target).length) {
   alert('Target is a child of #hello');
}

How to prevent text in a table cell from wrapping

There are at least two ways to do it:

Use nowrap attribute inside the "td" tag:

<th nowrap="nowrap">Really long column heading</th>

Use non-breakable spaces between your words:

<th>Really&nbsp;long&nbsp;column&nbsp;heading</th>

Remove all subviews?

In order to remove all subviews Syntax :

- (void)makeObjectsPerformSelector:(SEL)aSelector;

Usage :

[self.View.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

This method is present in NSArray.h file and uses NSArray(NSExtendedArray) interface

Can't push to the heroku

If you are using django app to deploy on heroku

make sure to put request library in the requirements.txt file.

How do I type a TAB character in PowerShell?

Test with [char]9, such as:

$Tab = [char]9
Write-Output "$Tab hello"

Output:

     hello

jQuery Data vs Attr?

The main difference between the two is where it is stored and how it is accessed.

$.fn.attr stores the information directly on the element in attributes which are publicly visible upon inspection, and also which are available from the element's native API.

$.fn.data stores the information in a ridiculously obscure place. It is located in a closed over local variable called data_user which is an instance of a locally defined function Data. This variable is not accessible from outside of jQuery directly.

Data set with attr()

  • accessible from $(element).attr('data-name')
  • accessible from element.getAttribute('data-name'),
  • if the value was in the form of data-name also accessible from $(element).data(name) and element.dataset['name'] and element.dataset.name
  • visible on the element upon inspection
  • cannot be objects

Data set with .data()

  • accessible only from .data(name)
  • not accessible from .attr() or anywhere else
  • not publicly visible on the element upon inspection
  • can be objects

How to use multiprocessing pool.map with multiple arguments?

From python 3.4.4, you can use multiprocessing.get_context() to obtain a context object to use multiple start methods:

import multiprocessing as mp

def foo(q, h, w):
    q.put(h + ' ' + w)
    print(h + ' ' + w)

if __name__ == '__main__':
    ctx = mp.get_context('spawn')
    q = ctx.Queue()
    p = ctx.Process(target=foo, args=(q,'hello', 'world'))
    p.start()
    print(q.get())
    p.join()

Or you just simply replace

pool.map(harvester(text,case),case, 1)

by:

pool.apply_async(harvester(text,case),case, 1)

Why do you use typedef when declaring an enum in C++?

You do not need to do it. In C (not C++) you were required to use enum Enumname to refer to a data element of the enumerated type. To simplify it you were allowed to typedef it to a single name data type.

typedef enum MyEnum { 
  //...
} MyEnum;

allowed functions taking a parameter of the enum to be defined as

void f( MyEnum x )

instead of the longer

void f( enum MyEnum x )

Note that the name of the typename does not need to be equal to the name of the enum. The same happens with structs.

In C++, on the other hand, it is not required, as enums, classes and structs can be accessed directly as types by their names.

// C++
enum MyEnum {
   // ...
};
void f( MyEnum x ); // Correct C++, Error in C

Converting 'ArrayList<String> to 'String[]' in Java

ArrayList<String> arrayList = new ArrayList<String>();
Object[] objectList = arrayList.toArray();
String[] stringArray =  Arrays.copyOf(objectList,objectList.length,String[].class);

Using copyOf, ArrayList to arrays might be done also.

PHP - regex to allow letters and numbers only

try this way .eregi("[^A-Za-z0-9.]", $value)

asp.net: How can I remove an item from a dropdownlist?

myDropDown.Items.Remove(myDropDown.Items.FindByText("TextToFind"))

How to read specific lines from a file (by line number)?

If your large text file file is strictly well-structured (meaning every line has the same length l), you could use for n-th line

with open(file) as f:
    f.seek(n*l)
    line = f.readline() 
    last_pos = f.tell()

Disclaimer This does only work for files with the same length!

jQuery Form Validation before Ajax submit

I think submitHandler with jquery validation is good solution. Please get idea from this code. Inspired from @Darin Dimitrov

$('.calculate').validate({

                submitHandler: function(form) {
                    $.ajax({
                        url: 'response.php',
                        type: 'POST',
                        data: $(form).serialize(),
                        success: function(response) {
                            $('#'+form.id+' .ht-response-data').html(response);
                        }            
                    });
                }
            });

iterating over and removing from a map

As of Java 8 you could do this as follows:

map.entrySet().removeIf(e -> <boolean expression>);

Oracle Docs: entrySet()

The set is backed by the map, so changes to the map are reflected in the set, and vice-versa

How do I include a file over 2 directories back?

including over directories can be processed by proxy file

  • root
  • .....|__web
  • .....|.........|_requiredDbSettings.php
  • .....|
  • .....|___db
  • .....|.........|_dbsettings.php
  • .....|
  • .....|_proxy.php

    dbsettings.php:
    $host='localhost';
    $user='username':
    $pass='pass';
    
    proxy.php:
    include_once 'db/dbsettings.php
    
    requiredDbSettings.php:
    include_once './../proxy.php';
    

Is there a timeout for idle PostgreSQL connections?

It sounds like you have a connection leak in your application because it fails to close pooled connections. You aren't having issues just with <idle> in transaction sessions, but with too many connections overall.

Killing connections is not the right answer for that, but it's an OK-ish temporary workaround.

Rather than re-starting PostgreSQL to boot all other connections off a PostgreSQL database, see: How do I detach all other users from a postgres database? and How to drop a PostgreSQL database if there are active connections to it? . The latter shows a better query.

For setting timeouts, as @Doon suggested see How to close idle connections in PostgreSQL automatically?, which advises you to use PgBouncer to proxy for PostgreSQL and manage idle connections. This is a very good idea if you have a buggy application that leaks connections anyway; I very strongly recommend configuring PgBouncer.

A TCP keepalive won't do the job here, because the app is still connected and alive, it just shouldn't be.

In PostgreSQL 9.2 and above, you can use the new state_change timestamp column and the state field of pg_stat_activity to implement an idle connection reaper. Have a cron job run something like this:

SELECT pg_terminate_backend(pid)
    FROM pg_stat_activity
    WHERE datname = 'regress'
      AND pid <> pg_backend_pid()
      AND state = 'idle'
      AND state_change < current_timestamp - INTERVAL '5' MINUTE;

In older versions you need to implement complicated schemes that keep track of when the connection went idle. Do not bother; just use pgbouncer.

Case insensitive comparison of strings in shell script

Here is my solution using tr:

var1=match
var2=MATCH
var1=`echo $var1 | tr '[A-Z]' '[a-z]'`
var2=`echo $var2 | tr '[A-Z]' '[a-z]'`
if [ "$var1" = "$var2" ] ; then
  echo "MATCH"
fi

c# why can't a nullable int be assigned null as a value

Another option is to use

int? accom = (accomStr == "noval" ? Convert.DBNull : Convert.ToInt32(accomStr); 

I like this one most.

How to read/process command line arguments?

There is also argparse stdlib module (an "impovement" on stdlib's optparse module). Example from the introduction to argparse:

# script.py
import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'integers', metavar='int', type=int, choices=range(10),
         nargs='+', help='an integer in the range 0..9')
    parser.add_argument(
        '--sum', dest='accumulate', action='store_const', const=sum,
        default=max, help='sum the integers (default: find the max)')

    args = parser.parse_args()
    print(args.accumulate(args.integers))

Usage:

$ script.py 1 2 3 4
4

$ script.py --sum 1 2 3 4
10

Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

Seeing how you draw your canvas with

$("canvas").drawImage();

it seems that you use jQuery Canvas (jCanvas) by Caleb Evans. I actually use that plugin and it has a simple way to retrieve canvas base64 image string with $('canvas').getCanvasImage();

Here's a working Fiddle for you: http://jsfiddle.net/e6nqzxpn/

How to remove duplicates from a list?

java 8 update
you can use stream of array as below:

Arrays.stream(yourArray).distinct()
                    .collect(Collectors.toList());

HTML if image is not found

If you want an alternative image instead of a text, you can as well use php:

$file="smiley.gif";
$alt_file="alt.gif";
if(file_exist($file)){
     echo "<img src='".$file."' border="0" />";
}else if($alt_file){
     // the alternative file too might not exist not exist
     echo "<img src='".$alt_file."' border="0" />";
}else{
  echo "smily face";
}

Using (Ana)conda within PyCharm

Continuum Analytics now provides instructions on how to setup Anaconda with various IDEs including Pycharm here. However, with Pycharm 5.0.1 running on Unbuntu 15.10 Project Interpreter settings were found via the File | Settings and then under the Project branch of the treeview on the Settings dialog.

JBoss vs Tomcat again

Take a look at TOMEE

It has all the features that you need to build a complete Java EE app.

Use jQuery to get the file input's selected filename without the path

Get the first file from the control and then get the name of the file, it will ignore the file path on Chrome, and also will make correction of path for IE browsers. On saving the file, you have to use System.io.Path.GetFileName method to get the file name only for IE browsers

var fileUpload    = $("#ContentPlaceHolder1_FileUpload_mediaFile").get(0); 
var files         =  fileUpload.files; 
var mediafilename = ""; 

for (var i = 0; i < files.length; i++) { 
  mediafilename = files[i].name; 
} 

Powershell v3 Invoke-WebRequest HTTPS error

These registry settings affect .NET Framework 4+ and therefore PowerShell. Set them and restart any PowerShell sessions to use latest TLS, no reboot needed.

Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord 

See https://docs.microsoft.com/en-us/dotnet/framework/network-programming/tls#schusestrongcrypto

TypeError: Router.use() requires middleware function but got a Object

I had this error and solution help which was posted by Anirudh. I built a template for express routing and forgot about this nuance - glad it was an easy fix.

I wanted to give a little clarification to his answer on where to put this code by explaining my file structure.

My typical file structure is as follows:

/lib

/routes

---index.js (controls the main navigation)

/page-one



/page-two



     ---index.js

(each file [in my case the index.js within page-two, although page-one would have an index.js too]- for each page - that uses app.METHOD or router.METHOD needs to have module.exports = router; at the end)

If someone wants I will post a link to github template that implements express routing using best practices. let me know

Thanks Anirudh!!! for the great answer.

Redirecting to a relative URL in JavaScript

https://developer.mozilla.org/en-US/docs/Web/API/Location/assign

  • window.location.assign("../"); // one level up
  • window.location.assign("/path"); // relative to domain

How display only years in input Bootstrap Datepicker?

format: "YYYY" 

Should be capital instead of "yyyy"

MySql Error: Can't update table in stored function/trigger because it is already used by statement which invoked this stored function/trigger

You cannot change a table while the INSERT trigger is firing. The INSERT might do some locking which could result in a deadlock. Also, updating the table from a trigger would then cause the same trigger to fire again in an infinite recursive loop. Both of these reasons are why MySQL prevents you from doing this.

However, depending on what you're trying to achieve, you can access the new values by using NEW.fieldname or even the old values--if doing an UPDATE--with OLD.

If you had a row named full_brand_name and you wanted to use the first two letters as a short name in the field small_name you could use:

CREATE TRIGGER `capital` BEFORE INSERT ON `brandnames`
FOR EACH ROW BEGIN
  SET NEW.short_name = CONCAT(UCASE(LEFT(NEW.full_name,1)) , LCASE(SUBSTRING(NEW.full_name,2)))
END

Get child node index

ES6:

Array.from(element.parentNode.children).indexOf(element)

Explanation :

  • element.parentNode.children ? Returns the brothers of element, including that element.

  • Array.from ? Casts the constructor of children to an Array object

  • indexOf ? You can apply indexOf because you now have an Array object.

How do I get total physical memory size using PowerShell without WMI?

For those coming here from a later day and age and one a working solution:

(Get-WmiObject -class "cim_physicalmemory" | Measure-Object -Property Capacity -Sum).Sum

this will give the total sum of bytes.

$bytes = (Get-WmiObject -class "cim_physicalmemory" | Measure-Object -Property Capacity -Sum).Sum

$kb = $bytes / 1024
$mb = $bytes / 1024 / 1024
$gb = $bytes / 1024 / 1024 / 1024

I tested this up to windows server 2008 (winver 6.0) even there this command seems to work

c++ array - expression must have a constant value

one could also use a fixed lengths vector and access it with indexing

int Lcs(string a, string b) 
{
    int x = a.size() + 1;
    int y = b.size() + 1;

    vector<vector<int>> L(x, vector<int>(y));

    for (int i = 1; i < x; i++)
    {
        for (int j = 1; j < y; j++)
        {
            L[i][j] = a[i - 1] == b[j - 1] ?
                L[i - 1][j - 1] + 1 :
                max(L[i - 1][j], L[i][j - 1]);
        }
    }

    return L[a.size()][b.size()];
}

check output from CalledProcessError

I ran into the same problem and found that the documentation has example for this type of scenario (where we write STDERR TO STDOUT and always exit successfully with return code 0) without causing/catching an exception.

output = subprocess.check_output("ping -c 2 -W 2 1.1.1.1; exit 0", stderr=subprocess.STDOUT, shell=True)

Now, you can use standard string function find to check the output string output.

Windows batch command(s) to read first line from text file

One liner, useful for stdout redirect with ">":

@for /f %%i in ('type yourfile.txt') do @echo %%i & exit

Load a bitmap image into Windows Forms using open file dialog

Works Fine. Try this,

private void addImageButton_Click(object sender, EventArgs e)
{
    OpenFileDialog of = new OpenFileDialog();
    //For any other formats
    of.Filter = "Image Files (*.bmp;*.jpg;*.jpeg,*.png)|*.BMP;*.JPG;*.JPEG;*.PNG"; 
    if (of.ShowDialog() == DialogResult.OK)
    {
        pictureBox1.ImageLocation = of.FileName;

    }
}

How to make a flat list out of list of lists?

Fastest solution I have found (for large list anyway):

import numpy as np
#turn list into an array and flatten()
np.array(l).flatten()

Done! You can of course turn it back into a list by executing list(l)

How to unlock android phone through ADB

If you have USB-Debugging/ADB enabled on your phone and your PC is authorized for debugging on your phone then you can try one of the follwing tools:

scrcpy

scrcpy connects over adb to your device and executes a temporary app to stream the contents of your screen to your PC and you're able to remote control your device. It works on GNU/Linux, Windows and macOS.

Vysor

Vysor is a chrome web app that connects to your device via adb and installs a companion app to stream your screen content to the PC. You can then remote control your device with your mouse.

MonkeyRemote

MonkeyRemote is a remote control tool written by myself before I found Vysor. It also connects through adb and lets you control your device by mouse but in contrast to Vysor, the streamed screen content updates very slow (~1 frame per second). The upside is that there is no need for a companion app to be installed.

show/hide html table columns using css

I don't think there is anything you can do to avoid what you are already doing, however, if you are building the table on the client with javascript, you can always add the style rules dynamically, so you can allow for any number of columns without cluttering up your css file with all those rules. See http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript if you don't know how to do this.

Edit: For your "sticky" toggle, you should just append class names rather than replacing them. For instance, you can give it a class name of "hide2 hide3" etc. I don't think you really need the "show" classes, since that would be the default. Libraries like jQuery make this easy, but in the absence, a function like this might help:

var modifyClassName = function (elem, add, string) {
var s = (elem.className) ? elem.className : "";
var a = s.split(" ");
if (add) {
  for (var i=0; i<a.length; i++) {
      if (a[i] == string) {
          return;
          }
      }
  s += " " + string;
  }
else {
    s = "";
    for (var i=0; i<a.length; i++) {
        if (a[i] != string)
            s += a[i] + " "; 
        }
    }
elem.className = s;
}

What's the difference between import java.util.*; and import java.util.Date; ?

but what I got is something like this: Date@124bbbf  
while I change the import to: import java.util.Date;  
the code works perfectly, why? 

What do you mean by "works perfectly"? The output of printing a Date object is the same no matter whether you imported java.util.* or java.util.Date. The output that you get when printing objects is the representation of the object by the toString() method of the corresponding class.

oracle varchar to number

If you want formated number then use

SELECT TO_CHAR(number, 'fmt')
   FROM DUAL;

SELECT TO_CHAR('123', 999.99)
   FROM DUAL;

Result 123.00

PHP how to get local IP of system

$_SERVER['SERVER_ADDR']

How to form a correct MySQL connection string?

string MyConString = "Data Source='mysql7.000webhost.com';" +
"Port=3306;" +
"Database='a455555_test';" +
"UID='a455555_me';" +
"PWD='something';";

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

Adding to MattR's answer:

As stated in here, @SpringBootApplication automatically inserts the needed annotations: @Configuration, @EnableAutoConfiguration, and also @ComponentScan; however, the @ComponentScan will only look for the components in the same package as the App, in this case your com.nice.application, whereas your controller resides in com.nice.controller. That's why you get 404 because the App didn't find the controller in the application package.

Java: JSON -> Protobuf & back conversion

Here is my utility class, you may use:

package <removed>;
import com.google.protobuf.Message;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.util.JsonFormat;
/**
 * Author @espresso stackoverflow.
 * Sample use:
 *      Model.Person reqObj = ProtoUtil.toProto(reqJson, Model.Person.getDefaultInstance());
        Model.Person res = personSvc.update(reqObj);
        final String resJson = ProtoUtil.toJson(res);
 **/
public class ProtoUtil {
    public static <T extends Message> String toJson(T obj){
        try{
            return JsonFormat.printer().print(obj);
        }catch(Exception e){
            throw new RuntimeException("Error converting Proto to json", e);
        }
    }
   public static <T extends MessageOrBuilder> T toProto(String protoJsonStr, T message){
        try{
            Message.Builder builder = message.getDefaultInstanceForType().toBuilder();
            JsonFormat.parser().ignoringUnknownFields().merge(protoJsonStr,builder);
            T out = (T) builder.build();
            return out;
        }catch(Exception e){
            throw new RuntimeException(("Error converting Json to proto", e);
        }
    }
}

How do I load an url in iframe with Jquery

Just in case anyone still stumbles upon this old question:

The code was theoretically almost correct in a sense, the problem was the use of $('this') instead of $(this), therefore telling jQuery to look for a tag.

$(document).ready(function(){
  $("#frame").click(function () { 
    $(this).load("http://www.google.com/");
  });
});

The script itself woudln't work as it is right now though because the load() function itself is an AJAX function, and google does not seem to specifically allow the use of loading this page with AJAX, but this method should be easy to use in order to load pages from your own domain by using relative paths.

How to request Administrator access inside a batch file

@echo off and title can come before this code:

net session>nul 2>&1
if %errorlevel%==0 goto main
echo CreateObject("Shell.Application").ShellExecute "%~f0", "", "", "runas">"%temp%/elevate.vbs"
"%temp%/elevate.vbs"
del "%temp%/elevate.vbs"
exit

:main
    <code goes here>
exit

A lot of the other answers are overkill if you don't need to worry about the following:

  • Parameters
  • Working Directory (cd %~dp0 will change to the directory containing the batch file)

Pod install is staying on "Setting up CocoaPods Master repo"

Try this command to track its work.

while true; do
  du -sh ~/.cocoapods/
  sleep 3
done

Check if starting characters of a string are alphabetical in T-SQL

You don't need to use regex, LIKE is sufficient:

WHERE my_field LIKE '[a-zA-Z][a-zA-Z]%'

Assuming that by "alphabetical" you mean only latin characters, not anything classified as alphabetical in Unicode.

Note - if your collation is case sensitive, it's important to specify the range as [a-zA-Z]. [a-z] may exclude A or Z. [A-Z] may exclude a or z.

Best XML Parser for PHP

I would have to say SimpleXML takes the cake because it is firstly an extension, written in C, and is very fast. But second, the parsed document takes the form of a PHP object. So you can "query" like $root->myElement.

how to set background image in submit button?

i do it like this cover button and the middle image that

<button><img src="foldername/imagename" width="30px" height= "30px"></button>

Convert absolute path into relative path given a current directory using Bash

This is a corrected, fully functional improvement of the currently best rated solution from @pini (which sadly handle only a few cases)

Reminder : '-z' test if the string is zero-length (=empty) and '-n' test if the string is not empty.

# both $1 and $2 are absolute paths beginning with /
# returns relative path to $2/$target from $1/$source
source=$1
target=$2

common_part=$source # for now
result="" # for now

while [[ "${target#$common_part}" == "${target}" ]]; do
    # no match, means that candidate common part is not correct
    # go up one level (reduce common part)
    common_part="$(dirname $common_part)"
    # and record that we went back, with correct / handling
    if [[ -z $result ]]; then
        result=".."
    else
        result="../$result"
    fi
done

if [[ $common_part == "/" ]]; then
    # special case for root (no common path)
    result="$result/"
fi

# since we now have identified the common part,
# compute the non-common part
forward_part="${target#$common_part}"

# and now stick all parts together
if [[ -n $result ]] && [[ -n $forward_part ]]; then
    result="$result$forward_part"
elif [[ -n $forward_part ]]; then
    # extra slash removal
    result="${forward_part:1}"
fi

echo $result

Test cases :

compute_relative.sh "/A/B/C" "/A"           -->  "../.."
compute_relative.sh "/A/B/C" "/A/B"         -->  ".."
compute_relative.sh "/A/B/C" "/A/B/C"       -->  ""
compute_relative.sh "/A/B/C" "/A/B/C/D"     -->  "D"
compute_relative.sh "/A/B/C" "/A/B/C/D/E"   -->  "D/E"
compute_relative.sh "/A/B/C" "/A/B/D"       -->  "../D"
compute_relative.sh "/A/B/C" "/A/B/D/E"     -->  "../D/E"
compute_relative.sh "/A/B/C" "/A/D"         -->  "../../D"
compute_relative.sh "/A/B/C" "/A/D/E"       -->  "../../D/E"
compute_relative.sh "/A/B/C" "/D/E/F"       -->  "../../../D/E/F"

How to add a border just on the top side of a UIView

Just posting here to help someone looking for adding borders. I have made a few changes in the accepted answer here swift label only border left. Changed width in case UIRectEdge.Top from CGRectGetHeight(self.frame) to CGRectGetWidth(self.frame) and in case UIRectEdge.Bottom from UIScreen.mainScreen().bounds.width to CGRectGetWidth(self.frame) to get borders correctly. Using Swift 2.

Finally the extension is :

extension CALayer {

func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {

    let border = CALayer();

    switch edge {
    case UIRectEdge.Top:
        border.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), thickness); 
        break
    case UIRectEdge.Bottom:
        border.frame = CGRectMake(0, CGRectGetHeight(self.frame) - thickness, CGRectGetWidth(self.frame), thickness)
        break
    case UIRectEdge.Left:
        border.frame = CGRectMake(0, 0, thickness, CGRectGetHeight(self.frame))
        break
    case UIRectEdge.Right:
        border.frame = CGRectMake(CGRectGetWidth(self.frame) - thickness, 0, thickness, CGRectGetHeight(self.frame))
        break
    default:
        break
    }

    border.backgroundColor = color.CGColor;

    self.addSublayer(border)
}

}

How to auto adjust the <div> height according to content in it?

Try with the following mark-up instead of directly specifying height:

_x000D_
_x000D_
.box-centerside {_x000D_
  background: url("../images/greybox-center-bg1.jpg") repeat-x scroll center top transparent;_x000D_
  float: left;_x000D_
  min-height: 100px;_x000D_
  width: 260px;_x000D_
}
_x000D_
<div class="box-centerside">_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
  This is sample content<br>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Drawing an image from a data URL to a canvas

Given a data URL, you can create an image (either on the page or purely in JS) by setting the src of the image to your data URL. For example:

var img = new Image;
img.src = strDataURI;

The drawImage() method of HTML5 Canvas Context lets you copy all or a portion of an image (or canvas, or video) onto a canvas.

You might use it like so:

var myCanvas = document.getElementById('my_canvas_id');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.onload = function(){
  ctx.drawImage(img,0,0); // Or at whatever offset you like
};
img.src = strDataURI;

Edit: I previously suggested in this space that it might not be necessary to use the onload handler when a data URI is involved. Based on experimental tests from this question, it is not safe to do so. The above sequence—create the image, set the onload to use the new image, and then set the src—is necessary for some browsers to surely use the results.

JavaScript: How do I print a message to the error console?

If you are using Firebug and need to support IE, Safari or Opera as well, Firebug Lite adds console.log() support to these browsers.

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

It seems that Maven doesn't like the JAVA_HOME variable to have more than one value. In my case, the error was due to the presence of the additional path C:\Program Files\Java\jax-rs (the whole path was C:\Program Files\Java\jdk1.8.0_20;C:\Program Files\Java\jax-rs).

So I deleted the JAVA_HOME variable and re-created it again with the single value C:\Program Files\Java\jdk1.8.0_20.

How could others, on a local network, access my NodeJS app while it's running on my machine?

One tip that nobody has mentioned yet is to remember to host the app on the LAN-accessible address 0.0.0.0 instead of the default localhost. Firewalls on Mac and Linux are less strict about this address compared to the default localhost address (172.0.0.1).

For example,

gatsby develop --host 0.0.0.0

yarn start --host 0.0.0.0

npm start --host 0.0.0.0

You can then access the address to connect to by entering ifconfig or ipconfig in the terminal. Then try one of the IP addresses on the left that does not end in .255 or .0

How can I make the browser wait to display the page until it's fully loaded?

Hope this code will help

 <html>  
    <head>
        <style type="text/css">
          .js #flash {display: none;}
        </style>
        <script type="text/javascript">
          document.documentElement.className = 'js';
        </script>
      </head>
      <body>
        <!-- the rest of your code goes here -->

        <script type="text/javascript" src="/scripts/jquery.js"></script>
        <script type="text/javascript">
          // Stuff to do as soon as the body finishes loading.
          // No need for $(document).ready() here.
        </script>
      </body>
    </html>

How to set margin of ImageView using code, not xml

sample code is here ,its very easy

LayoutParams params1 = (LayoutParams)twoLetter.getLayoutParams();//twoletter-imageview
                params1.height = 70;
                params1.setMargins(0, 210, 0, 0);//top margin -210 here
                twoLetter.setLayoutParams(params1);//setting layout params
                twoLetter.setImageResource(R.drawable.oo);

Maven does not find JUnit tests to run

Many of these answers were quite useful to me in the past, but I would like to add an additional scenario that has cost me some time, as it may help others in the future:

Make sure that the test classes and methods are public.

My problem was that I was using an automatic test class/methods generation feature of my IDE (IntelliJ) and for some reason it created them as package-private. I find this to be easier to miss than one would expect.

Can clearInterval() be called inside setInterval()?

Yes you can. You can even test it:

_x000D_
_x000D_
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
  console.log(++i);_x000D_
  if (i === 5) clearInterval(timer);_x000D_
  console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
_x000D_
_x000D_

In this example, this timer clears when i reaches 5.

How to properly set Column Width upon creating Excel file? (Column properties)

I have change all columns width in my case as

            worksheet.Columns[1].ColumnWidth = 7;
            worksheet.Columns[2].ColumnWidth = 15;
            worksheet.Columns[3].ColumnWidth = 15;
            worksheet.Columns[4].ColumnWidth = 15;
            worksheet.Columns[5].ColumnWidth = 18;
            worksheet.Columns[6].ColumnWidth = 8;
            worksheet.Columns[7].ColumnWidth = 13;
            worksheet.Columns[8].ColumnWidth = 17;
            worksheet.Columns[9].ColumnWidth = 17;

Note: Columns in worksheet start with 1 not from 0 as in Arrary.

How do I get a computer's name and IP address using VB.NET?

Thanks Shuwaiee

I made a slight change though as using it in a Private Sub already.

Dim GetIPAddress()

Dim strHostName As String

Dim strIPAddress As String

strHostName = System.Net.Dns.GetHostName()

strIPAddress = System.Net.Dns.GetHostByName(strHostName).AddressList(0).ToString()

MessageBox.Show("Host Name: " & strHostName & vbCrLf & "IP Address: " & strIPAddress)

But also made a change to the way the details are displayed so that they can show on seperate lines using & vbCrLf &

MessageBox.Show("Host Name: " & strHostName & vbCrLf & "IP Address: " & strIPAddress)

Hope this helps someone.

How to find all occurrences of an element in a list

A solution using list.index:

def indices(lst, element):
    result = []
    offset = -1
    while True:
        try:
            offset = lst.index(element, offset+1)
        except ValueError:
            return result
        result.append(offset)

It's much faster than the list comprehension with enumerate, for large lists. It is also much slower than the numpy solution if you already have the array, otherwise the cost of converting outweighs the speed gain (tested on integer lists with 100, 1000 and 10000 elements).

NOTE: A note of caution based on Chris_Rands' comment: this solution is faster than the list comprehension if the results are sufficiently sparse, but if the list has many instances of the element that is being searched (more than ~15% of the list, on a test with a list of 1000 integers), the list comprehension is faster.

Private Variables and Methods in Python

Please note that there is no such thing as "private method" in Python. Double underscore is just name mangling:

>>> class A(object):
...     def __foo(self):
...         pass
... 
>>> a = A()
>>> A.__dict__.keys()
['__dict__', '_A__foo', '__module__', '__weakref__', '__doc__']
>>> a._A__foo()

So therefore __ prefix is useful when you need the mangling to occur, for example to not clash with names up or below inheritance chain. For other uses, single underscore would be better, IMHO.

EDIT, regarding confusion on __, PEP-8 is quite clear on that:

If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores. This invokes Python's name mangling algorithm, where the name of the class is mangled into the attribute name. This helps avoid attribute name collisions should subclasses inadvertently contain attributes with the same name.

Note 3: Not everyone likes name mangling. Try to balance the need to avoid accidental name clashes with potential use by advanced callers.

So if you don't expect subclass to accidentally re-define own method with same name, don't use it.

Input type=password, don't let browser remember the password

<input type="password" autocomplete="off" />

I'd just like to add that as a user I think this is very annoying and a hassle to overcome. I strongly recommend against using this as it will more than likely aggravate your users.

Passwords are already not stored in the MRU, and correctly configured public machines will not even save the username.

opening html from google drive

  1. Create a new folder in Drive and share it as "Public on the web."
  2. Upload your content files to this folder.
  3. Right click on your folder and click on Details.
  4. Copy Hosting URL and paste it on your browser.(e.g. https://googledrive.com/host/0B716ywBKT84AcHZfMWgtNk5aeXM)
  5. It will launch index.html if it exist in your folder other wise list all files in your folder.

jQuery Validate - Enable validation for hidden fields

This is working for me.

jQuery("#form_name").validate().settings.ignore = "";

Insert current date into a date column using T-SQL?

To insert a new row into a given table (tblTable) :

INSERT INTO tblTable (DateColumn) VALUES (GETDATE())

To update an existing row :

UPDATE tblTable SET DateColumn = GETDATE()
 WHERE ID = RequiredUpdateID

Note that when INSERTing a new row you will need to observe any constraints which are on the table - most likely the NOT NULL constraint - so you may need to provide values for other columns eg...

 INSERT INTO tblTable (Name, Type, DateColumn) VALUES ('John', 7, GETDATE())

How to obtain the last index of a list?

the best and fast way to obtain last index of a list is using -1 for number of index , for example:

my_list = [0, 1, 'test', 2, 'hi']
print(my_list[-1])

out put is : 'hi'. index -1 in show you last index or first index of the end.

Generate a range of dates using SQL

Ahahaha, here's a funny way I just came up with to do this:

select SYSDATE - ROWNUM
from shipment_weights sw
where ROWNUM < 365;

where shipment_weights is any large table;

Select N random elements from a List<T> in C#

Was thinking about comment by @JohnShedletsky on the accepted answer regarding (paraphrase):

you should be able to to this in O(subset.Length), rather than O(originalList.Length)

Basically, you should be able to generate subset random indices and then pluck them from the original list.

The Method

public static class EnumerableExtensions {

    public static Random randomizer = new Random(); // you'd ideally be able to replace this with whatever makes you comfortable

    public static IEnumerable<T> GetRandom<T>(this IEnumerable<T> list, int numItems) {
        return (list as T[] ?? list.ToArray()).GetRandom(numItems);

        // because ReSharper whined about duplicate enumeration...
        /*
        items.Add(list.ElementAt(randomizer.Next(list.Count()))) ) numItems--;
        */
    }

    // just because the parentheses were getting confusing
    public static IEnumerable<T> GetRandom<T>(this T[] list, int numItems) {
        var items = new HashSet<T>(); // don't want to add the same item twice; otherwise use a list
        while (numItems > 0 )
            // if we successfully added it, move on
            if( items.Add(list[randomizer.Next(list.Length)]) ) numItems--;

        return items;
    }

    // and because it's really fun; note -- you may get repetition
    public static IEnumerable<T> PluckRandomly<T>(this IEnumerable<T> list) {
        while( true )
            yield return list.ElementAt(randomizer.Next(list.Count()));
    }

}

If you wanted to be even more efficient, you would probably use a HashSet of the indices, not the actual list elements (in case you've got complex types or expensive comparisons);

The Unit Test

And to make sure we don't have any collisions, etc.

[TestClass]
public class RandomizingTests : UnitTestBase {
    [TestMethod]
    public void GetRandomFromList() {
        this.testGetRandomFromList((list, num) => list.GetRandom(num));
    }

    [TestMethod]
    public void PluckRandomly() {
        this.testGetRandomFromList((list, num) => list.PluckRandomly().Take(num), requireDistinct:false);
    }

    private void testGetRandomFromList(Func<IEnumerable<int>, int, IEnumerable<int>> methodToGetRandomItems, int numToTake = 10, int repetitions = 100000, bool requireDistinct = true) {
        var items = Enumerable.Range(0, 100);
        IEnumerable<int> randomItems = null;

        while( repetitions-- > 0 ) {
            randomItems = methodToGetRandomItems(items, numToTake);
            Assert.AreEqual(numToTake, randomItems.Count(),
                            "Did not get expected number of items {0}; failed at {1} repetition--", numToTake, repetitions);
            if(requireDistinct) Assert.AreEqual(numToTake, randomItems.Distinct().Count(),
                            "Collisions (non-unique values) found, failed at {0} repetition--", repetitions);
            Assert.IsTrue(randomItems.All(o => items.Contains(o)),
                        "Some unknown values found; failed at {0} repetition--", repetitions);
        }
    }
}

DbEntityValidationException - How can I easily tell what caused the error?

I think "The actual validation errors" may contain sensitive information, and this could be the reason why Microsoft chose to put them in another place (properties). The solution marked here is practical, but it should be taken with caution.

I would prefer to create an extension method. More reasons to this:

  • Keep original stack trace
  • Follow open/closed principle (ie.: I can use different messages for different kind of logs)
  • In production environments there could be other places (ie.: other dbcontext) where a DbEntityValidationException could be thrown.

Fatal error: Namespace declaration statement has to be the very first statement in the script in

I just discovered an easy way to raise this exception; let your text editor default to saving as UTF-8. Unless you can force it to omit the Byte Order Mark, which may not be easy or even possible, depending on your editor, you'll have a "character" in front of the opening <, which will be hidden from view.

Fortunately, when that possibility crossed my mind, I switched my editor (UltraEdit) into hexadecimal mode, which hides nothing, not even Byte Order Marks. Having written code that processes Byte Order Marks for many years, I recognized it instantly.

Save file as ANSI/ASCII, and accept the default 1252 ANSI Latin-1 code page, problem solved!

Using CRON jobs to visit url?

you can use this for url with parameters:

lynx -dump "http://vps-managed.com/tasks.php?code=23456"

lynx is available on all systems by default.

Launch Image does not show up in my iOS App

If you have changed your launch image from a previous image, and observe the following:

  • devices/simulators where the app was previously installed, still show the previous image and refuse to show the new one (uninstalling and reinstalling the app doesn't help)
  • devices/simulators where the app was not previously installed, show the new launch image

It is likely because of the caching of launch image done by iOS. Rebooting the device should solve the problem.

How to stop PHP code execution?

Please see the following information from user Pekka ?

According to the manual, destructors are executed even if the script gets terminated using die() or exit():

The destructor will be called even if script execution is stopped using exit(). Calling exit() in a destructor will prevent the remaining shutdown routines from executing.
According to this PHP: destructor vs register_shutdown_function, the destructor does not get executed when PHP's execution time limit is reached (Confirmed on Apache 2, PHP 5.2 on Windows 7).

The destructor also does not get executed when the script terminates because the memory limit was reached. (Just tested)

The destructor does get executed on fatal errors (Just tested) Update: The OP can't confirm this - there seem to be fatal errors where things are different

It does not get executed on parse errors (because the whole script won't be interpreted)

The destructor will certainly not be executed if the server process crashes or some other exception out of PHP's control occurs.

Referenced in this question Are there any instances when the destructor in PHP is NOT called?

Jquery: How to check if the element has certain css class/style

Question is asking for two different things:

  1. An element has certain class
  2. An element has certain style.

Second question has been already answered. For the first one, I would do it this way:

if($("#someElement").is(".test")){
    // Has class test assigned, eventually combined with other classes
}
else{
    // Does not have it
}

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

Edit existing excel workbooks and sheets with xlrd and xlwt

As I wrote in the edits of the op, to edit existing excel documents you must use the xlutils module (Thanks Oliver)

Here is the proper way to do it:

#xlrd, xlutils and xlwt modules need to be installed.  
#Can be done via pip install <module>
from xlrd import open_workbook
from xlutils.copy import copy

rb = open_workbook("names.xls")
wb = copy(rb)

s = wb.get_sheet(0)
s.write(0,0,'A1')
wb.save('names.xls')

This replaces the contents of the cell located at a1 in the first sheet of "names.xls" with the text "a1", and then saves the document.

Chrome blocks different origin requests

Direct Javascript calls between frames and/or windows are only allowed if they conform to the same-origin policy. If your window and iframe share a common parent domain you can set document.domain to "domain lower") one or both such that they can communicate. Otherwise you'll need to look into something like the postMessage() API.

Printing Lists as Tabular Data

I know that I am late to the party, but I just made a library for this that I think could really help. It is extremely simple, that's why I think you should use it. It is called TableIT.

Basic Use

To use it, first follow the download instructions on the GitHub Page.

Then import it:

import TableIt

Then make a list of lists where each inner list is a row:

table = [
    [4, 3, "Hi"],
    [2, 1, 808890312093],
    [5, "Hi", "Bye"]
]

Then all you have to do is print it:

TableIt.printTable(table)

This is the output you get:

+--------------------------------------------+
| 4            | 3            | Hi           |
| 2            | 1            | 808890312093 |
| 5            | Hi           | Bye          |
+--------------------------------------------+

Field Names

You can use field names if you want to (if you aren't using field names you don't have to say useFieldNames=False because it is set to that by default):


TableIt.printTable(table, useFieldNames=True)

From that you will get:

+--------------------------------------------+
| 4            | 3            | Hi           |
+--------------+--------------+--------------+
| 2            | 1            | 808890312093 |
| 5            | Hi           | Bye          |
+--------------------------------------------+

There are other uses to, for example you could do this:

import TableIt

myList = [
    ["Name", "Email"],
    ["Richard", "[email protected]"],
    ["Tasha", "[email protected]"]
]

TableIt.print(myList, useFieldNames=True)

From that:

+-----------------------------------------------+
| Name                  | Email                 |
+-----------------------+-----------------------+
| Richard               | [email protected] |
| Tasha                 | [email protected]    |
+-----------------------------------------------+

Or you could do:

import TableIt

myList = [
    ["", "a", "b"],
    ["x", "a + x", "a + b"],
    ["z", "a + z", "z + b"]
]

TableIt.printTable(myList, useFieldNames=True)

And from that you get:

+-----------------------+
|       | a     | b     |
+-------+-------+-------+
| x     | a + x | a + b |
| z     | a + z | z + b |
+-----------------------+

Colors

You can also use colors.

You use colors by using the color option (by default it is set to None) and specifying RGB values.

Using the example from above:

import TableIt

myList = [
    ["", "a", "b"],
    ["x", "a + x", "a + b"],
    ["z", "a + z", "z + b"]
]

TableIt.printTable(myList, useFieldNames=True, color=(26, 156, 171))

Then you will get:

enter image description here

Please note that printing colors might not work for you but it does works the exact same as the other libraries that print colored text. I have tested and every single color works. The blue is not messed up either as it would if using the default 34m ANSI escape sequence (if you don't know what that is it doesn't matter). Anyway, it all comes from the fact that every color is RGB value rather than a system default.

More Info

For more info check the GitHub Page

What does the term "Tuple" Mean in Relational Databases?

Tuple is used to refer to a row in a relational database model. But tuple has little bit difference with row.

object==null or null==object?

In Java there is no good reason.

A couple of other answers have claimed that it's because you can accidentally make it assignment instead of equality. But in Java, you have to have a boolean in an if, so this:

if (o = null)

will not compile.

The only time this could matter in Java is if the variable is boolean:

int m1(boolean x)
{
    if (x = true)  // oops, assignment instead of equality

BACKUP LOG cannot be performed because there is no current database backup

Originally, I created a database and then restored the backup file to my new empty database:

Right click on Databases > Restore Database > General : Device: [the path of back up file] ? OK

This was wrong. I shouldn't have first created the database.

Now, instead, I do this:

Right click on Databases > Restore Database > General : Device: [the path of back up file] ? OK

jQuery: keyPress Backspace won't fire?

Use keyup instead of keypress. This gets all the key codes when the user presses something

Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

Try method below:

var mediaStream = null;
    navigator.getUserMedia(
        {
            audio: true,
            video: true
        },
        function (stream) {
            mediaStream = stream;
            mediaStream.stop = function () {
                this.getAudioTracks().forEach(function (track) {
                    track.stop();
                });
                this.getVideoTracks().forEach(function (track) { //in case... :)
                    track.stop();
                });
            };
            /*
             * Rest of your code.....
             * */
        });

    /*
    * somewhere insdie your code you call
    * */
    mediaStream.stop();

window.open target _self v window.location.href?

You can omit window and just use location.href. For example:

location.href = 'http://google.im/';

Encrypt & Decrypt using PyCrypto AES 256

from Crypto import Random
from Crypto.Cipher import AES
import base64

BLOCK_SIZE=16
def trans(key):
     return md5.new(key).digest()

def encrypt(message, passphrase):
    passphrase = trans(passphrase)
    IV = Random.new().read(BLOCK_SIZE)
    aes = AES.new(passphrase, AES.MODE_CFB, IV)
    return base64.b64encode(IV + aes.encrypt(message))

def decrypt(encrypted, passphrase):
    passphrase = trans(passphrase)
    encrypted = base64.b64decode(encrypted)
    IV = encrypted[:BLOCK_SIZE]
    aes = AES.new(passphrase, AES.MODE_CFB, IV)
    return aes.decrypt(encrypted[BLOCK_SIZE:])

AngularJS ui router passing data between states without URL

The params object is included in $stateParams, but won't be part of the url.

1) In the route configuration:

$stateProvider.state('edit_user', {
    url: '/users/:user_id/edit',
    templateUrl: 'views/editUser.html',
    controller: 'editUserCtrl',
    params: {
        paramOne: { objectProperty: "defaultValueOne" },  //default value
        paramTwo: "defaultValueTwo"
    }
});

2) In the controller:

.controller('editUserCtrl', function ($stateParams, $scope) {       
    $scope.paramOne = $stateParams.paramOne;
    $scope.paramTwo = $stateParams.paramTwo;
});

3A) Changing the State from a controller

$state.go("edit_user", {
    user_id: 1,                
    paramOne: { objectProperty: "test_not_default1" },
    paramTwo: "from controller"
});

3B) Changing the State in html

<div ui-sref="edit_user({ user_id: 3, paramOne: { objectProperty: 'from_html1' }, paramTwo: 'fromhtml2' })"></div>

Example Plunker

What's the best free C++ profiler for Windows?

I used Luke Stackwalker and it did the job for my Visual Studio project.

Other interesting projects are:

How to center content in a bootstrap column?

You can add float:none; margin:auto; styling to centerize column content.

How do I Search/Find and Replace in a standard string?

In C++11, you can do this as a one-liner with a call to regex_replace:

#include <string>
#include <regex>

using std::string;

string do_replace( string const & in, string const & from, string const & to )
{
  return std::regex_replace( in, std::regex(from), to );
}

string test = "Remove all spaces";
std::cout << do_replace(test, " ", "") << std::endl;

output:

Removeallspaces

How do I get the path to the current script with Node.js?

var settings = 
    JSON.parse(
        require('fs').readFileSync(
            require('path').resolve(
                __dirname, 
                'settings.json'),
            'utf8'));

Remove element from JSON Object

To iterate through the keys of an object, use a for .. in loop:

for (var key in json_obj) {
    if (json_obj.hasOwnProperty(key)) {
        // do something with `key'
    }
}

To test all elements for empty children, you can use a recursive approach: iterate through all elements and recursively test their children too.

Removing a property of an object can be done by using the delete keyword:

var someObj = {
    "one": 123,
    "two": 345
};
var key = "one";
delete someObj[key];
console.log(someObj); // prints { "two": 345 }

Documentation:

Storing Images in PostgreSQL

Updating to 2012, when we see that image sizes, and number of images, are growing and growing, in all applications...

We need some distinction between "original image" and "processed image", like thumbnail.

As Jcoby's answer says, there are two options, then, I recommend:

  • use blob (Binary Large OBject): for original image store, at your table. See Ivan's answer (no problem with backing up blobs!), PostgreSQL additional supplied modules, How-tos etc.

  • use a separate database with DBlink: for original image store, at another (unified/specialized) database. In this case, I prefer bytea, but blob is near the same. Separating database is the best way for a "unified image webservice".

  • use bytea (BYTE Array): for caching thumbnail images. Cache the little images to send it fast to the web-browser (to avoiding rendering problems) and reduce server processing. Cache also essential metadata, like width and height. Database caching is the easiest way, but check your needs and server configs (ex. Apache modules): store thumbnails at file system may be better, compare performances. Remember that it is a (unified) web-service, then can be stored at a separate database (with no backups), serving many tables. See also PostgreSQL binary data types manual, tests with bytea column, etc.

NOTE1: today the use of "dual solutions" (database+filesystem) is deprecated (!). There are many advantages to using "only database" instead dual. PostgreSQL have comparable performance and good tools for export/import/input/output.

NOTE2: remember that PostgreSQL have only bytea, not have a default Oracle's BLOB: "The SQL standard defines (...) BLOB. The input format is different from bytea, but the provided functions and operators are mostly the same",Manual.


EDIT 2014: I have not changed the original text above today (my answer was Apr 22 '12, now with 14 votes), I am opening the answer for your changes (see "Wiki mode", you can edit!), for proofreading and for updates.
The question is stable (@Ivans's '08 answer with 19 votes), please, help to improve this text.

Find integer index of rows with NaN in pandas dataframe

Here are tests for a few methods:

%timeit np.where(np.isnan(df['b']))[0]
%timeit pd.isnull(df['b']).nonzero()[0]
%timeit np.where(df['b'].isna())[0]
%timeit df.loc[pd.isna(df['b']), :].index

And their corresponding timings:

333 µs ± 9.95 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
280 µs ± 220 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
313 µs ± 128 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
6.84 ms ± 1.59 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

It would appear that pd.isnull(df['DRGWeight']).nonzero()[0] wins the day in terms of timing, but that any of the top three methods have comparable performance.

How can I check whether a option already exist in select by JQuery

It's help me :

  var key = 'Hallo';

   if ( $("#chosen_b option[value='"+key+"']").length == 0 ){
   alert("option not exist!");

    $('#chosen_b').append("<option value='"+key+"'>"+key+"</option>");
    $('#chosen_b').val(key);
   $('#chosen_b').trigger("chosen:updated");
                         }
  });

If a DOM Element is removed, are its listeners also removed from memory?

Yes, the garbage collector will remove them as well. Might not always be the case with legacy browsers though.

Push JSON Objects to array in localStorage

There are a few steps you need to take to properly store this information in your localStorage. Before we get down to the code however, please note that localStorage (at the current time) cannot hold any data type except for strings. You will need to serialize the array for storage and then parse it back out to make modifications to it.

Step 1:

The First code snippet below should only be run if you are not already storing a serialized array in your localStorage session variable.
To ensure your localStorage is setup properly and storing an array, run the following code snippet first:

var a = [];
a.push(JSON.parse(localStorage.getItem('session')));
localStorage.setItem('session', JSON.stringify(a));

The above code should only be run once and only if you are not already storing an array in your localStorage session variable. If you are already doing this skip to step 2.

Step 2:

Modify your function like so:

function SaveDataToLocalStorage(data)
{
    var a = [];
    // Parse the serialized data back into an aray of objects
    a = JSON.parse(localStorage.getItem('session')) || [];
    // Push the new data (whether it be an object or anything else) onto the array
    a.push(data);
    // Alert the array value
    alert(a);  // Should be something like [Object array]
    // Re-serialize the array back into a string and store it in localStorage
    localStorage.setItem('session', JSON.stringify(a));
}

This should take care of the rest for you. When you parse it out, it will become an array of objects.

Hope this helps.

Android: How can I pass parameters to AsyncTask's onPreExecute()?

You can either pass the parameter in the task constructor or when you call execute:

AsyncTask<Object, Void, MyTaskResult>

The first parameter (Object) is passed in doInBackground. The third parameter (MyTaskResult) is returned by doInBackground. You can change them to the types you want. The three dots mean that zero or more objects (or an array of them) may be passed as the argument(s).

public class MyActivity extends AppCompatActivity {

    TextView textView1;
    TextView textView2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);    
        textView1 = (TextView) findViewById(R.id.textView1);
        textView2 = (TextView) findViewById(R.id.textView2);

        String input1 = "test";
        boolean input2 = true;
        int input3 = 100;
        long input4 = 100000000;

        new MyTask(input3, input4).execute(input1, input2);
    }

    private class MyTaskResult {
        String text1;
        String text2;
    }

    private class MyTask extends AsyncTask<Object, Void, MyTaskResult> {
        private String val1;
        private boolean val2;
        private int val3;
        private long val4;


        public MyTask(int in3, long in4) {
            this.val3 = in3;
            this.val4 = in4;

            // Do something ...
        }

        protected void onPreExecute() {
            // Do something ...
        }

        @Override
        protected MyTaskResult doInBackground(Object... params) {
            MyTaskResult res = new MyTaskResult();
            val1 = (String) params[0];
            val2 = (boolean) params[1];

            //Do some lengthy operation    
            res.text1 = RunProc1(val1);
            res.text2 = RunProc2(val2);

            return res;
        }

        @Override
        protected void onPostExecute(MyTaskResult res) {
            textView1.setText(res.text1);
            textView2.setText(res.text2);

        }
    }

}

Utilizing multi core for tar+gzip/bzip compression/decompression

A relatively newer (de)compression tool you might want to consider is zstandard. It does an excellent job of utilizing spare cores, and it has made some great trade-offs when it comes to compression ratio vs. (de)compression time. It is also highly tweak-able depending on your compression ratio needs.

Test if string is a number in Ruby on Rails

no you're just using it wrong. your is_number? has an argument. you called it without the argument

you should be doing is_number?(mystring)

nil detection in Go

In Go 1.13 and later, you can use Value.IsZero method offered in reflect package.

if reflect.ValueOf(v).IsZero() {
    // v is zero, do something
}

Apart from basic types, it also works for Array, Chan, Func, Interface, Map, Ptr, Slice, UnsafePointer, and Struct. See this for reference.

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

So simple. In Nuget Package Manager Console:

Update-Package Microsoft.AspNet.Mvc -Reinstall

Click through div to underlying elements

Yes, you CAN do this.

Using pointer-events: none along with CSS conditional statements for IE11 (does not work in IE10 or below), you can get a cross browser compatible solution for this problem.

Using AlphaImageLoader, you can even put transparent .PNG/.GIFs in the overlay div and have clicks flow through to elements underneath.

CSS:

pointer-events: none;
background: url('your_transparent.png');

IE11 conditional:

filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='your_transparent.png', sizingMethod='scale');
background: none !important;

Here is a basic example page with all the code.

Converting Float to Dollars and Cents

you said that:

`mony = float(1234.5)
print(money)      #output is 1234.5
'${:,.2f}'.format(money)
print(money)

did not work.... Have you coded exactly that way? This should work (see the little difference):

money = float(1234.5)      #next you used format without printing, nor affecting value of "money"
amountAsFormattedString = '${:,.2f}'.format(money)
print( amountAsFormattedString )

How to completely uninstall python 2.7.13 on Ubuntu 16.04

This is what I have after doing purge of all the python versions and reinstalling only 3.6.

root@esp32:/# python
Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) 
[GCC 6.2.0 20161005] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 
root@esp32:/# python3
Python 3.8.0 (default, Dec 15 2019, 14:19:02) 
[GCC 6.2.0 20161005] on linux
Type "help", "copyright", "credits" or "license" for more information.

Also the pip and pip3 commands are totally f up:

root@esp32:/# pip
Traceback (most recent call last):
  File "/usr/local/bin/pip", line 7, in <module>
    from pip._internal.cli.main import main
  File "/usr/local/lib/python3.5/dist-packages/pip/_internal/cli/main.py", line 60
    sys.stderr.write(f"ERROR: {exc}")
                                   ^
SyntaxError: invalid syntax

root@esp32:/# pip3
Traceback (most recent call last):
  File "/usr/local/bin/pip3", line 7, in <module>
    from pip._internal.cli.main import main
  File "/usr/local/lib/python3.5/dist-packages/pip/_internal/cli/main.py", line 60
    sys.stderr.write(f"ERROR: {exc}")
                                   ^
SyntaxError: invalid syntax

I am totally noob at Linux, I just wanted to update Python from 2.x to 3.x so that Platformio could upgrade and now I messed up everything it seems.

Getting first and last day of the current month

var now = DateTime.Now;
var first = new DateTime(now.Year, now.Month, 1);
var last = first.AddMonths(1).AddDays(-1);

You could also use DateTime.DaysInMonth method:

var last = new DateTime(now.Year, now.Month, DateTime.DaysInMonth(now.Year, now.Month));

How to make responsive table

Basically

A responsive table is simply a 100% width table.

You can just set up your table with this CSS:

.table { width: 100%; }

Demo here

You can use media queries to show/hide/manipulate columns according to the screens dimensions by adding a class (or targeting using nth-child, etc):

@media screen and (max-width: 320px) {
    .hide { display: none; }
}

HTML

<td class="hide">Not important</td>

More advanced solutions

If you have a table with a lot of data and you would like to make it readable on small screen devices there are many other solutions:

Difference between web server, web container and application server

Web containers are responsible to provide the run time environment to web applications. It contains components that provide naming context and manages the life cycle of a web application. Web containers are a part of a web server and they generally processes the user request and send a static response.

Servlet containers are the one where JSP created components reside. They are basically responsible to provide dynamic content as per the user request. Basically, Web containers reply with a static content as per the user request, but Servlets can create the dynamic pages.

Looking for a short & simple example of getters/setters in C#

In C#, Properties represent your Getters and Setters.

Here's an example:

public class PropertyExample
{
    private int myIntField = 0;

    public int MyInt
    {
        // This is your getter.
        // it uses the accessibility of the property (public)
        get
        {
            return myIntField;
        }
        // this is your setter
        // Note: you can specify different accessibility
        // for your getter and setter.
        protected set
        {
            // You can put logic into your getters and setters
            // since they actually map to functions behind the scenes
            DoSomeValidation(value)
            {
                // The input of the setter is always called "value"
                // and is of the same type as your property definition
                myIntField = value;
            }
        }
    }
}

You would access this property just like a field. For example:

PropertyExample example = new PropertyExample();
example.MyInt = 4; // sets myIntField to 4
Console.WriteLine( example.MyInt ); // prints 4

A few other things to note:

  1. You don't have to specifiy both a getter and a setter, you can omit either one.
  2. Properties are just "syntactic sugar" for your traditional getter and setter. The compiler will actually build get_ and set_ functions behind the scenes (in the compiled IL) and map all references to your property to those functions.

How to assign an exec result to a sql variable?

This will work if you wish to simply return an integer:

DECLARE @ResultForPos INT 
EXEC @ResultForPos = storedprocedureName 'InputParameter'
SELECT @ResultForPos

onclick event pass <li> id or value

Try like this...

<script>
function getPaging(str) {
  $("#loading-content").load("dataSearch.php?"+str, hideLoader);
}
</script>

<li onclick="getPaging(this.id)" id="1">1</li>
<li onclick="getPaging(this.id)" id="2">2</li>

or unobtrusively

$(function() {
  $("li").on("click",function() {
    showLoader();
    $("#loading-content").load("dataSearch.php?"+this.id, hideLoader);
  });
});

using just

<li id="1">1</li>
<li id="2">2</li>

Remove leading or trailing spaces in an entire column of data

Without using a formula you can do this with 'Text to columns'.

  • Select the column that has the trailing spaces in the cells.
  • Click 'Text to columns' from the 'Data' tab, then choose option 'Fixed width'.
  • Set a break line so the longest text will fit. If your largest cell has 100 characters you can set the breakline on 200 or whatever you want.
  • Finish the operation.
  • You can now delete the new column Excel has created.

The 'side-effect' is that Excel has removed all trailing spaces in the original column.

How to populate HTML dropdown list with values from database

I'd suggest following a few debugging steps.

First run the query directly against the DB. Confirm it is bringing results back. Even with something as simple as this you can find you've made a mistake, or the table is empty, or somesuch oddity.

If the above is ok, then try looping and echoing out the contents of $row just directly into the HTML to see what you've getting back in the mysql_query - see if it matches what you got directly in the DB.

If your data is output onto the page, then look at what's going wrong in your HTML formatting.

However, if nothing is output from $row, then figure out why the mysql_query isn't working e.g. does the user have permission to query that DB, do you have an open DB connection, can the webserver connect to the DB etc [something on these lines can often be a gotcha]

Changing your query slightly to

$sql = mysql_query("SELECT username FROM users") or die(mysql_error());  

may help to highlight any errors: php manual

<DIV> inside link (<a href="">) tag

I think you should do it the other way round. Define your Divs and have your a href within each Div, pointing to different links

How to read a list of files from a folder using PHP?

This is what I like to do:

$files = array_values(array_filter(scandir($path), function($file) use ($path) { 
    return !is_dir($path . '/' . $file);
}));

foreach($files as $file){
    echo $file;
}

How to list all users in a Linux group?

Here's a very simple awk script that takes into account all common pitfalls listed in the other answers:

getent passwd | awk -F: -v group_name="wheel" '
  BEGIN {
    "getent group " group_name | getline groupline;
    if (!groupline) exit 1;
    split(groupline, groupdef, ":");
    guid = groupdef[3];
    split(groupdef[4], users, ",");
    for (k in users) print users[k]
  }
  $4 == guid {print $1}'

I'm using this with my ldap-enabled setup, runs on anything with standards-compliant getent & awk, including solaris 8+ and hpux.

Parse query string in JavaScript

Following on from my comment to the answer @bobby posted, here is the code I would use:

    function parseQuery(str)
        {
        if(typeof str != "string" || str.length == 0) return {};
        var s = str.split("&");
        var s_length = s.length;
        var bit, query = {}, first, second;
        for(var i = 0; i < s_length; i++)
            {
            bit = s[i].split("=");
            first = decodeURIComponent(bit[0]);
            if(first.length == 0) continue;
            second = decodeURIComponent(bit[1]);
            if(typeof query[first] == "undefined") query[first] = second;
            else if(query[first] instanceof Array) query[first].push(second);
            else query[first] = [query[first], second]; 
            }
        return query;
        }

This code takes in the querystring provided (as 'str') and returns an object. The string is split on all occurances of &, resulting in an array. the array is then travsersed and each item in it is split by "=". This results in sub arrays wherein the 0th element is the parameter and the 1st element is the value (or undefined if no = sign). These are mapped to object properties, so for example the string "hello=1&another=2&something" is turned into:

{
hello: "1",
another: "2",
something: undefined
}

In addition, this code notices repeating reoccurances such as "hello=1&hello=2" and converts the result into an array, eg:

{
hello: ["1", "2"]
}

You'll also notice it deals with cases in whih the = sign is not used. It also ignores if there is an equal sign straight after an & symbol.

A bit overkill for the original question, but a reusable solution if you ever need to work with querystrings in javascript :)

How can I calculate the difference between two ArrayLists?

Although this is a very old question in Java 8 you could do something like

 List<String> a1 = Arrays.asList("2009-05-18", "2009-05-19", "2009-05-21");
 List<String> a2 = Arrays.asList("2009-05-18", "2009-05-18", "2009-05-19", "2009-05-19", "2009-05-20", "2009-05-21","2009-05-21", "2009-05-22");

 List<String> result = a2.stream().filter(elem -> !a1.contains(elem)).collect(Collectors.toList());

PYODBC--Data source name not found and no default driver specified

You need to download Microsoft ODBC Driver 13 for SQL Server from Microsoft ODBC Driver 13

Where is body in a nodejs http.get response?

You can't get the body of the response from the return value of http.get().

http.get() doesn't return a response object. It returns the request object (http.clientRequest). So, there isn't any way to get the body of the response from the return value of http.get().

I know it's an old question, but reading the documentation you linked to shows that this was the case even when you posted it.

How to use store and use session variables across pages?

Try this:

<!-- first page -->
<?php
  session_start(); 
  session_register('myvar');
  $_SESSION['myvar'] == 'myvalue';
?>

<!-- second page -->
<?php
    session_start();
    echo("1");
    if(session_is_registered('myvar'))
    {
        echo("2");
       if($_SESSION['myvar'] == 'myvalue')
       {
           echo("3");
           exit;
       }
    }
    ?>

How do I make Git ignore file mode (chmod) changes?

Simple solution:

Hit this Simple command in project Folder(it won't remove your original changes) ...it will only remove changes that had been done while you changed project folder permission

command is below:

git config core.fileMode false

Why this all unnecessary file get modified: because you have changed the project folder permissions with commend sudo chmod -R 777 ./yourProjectFolder

when will you check changes what not you did? you found like below while using git diff filename

old mode 100644
new mode 100755

Inline Form nested within Horizontal Form in Bootstrap 3

Another option is to put all of the fields that you want on a single line within a single form-group.

See demo here

<form class="form-horizontal">
    <div class="form-group">
        <label for="name" class="col-xs-2 control-label">Name</label>
        <div class="col-xs-10">
            <input type="text" class="form-control col-sm-10" name="name" placeholder="name"/>
        </div>
    </div>

    <div class="form-group">
        <label for="birthday" class="col-xs-3 col-sm-2 control-label">Birthday</label>
        <div class="col-xs-3">
            <input type="text" class="form-control" placeholder="year"/>
        </div>
        <div class="col-xs-3">
            <input type="text" class="form-control" placeholder="month"/>
        </div>
        <div class="col-xs-3">
            <input type="text" class="form-control" placeholder="day"/>
        </div>    
    </div>
</form>

Using G++ to compile multiple .cpp and .h files

You can use several g++ commands and then link, but the easiest is to use a traditional Makefile or some other build system: like Scons (which are often easier to set up than Makefiles).

How do I use WPF bindings with RelativeSource?

If you want to bind to another property on the object:

{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}

If you want to get a property on an ancestor:

{Binding Path=PathToProperty,
    RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}

If you want to get a property on the templated parent (so you can do 2 way bindings in a ControlTemplate)

{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}

or, shorter (this only works for OneWay bindings):

{TemplateBinding Path=PathToProperty}

What to do with "Unexpected indent" in python?

One issue which doesn't seem to have been mentioned is that this error can crop up due to a problem with the code that has nothing to do with indentation.

For example, take the following script:

def add_one(x):
    try:
        return x + 1
add_one(5)

This returns an IndentationError: unexpected unindent when the problem is of course a missing except: statement.

My point: check the code above where the unexpected (un)indent is reported!

Create dynamic variable name

No. That is not possible. You should use an array instead:

name[i] = i;

In this case, your name+i is name[i].

Creating a copy of an object in C#

You could do:

class myClass : ICloneable
{
    public String test;
    public object Clone()
    {
        return this.MemberwiseClone();
    }
}

then you can do

myClass a = new myClass();
myClass b = (myClass)a.Clone();

N.B. MemberwiseClone() Creates a shallow copy of the current System.Object.

Show or hide element in React

React circa 2020

In the onClick callback, call the state hook's setter function to update the state and re-render:

_x000D_
_x000D_
const Search = () => {_x000D_
  const [showResults, setShowResults] = React.useState(false)_x000D_
  const onClick = () => setShowResults(true)_x000D_
  return (_x000D_
    <div>_x000D_
      <input type="submit" value="Search" onClick={onClick} />_x000D_
      { showResults ? <Results /> : null }_x000D_
    </div>_x000D_
  )_x000D_
}_x000D_
_x000D_
const Results = () => (_x000D_
  <div id="results" className="search-results">_x000D_
    Some Results_x000D_
  </div>_x000D_
)_x000D_
_x000D_
ReactDOM.render(<Search />, document.querySelector("#container"))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>_x000D_
_x000D_
<div id="container">_x000D_
  <!-- This element's contents will be replaced with your component. -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

JSFiddle

React circa 2014

The key is to update the state of the component in the click handler using setState. When the state changes get applied, the render method gets called again with the new state:

_x000D_
_x000D_
var Search = React.createClass({_x000D_
    getInitialState: function() {_x000D_
        return { showResults: false };_x000D_
    },_x000D_
    onClick: function() {_x000D_
        this.setState({ showResults: true });_x000D_
    },_x000D_
    render: function() {_x000D_
        return (_x000D_
            <div>_x000D_
                <input type="submit" value="Search" onClick={this.onClick} />_x000D_
                { this.state.showResults ? <Results /> : null }_x000D_
            </div>_x000D_
        );_x000D_
    }_x000D_
});_x000D_
_x000D_
var Results = React.createClass({_x000D_
    render: function() {_x000D_
        return (_x000D_
            <div id="results" className="search-results">_x000D_
                Some Results_x000D_
            </div>_x000D_
        );_x000D_
    }_x000D_
});_x000D_
_x000D_
ReactDOM.render( <Search /> , document.getElementById('container'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.min.js"></script>_x000D_
_x000D_
<div id="container">_x000D_
  <!-- This element's contents will be replaced with your component. -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

JSFiddle

Hadoop: «ERROR : JAVA_HOME is not set»

Make sure that you have removed the comment tag and changed your JAVA_HOME in the hadoop-env.sh as well as the appropriate .bashrc and/or .profile:

# export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk

should be

export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk

You can set your JAVA_HOME and PATH for all users (make sure you haven't previously set this to the wrong path) in /etc/profile.

Also, don't forget to activate the new change by logging-out/in or by executing source /etc/profile.

Best Java obfuscator?

I used Allatori and it did its job pretty well.

Fixing npm path in Windows 8 and 10

Installed Node Version Manager (NVM) for Windows: https://github.com/coreybutler/nvm-windows

I'm using Windows 10 - 64 bit so I run... Commands:

  • nvm arch 64 (to make default the 64 bit executable)
  • nvm list (to list all available node versions)
  • nvm install 8.0.0 (to download node version 8.0.0 - you can pick any)
  • nvm use 8.0.0 (to use that specific version)

In my case I had to just switch to version 8.5.0 and then switch back again to 8.0.0 and it was fixed. Apparently NVM sets the PATH variables whenever you do that switch.

MySQL SELECT AS combine two columns into one

If both columns can contain NULL, but you still want to merge them to a single string, the easiest solution is to use CONCAT_WS():

SELECT FirstName AS First_Name
     , LastName AS Last_Name
     , CONCAT_WS('', ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
  FROM TABLE1

This way you won't have to check for NULL-ness of each column separately.

Alternatively, if both columns are actually defined as NOT NULL, CONCAT() will be quite enough:

SELECT FirstName AS First_Name
     , LastName AS Last_Name
     , CONCAT(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
  FROM TABLE1

As for COALESCE, it's a bit different beast: given the list of arguments, it returns the first that's not NULL.

How can I change my Cygwin home folder after installation?

Starting with Cygwin 1.7.34, the recommended way to do this is to add a custom db_home setting to /etc/nsswitch.conf. A common wish when doing this is to make your Cygwin home directory equal to your Windows user profile directory. This setting will do that:

db_home: windows

Or, equivalently:

db_home: /%H

You need to use the latter form if you want some variation on this scheme, such as to segregate your Cygwin home files into a subdirectory of your Windows user profile directory:

db_home: /%H/cygwin

There are several other alternative schemes for the windows option plus several other % tokens you can use instead of %H or in addition to it. See the nsswitch.conf syntax description in the Cygwin User Guide for details.

If you installed Cygwin prior to 1.7.34 or have run its mkpasswd utility so that you have an /etc/passwd file, you can change your Cygwin home directory by editing your user's entry in that file. Your home directory is the second-to-last element on your user's line in /etc/passwd

Whichever way you do it, this causes the HOME environment variable to be set during shell startup.²

See this FAQ item for more on the topic.


Footnotes:

  1. Consider moving /etc/passwd and /etc/group out of the way in order to use the new SAM/AD-based mechanism instead.

  2. While it is possible to simply set %HOME% via the Control Panel, it is officially discouraged. Not only does it unceremoniously override the above mechanisms, it doesn't always work, such as when running shell scripts via cron.

RegEx for validating an integer with a maximum length of 10 characters

1 to 10:

[0-9]{1,10}

In .NET (and not only, see the comment below) also valid (with a stipulation) this:

\d{1,10}

C#:

var regex = new Regex("^[0-9]{1,10}$", RegexOptions.Compiled);
regex.IsMatch("1"); // true
regex.IsMatch("12"); // true
..
regex.IsMatch("1234567890"); // true
regex.IsMatch(""); // false
regex.IsMatch(" "); // true
regex.IsMatch("a"); // false

P.S. Here's a very useful sandbox.

PHP upload image

You need to add two new file one is index.html, copy and paste the below code and other is imageup.php which will upload your image

 <form action="imageup.php" method="post" enctype="multipart/form-data">
 <input type="file" name="banner" >
 <input type="submit" value="submit">
 </form>

 imageup.php
 <?php
 $banner=$_FILES['banner']['name']; 
 $expbanner=explode('.',$banner);
 $bannerexptype=$expbanner[1];
 date_default_timezone_set('Australia/Melbourne');
 $date = date('m/d/Yh:i:sa', time());
 $rand=rand(10000,99999);
 $encname=$date.$rand;
 $bannername=md5($encname).'.'.$bannerexptype;
 $bannerpath="uploads/banners/".$bannername;
 move_uploaded_file($_FILES["banner"]["tmp_name"],$bannerpath);
 ?>

The above code will upload your image with encrypted name

CSS: Truncate table cells, but fit as much as possible

There's a much easier and more elegant solution.

Within the table-cell that you want to apply truncation, simply include a container div with css table-layout: fixed. This container takes the full width of the parent table cell, so it even acts responsive.

Make sure to apply truncation to the elements in the table.

Works from IE8+

<table>
  <tr>
    <td>
     <div class="truncate">
       <h1 class="truncated">I'm getting truncated because I'm way too long to fit</h1>
     </div>
    </td>
    <td class="some-width">
       I'm just text
    </td>
  </tr>
</table>

and css:

    .truncate {
      display: table;
      table-layout: fixed;
      width: 100%;
    }

    h1.truncated {
      overflow-x: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

here's a working Fiddle https://jsfiddle.net/d0xhz8tb/

Display date/time in user's locale format and time offset

Once you have your date object constructed, here's a snippet for the conversion:

The function takes a UTC formatted Date object and format string.
You will need a Date.strftime prototype.

function UTCToLocalTimeString(d, format) {
    if (timeOffsetInHours == null) {
        timeOffsetInHours = (new Date().getTimezoneOffset()/60) * (-1);
    }
    d.setHours(d.getHours() + timeOffsetInHours);

    return d.strftime(format);
}

Run reg command in cmd (bat file)?

In command line it's better to use REG tool rather than REGEDIT:

REG IMPORT yourfile.reg

REG is designed for console mode, while REGEDIT is for graphical mode. This is why running regedit.exe /S yourfile.reg is a bad idea, since you will not be notified if the there's an error, whereas REG Tool will prompt:

>  REG IMPORT missing_file.reg

ERROR: Error opening the file. There may be a disk or file system error.

>  %windir%\System32\reg.exe /?

REG Operation [Parameter List]

  Operation  [ QUERY   | ADD    | DELETE  | COPY    |
               SAVE    | LOAD   | UNLOAD  | RESTORE |
               COMPARE | EXPORT | IMPORT  | FLAGS ]

Return Code: (Except for REG COMPARE)

  0 - Successful
  1 - Failed

For help on a specific operation type:

  REG Operation /?

Examples:

  REG QUERY /?
  REG ADD /?
  REG DELETE /?
  REG COPY /?
  REG SAVE /?
  REG RESTORE /?
  REG LOAD /?
  REG UNLOAD /?
  REG COMPARE /?
  REG EXPORT /?
  REG IMPORT /?
  REG FLAGS /?

Changing background color of selected cell?

In Swift

let v = UIView()
    v.backgroundColor = self.darkerColor(color)
    cell?.selectedBackgroundView = v;

...

func darkerColor( color: UIColor) -> UIColor {
    var h = CGFloat(0)
    var s = CGFloat(0)
    var b = CGFloat(0)
    var a = CGFloat(0)
    let hueObtained = color.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
    if hueObtained {
        return UIColor(hue: h, saturation: s, brightness: b * 0.75, alpha: a)
    }
    return color
}

Using Rsync include and exclude options to include directory and file by pattern

Here's my "teach a person to fish" answer:

Rsync's syntax is definitely non-intuitive, but it is worth understanding.

  1. First, use -vvv to see the debug info for rsync.
$ rsync -nr -vvv --include="**/file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/

[sender] hiding directory 1280000000 because of pattern *
[sender] hiding directory 1260000000 because of pattern *
[sender] hiding directory 1270000000 because of pattern *

The key concept here is that rsync applies the include/exclude patterns for each directory recursively. As soon as the first include/exclude is matched, the processing stops.

The first directory it evaluates is /Storage/uploads. Storage/uploads has 1280000000/, 1260000000/, 1270000000/ dirs/files. None of them match file_11*.jpg to include. All of them match * to exclude. So they are excluded, and rsync ends.

  1. The solution is to include all dirs (*/) first. Then the first dir component will be 1260000000/, 1270000000/, 1280000000/ since they match */. The next dir component will be 1260000000/. In 1260000000/, file_11_00.jpg matches --include="file_11*.jpg", so it is included. And so forth.
$ rsync -nrv --include='*/' --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/

./
1260000000/
1260000000/file_11_00.jpg
1260000000/file_11_01.jpg
1270000000/
1270000000/file_11_00.jpg
1270000000/file_11_01.jpg
1280000000/
1280000000/file_11_00.jpg
1280000000/file_11_01.jpg

https://download.samba.org/pub/rsync/rsync.1

Simplest way to read json from a URL in java

If you don't mind using a couple libraries it can be done in a single line.

Include Apache Commons IOUtils & json.org libraries.

JSONObject json = new JSONObject(IOUtils.toString(new URL("https://graph.facebook.com/me"), Charset.forName("UTF-8")));

How to split a string content into an array of strings in PowerShell?

[string[]]$recipients = $address.Split('; ',[System.StringSplitOptions]::RemoveEmptyEntries)

How to edit incorrect commit message in Mercurial?

In TortoiseHg, right-click on the revision you want to modify. Choose Modify History->Import MQ. That will convert all the revisions up to and including the selected revision from Mercurial changesets into Mercurial Queue patches. Select the Patch you want to modify the message for, and it should automatically change the screen to the MQ editor. Edit the message which is in the middle of the screen, then click QRefresh. Finally, right click on the patch and choose Modify History->Finish Patch, which will convert it from a patch back into a change set.

Oh, this assumes that MQ is an active extension for TortoiseHG on this repository. If not, you should be able to click File->Settings, click Extensions, and click the mq checkbox. It should warn you that you have to close TortoiseHg before the extension is active, so close and reopen.

VSCode cannot find module '@angular/core' or any other modules

I had the same problem. I resolved it by clearing npm cache which is at "C:\Users\Administrator\AppData\Roaming\npm-cache"

Or you can simply run:

npm cache clean --force

and then close vscode, and then open your folder again.

Getting CheckBoxList Item values

Try to use this :

 private void button1_Click(object sender, EventArgs e)
    {

        for (int i = 0; i < chBoxListTables.Items.Count; i++)
            if (chBoxListTables.GetItemCheckState(i) == CheckState.Checked)
            {
               txtBx.text += chBoxListTables.Items[i].ToString() + " \n"; 

            }
    }

How to create a date object from string in javascript

Always, for any issue regarding the JavaScript spec in practical, I will highly recommend the Mozilla Developer Network, and their JavaScript reference.

As it states in the topic of the Date object about the argument variant you use:

new Date(year, month, day [, hour, minute, second, millisecond ])

And about the months parameter:

month Integer value representing the month, beginning with 0 for January to 11 for December.

Clearly, then, you should use the month number 10 for November.

P.S.: The reason why I recommend the MDN is the correctness, good explanation of things, examples, and browser compatibility chart.

How can I shuffle an array?

Use the modern version of the Fisher–Yates shuffle algorithm:

/**
 * Shuffles array in place.
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

ES2015 (ES6) version

/**
 * Shuffles array in place. ES6 version
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

Note however, that swapping variables with destructuring assignment causes significant performance loss, as of October 2017.

Use

var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);

Implementing prototype

Using Object.defineProperty (method taken from this SO answer) we can also implement this function as a prototype method for arrays, without having it show up in loops such as for (i in arr). The following will allow you to call arr.shuffle() to shuffle the array arr:

Object.defineProperty(Array.prototype, 'shuffle', {
    value: function() {
        for (let i = this.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this[i], this[j]] = [this[j], this[i]];
        }
        return this;
    }
});