Programs & Examples On #Winapp

ComboBox: Adding Text and Value to an Item (no Binding Source)

Don't know if this will work for the situation given in the original post (never mind the fact that this is two years later), but this example works for me:

Hashtable htImageTypes = new Hashtable();
htImageTypes.Add("JPEG", "*.jpg");
htImageTypes.Add("GIF", "*.gif");
htImageTypes.Add("BMP", "*.bmp");

foreach (DictionaryEntry ImageType in htImageTypes)
{
    cmbImageType.Items.Add(ImageType);
}
cmbImageType.DisplayMember = "key";
cmbImageType.ValueMember = "value";

To read your value back out, you'll have to cast the SelectedItem property to a DictionaryEntry object, and you can then evaluate the Key and Value properties of that. For instance:

DictionaryEntry deImgType = (DictionaryEntry)cmbImageType.SelectedItem;
MessageBox.Show(deImgType.Key + ": " + deImgType.Value);

How to solve '...is a 'type', which is not valid in the given context'? (C#)

CERAS is a class name which cannot be assigned. As the class implements IDisposable a typical usage would be:

using (CERas.CERAS ceras = new CERas.CERAS())
{
    // call some method on ceras
}

Split string into strings by length?

Here is a one-liner that doesn't need to know the length of the string beforehand:

from functools import partial
from StringIO import StringIO

[l for l in iter(partial(StringIO(data).read, 4), '')]

If you have a file or socket, then you don't need the StringIO wrapper:

[l for l in iter(partial(file_like_object.read, 4), '')]

How to match a substring in a string, ignoring case

import re
if re.search('(?i)Mandy Pande:', line):
    ...

How to prevent multiple definitions in C?

If you're using Visual Studio you could also do "#pragma once" at the top of the headerfile to achieve the same thing as the "#ifndef ..."-wrapping. Some other compilers probably support it as well .. .. However, don't do this :D Stick with the #ifndef-wrapping to achieve cross-compiler compatibility. I just wanted to let you know that you could also do #pragma once, since you'll probably meet this statement quite a bit when reading other peoples code.

Good luck with it

Format a datetime into a string with milliseconds

I assume you mean you're looking for something that is faster than datetime.datetime.strftime(), and are essentially stripping the non-alpha characters from a utc timestamp.

You're approach is marginally faster, and I think you can speed things up even more by slicing the string:

>>> import timeit
>>> t=timeit.Timer('datetime.utcnow().strftime("%Y%m%d%H%M%S%f")','''
... from datetime import datetime''')
>>> t.timeit(number=10000000)
116.15451288223267

>>> def replaceutc(s):
...     return s\
...         .replace('-','') \
...         .replace(':','') \
...         .replace('.','') \
...         .replace(' ','') \
...         .strip()
... 
>>> t=timeit.Timer('replaceutc(str(datetime.datetime.utcnow()))','''
... from __main__ import replaceutc
... import datetime''')
>>> t.timeit(number=10000000)
77.96774983406067

>>> def sliceutc(s):
...     return s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:]
... 
>>> t=timeit.Timer('sliceutc(str(datetime.utcnow()))','''
... from __main__ import sliceutc
... from datetime import datetime''')
>>> t.timeit(number=10000000)
62.378515005111694

How to use (install) dblink in PostgreSQL?

On linux, find dblink.sql, then execute in the postgresql console something like this to create all required functions:

\i /usr/share/postgresql/8.4/contrib/dblink.sql 

you might need to install the contrib packages: sudo apt-get install postgresql-contrib

What is this: [Ljava.lang.Object;?

If you are here because of the Liquibase error saying:

Caused By: Precondition Error
...
Can't detect type of array [Ljava.lang.Short

and you are using

not {
  indexExists()
}

precondition multiple times, then you are facing an old bug: https://liquibase.jira.com/browse/CORE-1342

We can try to execute an above check using bare sqlCheck(Postgres):

SELECT COUNT(i.relname)
FROM
    pg_class t,
    pg_class i,
    pg_index ix
WHERE
    t.oid = ix.indrelid
    and i.oid = ix.indexrelid
    and t.relkind = 'r'
    and t.relname = 'tableName'
    and i.relname = 'indexName';

where tableName - is an index table name and indexName - is an index name

Centering a Twitter Bootstrap button

Since you want to center the button, and not the text, what I've done in the past is add a class, then use that class to center the button:

<button class="btn btn-large btn-primary newclass" type="button">Submit</button>

and the CSS would be:

.btn.newclass {width:25%; display:block; margin: 0 auto;}

The "width" value is up to you, and you can play with that to get the right look.

Steve

How to compare two lists in python?

Given the code you provided in comments, I assume you want to do this:

>>> dateList = "Thu Sep 16 13:14:15 CDT 2010".split()
>>> sdateList = "Thu Sep 16 14:14:15 CDT 2010".split()
>>> dateList == sdataList
false

The split-method of the string returns a list. A list in Python is very different from an array. == in this case does an element-wise comparison of the two lists and returns if all their elements are equal and the number and order of the elements is the same. Read the documentation.

How to disable an Android button?

WRONG WAY IN LISTENER TO USE VARIABLE INSTEAD OF PARAMETER!!!

btnSend.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        btnSend.setClickable(false);

    }
});

RIGHT WAY:

btnSend.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

        /** check given view  by assertion or cast as u wish */
        if(v instance of Button) {

            /** cast */
            Button button = (Button) v;

            /** we can perform some check up */
            if(button.getId() == EXPECTED_ID) {

                /** disable view */
                button.setEnabled(false)            
                button.setClickable(false); 
            }

        } else {

             /** you can for example find desired view by root view  */
             Button bt = (Button) v.getRootView().findViewById(R.id.btId);

             /*check for button */
             if(bt!=null) {

                 /** disable button view */
                 ...
             } else {
                 /** according to @jeroen-bollen remark
                   * we made assumption that we expected a view
                   * of type button here in other any case  
                   */
                  throw new IllegalArgumentException("Wrong argument: " +
                         "View passed to method is not a Button type!");
             }
          }
       }
    });

EDIT: In reply to @jeroen-bollen

 View.OnClickListener 

is Interface definition for a callback to be invoked when a view is clicked.

with method definition

void onClick(View v);

when the view is clicked the View class object makes callback to method onClick() sending as parameter itself, so null view parameter should not occur if it does it's an Assertion Error it could happen for example when View object class was destroyed in meanwhile (for example collected by GC) or method was tampered due to hack

little about instanceof & null

JLS / 15.20.2. Type Comparison Operator instanceof

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException.

Otherwise the result is false.


three words from the Author

IF U ASK WHY ?

MOSTLY TO AVOID NullPointerException

Little more code will save your time on later bug tracking in your code & reduces the occurrence of abnomalies.

consider following example:

View.OnClickListener listener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        btnSend.setClickable(false);

    }
});

btnSend.setOnClickListener(listener)
btnCancel.setOnClickListener(listener)  

Converting integer to binary in python

The best way is to specify the format.

format(a, 'b')

returns the binary value of a in string format.

To convert a binary string back to integer, use int() function.

int('110', 2)

returns integer value of binary string.

ImportError in importing from sklearn: cannot import name check_build

For me, I was upgrading the existing code into new setup by installing Anaconda from fresh with latest python version(3.7) For this,

from sklearn import cross_validation, 
from sklearn.grid_search import GridSearchCV

to

from sklearn.model_selection import GridSearchCV,cross_validate

Amazon S3 and Cloudfront cache, how to clear cache or synchronize their cache

Don't use invalidations. They cannot be reverted and you will be charged. They only way it works for me is reducing the TTL and wait.

Regards

AngularJS accessing DOM elements inside directive template

You could write a directive for this, which simply assigns the (jqLite) element to the scope using an attribute-given name.

Here is the directive:

app.directive("ngScopeElement", function () {
  var directiveDefinitionObject = {

    restrict: "A",

    compile: function compile(tElement, tAttrs, transclude) {
      return {
          pre: function preLink(scope, iElement, iAttrs, controller) {
            scope[iAttrs.ngScopeElement] = iElement;
          }
        };
    }
  };

  return directiveDefinitionObject;
});

Usage:

app.directive("myDirective", function() {
    return {
        template: '<div><ul ng-scope-element="list"><li ng-repeat="item in items"></ul></div>',
        link: function(scope, element, attrs) {
            scope.list[0] // scope.list is the jqlite element, 
                          // scope.list[0] is the native dom element
        }
    }
});

Some remarks:

  • Due to the compile and link order for nested directives you can only access scope.list from myDirectives postLink-Function, which you are very likely using anyway
  • ngScopeElement uses a preLink-function, so that directives nested within the element having ng-scope-element can already access scope.list
  • not sure how this behaves performance-wise

Mock a constructor with parameter

To my knowledge, you can't mock constructors with mockito, only methods. But according to the wiki on the Mockito google code page there is a way to mock the constructor behavior by creating a method in your class which return a new instance of that class. then you can mock out that method. Below is an excerpt directly from the Mockito wiki:

Pattern 1 - using one-line methods for object creation

To use pattern 1 (testing a class called MyClass), you would replace a call like

   Foo foo = new Foo( a, b, c );

with

   Foo foo = makeFoo( a, b, c );

and write a one-line method

   Foo makeFoo( A a, B b, C c ) { 
        return new Foo( a, b, c );
   }

It's important that you don't include any logic in the method; just the one line that creates the object. The reason for this is that the method itself is never going to be unit tested.

When you come to test the class, the object that you test will actually be a Mockito spy, with this method overridden, to return a mock. What you're testing is therefore not the class itself, but a very slightly modified version of it.

Your test class might contain members like

  @Mock private Foo mockFoo;
  private MyClass toTest = spy(new MyClass());

Lastly, inside your test method you mock out the call to makeFoo with a line like

  doReturn( mockFoo )
      .when( toTest )
      .makeFoo( any( A.class ), any( B.class ), any( C.class ));

You can use matchers that are more specific than any() if you want to check the arguments that are passed to the constructor.

If you're just wanting to return a mocked object of your class I think this should work for you. In any case you can read more about mocking object creation here:

http://code.google.com/p/mockito/wiki/MockingObjectCreation

The name does not exist in the namespace error in XAML

I had the same symptoms "The name does not exist in the namespace error", but the cause turned out to be different. I had a C: drive crash and had to reinstall Visual Studio 2017. I restored my source code files and opened the solution. Built it. No dice. As well as the "Name does not exist in the namespace" errors I noticed my sub-projects complaining that they couldn't find a MyProject.cs file ('MyProject' is not the actual project name, just used here as an example). I had a hunt for where MyProject.cs had gone, then remembered that there was never any such file! I looked in the Properties folders of each sub-project and found that Visual Studio had off its own back added bogus references to MyProject.cs!! I removed these references and now the solution builds fine like it used to.

Simplest/cleanest way to implement a singleton in JavaScript

I needed several singletons with:

  • lazy initialisation
  • initial parameters

And so this was what I came up with:

createSingleton ('a', 'add', [1, 2]);
console.log(a);

function createSingleton (name, construct, args) {
    window[name] = {};
    window[construct].apply(window[name], args);
    window[construct] = null;
}

function add (a, b) {
    this.a = a;
    this.b = b;
    this.sum = a + b;
}
  • args must be Array for this to work, so if you have empty variables, just pass in []

  • I used the window object in the function, but I could have passed in a parameter to create my own scope

  • name and construct parameters are only String in order for window[] to work, but with some simple typechecking, window.name and window.construct are also possible.

How to get URL parameter using jQuery or plain JavaScript?

This might be overkill, but there is a pretty popular library now available for parsing URIs, called URI.js.

Example

_x000D_
_x000D_
var uri = "http://example.org/foo.html?technology=jquery&technology=css&blog=stackoverflow";_x000D_
var components = URI.parse(uri);_x000D_
var query = URI.parseQuery(components['query']);_x000D_
document.getElementById("result").innerHTML = "URI = " + uri;_x000D_
document.getElementById("result").innerHTML += "<br>technology = " + query['technology'];_x000D_
_x000D_
// If you look in your console, you will see that this library generates a JS array for multi-valued queries!_x000D_
console.log(query['technology']);_x000D_
console.log(query['blog']);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.17.0/URI.min.js"></script>_x000D_
_x000D_
<span id="result"></span>
_x000D_
_x000D_
_x000D_

How do I display images from Google Drive on a website?

<img src="https://drive.google.com/uc?export=view&id=Your_Image_ID" alt="">

I use on my wordpress site as storing image files on local host takes up to much space and slows down my site

I use textmate as it is easy to edit multiple URLs at same time using the 'alt/option' button

Pass variables from servlet to jsp

Simple way which i found is,

In servlet:

You can set the value and forward it to JSP like below

req.setAttribute("myname",login);
req.getRequestDispatcher("welcome.jsp").forward(req, resp); 

In Welcome.jsp you can get the values by

.<%String name = (String)request.getAttribute("myname"); %>
<%= name%>

(or) directly u can call

<%= request.getAttribute("myname") %>.

Get Value of Row in Datatable c#

for (Int32 i = 1; i < dt_pattern.Rows.Count - 1; i++){ double yATmax = ToDouble(dt_pattern.Rows[i]["Ampl"].ToString()) + AT; }

if you want to get around the + 1 issue

CMake is not able to find BOOST libraries

seems the answer is in the comments and as an edit but to clarify this should work for you:

export BUILDDIR='your path to  build directory here'
export SRCDIR='your path to source dir here'
export BOOST_ROOT="/opt/boost/boost_1_57_0"
export BOOST_INCLUDE="/opt/boost/boost-1.57.0/include"
export BOOST_LIBDIR="/opt/boost/boost-1.57.0/lib"
export BOOST_OPTS="-DBOOST_ROOT=${BOOST_ROOT} -DBOOST_INCLUDEDIR=${BOOST_INCLUDE} -DBOOST_LIBRARYDIR=${BOOST_LIBDIR}"
(cd ${BUILDDIR} && cmake ${BOOST_OPTS} ${SRCDIR})

you need to specify the arguments as command line arguments or you can use a toolchain file for that, but cmake will not touch your environment variables.

Reading and writing to serial port in C on Linux

1) I'd add a /n after init. i.e. write( USB, "init\n", 5);

2) Double check the serial port configuration. Odds are something is incorrect in there. Just because you don't use ^Q/^S or hardware flow control doesn't mean the other side isn't expecting it.

3) Most likely: Add a "usleep(100000); after the write(). The file-descriptor is set not to block or wait, right? How long does it take to get a response back before you can call read? (It has to be received and buffered by the kernel, through system hardware interrupts, before you can read() it.) Have you considered using select() to wait for something to read()? Perhaps with a timeout?

Edited to Add:

Do you need the DTR/RTS lines? Hardware flow control that tells the other side to send the computer data? e.g.

int tmp, serialLines;

cout << "Dropping Reading DTR and RTS\n";
ioctl ( readFd, TIOCMGET, & serialLines );
serialLines &= ~TIOCM_DTR;
serialLines &= ~TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
usleep(100000);
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
sleep (2);

cout << "Setting Reading DTR and RTS\n";
serialLines |= TIOCM_DTR;
serialLines |= TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;

SQL LIKE condition to check for integer?

Assuming that you're looking for "numbers that start with 7" rather than "strings that start with 7," maybe something like

select * from books where convert(char(32), book_id) like '7%'

Or whatever the Postgres equivalent of convert is.

Is there a C# case insensitive equals operator?

string.Equals(StringA, StringB, StringComparison.CurrentCultureIgnoreCase);

Spark - repartition() vs coalesce()

But also you should make sure that, the data which is coming coalesce nodes should have highly configured, if you are dealing with huge data. Because all the data will be loaded to those nodes, may lead memory exception. Though reparation is costly, i prefer to use it. Since it shuffles and distribute the data equally.

Be wise to select between coalesce and repartition.

Jackson: how to prevent field serialization

One should ask why you would want a public getter method for the password. Hibernate, or any other ORM framework, will do with a private getter method. For checking whether the password is correct, you can use

public boolean checkPassword(String password){
  return this.password.equals(anyHashingMethod(password));
}

Generating Fibonacci Sequence

I think this one is simple enough to understand:

function fibonacci(limit) {
    let result = [0, 1];

    for (var i = 2; i < limit; i++) {
        result[result.length] = result[result.length - 1] + result[result.length - 2];
    }

    return result;

}
// [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
console.log(fibonacci(10));

Where can I find the API KEY for Firebase Cloud Messaging?

You can also get the API key in the android studio. Switch to Project view in android then find the google-services.json. Scroll down and you will find the api_key

Eclipse: All my projects disappeared from Project Explorer

I tried many solutions. I found mine in the drop down menu of the Entreprise Explorer: - Deleting org.eclipse.core.resources has no effect. - "Top Level Elements -> Projects" was already checked for me; swtiching with Documents has no effect. - Selecting all extensions in the filter option of the drop down menu has no effect at first sight, maybe it solve part of the problem.

The solution come from "Unselecting documents" (third choice in the Entreprise Explorer drop down menu). I think that choice reset the filtering of documents displayed in the Explorer.

Hope it'll helps JN Gerbaux

How to use jQuery to select a dropdown option?

Use the following code if you want to select an option with a specific value:

$('select>option[value="' + value + '"]').prop('selected', true);

Boolean.parseBoolean("1") = false...?

It accepts only a string value of "true" to represent boolean true. Best what you can do is

boolean uses_votes = "1".equals(o.get("uses_votes"));

Or if the Map actually represents an "entitiy", I think a Javabean is way much better. Or if it represents configuration settings, you may want to take a look into Apache Commons Configuration.

Count indexes using "for" in Python

use enumerate:

>>> l = ['a', 'b', 'c', 'd']
>>> for index, val in enumerate(l):
...    print "%d: %s" % (index, val)
... 
0: a
1: b
2: c
3: d

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

I have Samsung Galaxy S3 and it was not showing in the "Remote devices" tab nor in chrome://inspect. The device did show in Windows's Device Manager as GT-I9300, though. What worked for me was:

  1. Plug the mobile phone to the front USB port
  2. On my phone, click the notification about successful connection
  3. Make sure the connection type is Camera (PTP)
  4. On my Windows machine, download installer from https://github.com/koush/UniversalAdbDriver
  5. Run it :)
  6. Open cmd.exe
  7. cd "C:\Program Files (x86)\ClockworkMod\Universal Adb Driver"
  8. adb devices
  9. Open Chrome in both mobile phone and Windows machine
  10. On Windows's machine navigate to chrome://inspect - there, after a while you should see the target phone :)

I'm not sure if it affected the whole flow somehow, but at some point I've installed, and later uninstalled the drivers from Samsung: http://www.samsung.com/us/support/downloads/ > Mobile > Phones > Galaxy S > S III > Unlocked > http://www.samsung.com/us/support/owners/product/galaxy-s-iii-unlocked#downloads

Modulo operator with negative values

a % b

in c++ default:

(-7/3) => -2
-2 * 3 => -6
so a%b => -1

(7/-3) => -2
-2 * -3 => 6
so a%b => 1

in python:

-7 % 3 => 2
7 % -3 => -2

in c++ to python:

(b + (a%b)) % b

set dropdown value by text using jquery

For GOOGLE, GOOGLEDOWN, GOOGLEUP i.e similar kind of value you can try below code

   $("#HowYouKnow option:contains('GOOGLE')").each(function () {

                        if($(this).html()=='GOOGLE'){
                            $(this).attr('selected', 'selected');
                        }
                    });

In this way,number of loop iteration can be reduced and will work in all situation.

How to change the name of a Django app?

In case you are using PyCharm and project stops working after rename:

  1. Edit Run/Debug configuration and change environment variable DJANGO_SETTINGS_MODULE, since it includes your project name.
  2. Go to Settings / Languages & Frameworks / Django and update the settings file location.

How to use EditText onTextChanged event when I press the number?

You can also try this:

EditText searchTo = (EditText)findViewById(R.id.medittext);
searchTo.addTextChangedListener(new TextWatcher() {
    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        doSomething();
    } 
});

How to customize the background/border colors of a grouped table view cell?

This task can be easily done using PrettyKit by adding about 5 lines of code. If you use nib files or storyboard, also do not forget to apply this little hack . When you use this approach, you should subclass your cell from PrettyTableViewCell:

#import <PrettyKit/PrettyKit.h>

@class RRSearchHistoryItem;

@interface RRSearchHistoryCell : PrettyTableViewCell

This is example of my cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *cellIdentifier = @"RRSearchHistoryCell";

  RRSearchHistoryCell *cell = (RRSearchHistoryCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

  if ( cell == nil ) {

    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"RRSearchHistoryCell" owner:self options:nil];
    cell = topLevelObjects[0];
    cell.gradientStartColor = RGB(0xffffff);
    cell.gradientEndColor = RGB(0xf3f3f3);

  }

  RRSearchHistoryItem *item = _historyTableData[indexPath.row];
  [cell setHistoryItem:item];


  [cell prepareForTableView:tableView indexPath:indexPath];

  return cell;
}

Unix command to find lines common in two files

Just for reference if someone is still looking on how to do this for multiple files, see the linked answer to Finding matching lines across many files.


Combining these two answers (ans1 and ans2), I think you can get the result you are needing without sorting the files:

#!/bin/bash
ans="matching_lines"

for file1 in *
do 
    for file2 in *
        do 
            if  [ "$file1" != "$ans" ] && [ "$file2" != "$ans" ] && [ "$file1" != "$file2" ] ; then
                echo "Comparing: $file1 $file2 ..." >> $ans
                perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/' $file1 $file2 >> $ans
            fi
         done 
done

Simply save it, give it execution rights (chmod +x compareFiles.sh) and run it. It will take all the files present in the current working directory and will make an all-vs-all comparison leaving in the "matching_lines" file the result.

Things to be improved:

  • Skip directories
  • Avoid comparing all the files two times (file1 vs file2 and file2 vs file1).
  • Maybe add the line number next to the matching string

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

How to change MySQL column definition?

Do you mean altering the table after it has been created? If so you need to use alter table, in particular:

ALTER TABLE tablename MODIFY COLUMN new-column-definition

e.g.

ALTER TABLE test MODIFY COLUMN locationExpect VARCHAR(120);

Add Expires headers

The easiest way to add these headers is a .htaccess file that adds some configuration to your server. If the assets are hosted on a server that you don't control, there's nothing you can do about it.

Note that some hosting providers will not let you use .htaccess files, so check their terms if it doesn't seem to work.

The HTML5Boilerplate project has an excellent .htaccess file that covers the necessary settings. See the relevant part of the file at their Github repository

These are the important bits

# ----------------------------------------------------------------------
# Expires headers (for better cache control)
# ----------------------------------------------------------------------

# These are pretty far-future expires headers.
# They assume you control versioning with filename-based cache busting
# Additionally, consider that outdated proxies may miscache
# www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/

# If you don't use filenames to version, lower the CSS and JS to something like
# "access plus 1 week".

<IfModule mod_expires.c>
  ExpiresActive on

# Your document html
  ExpiresByType text/html "access plus 0 seconds"

# Media: images, video, audio
  ExpiresByType audio/ogg "access plus 1 month"
  ExpiresByType image/gif "access plus 1 month"
  ExpiresByType image/jpeg "access plus 1 month"
  ExpiresByType image/png "access plus 1 month"
  ExpiresByType video/mp4 "access plus 1 month"
  ExpiresByType video/ogg "access plus 1 month"
  ExpiresByType video/webm "access plus 1 month"

# CSS and JavaScript
  ExpiresByType application/javascript "access plus 1 year"
  ExpiresByType text/css "access plus 1 year"
</IfModule>

They have documented what that file does, the most important bit is that you need to rename your CSS and Javascript files whenever they change, because your visitor's browsers will not check them again for a year, once they are cached.

php $_GET and undefined index

Actually none of the proposed answers, although a good practice, would remove the warning.

For the sake of correctness, I'd do the following:

function getParameter($param, $defaultValue) {
    if (array_key_exists($param, $_GET)) {
        $value=$_GET[$param];
        return isSet($value)?$value:$defaultValue;
    }
    return $defaultValue;
}

This way, I check the _GET array for the key to exist without triggering the Warning. It's not a good idea to disable the warnings because a lot of times they are at least interesting to take a look.

To use the function you just do:

$myvar = getParameter("getparamer", "defaultValue")

so if the parameter exists, you get the value, and if it doesnt, you get the defaultValue.

CASE (Contains) rather than equal statement

CASE WHEN ', ' + dbo.Table.Column +',' LIKE '%, lactulose,%' 
  THEN 'BP Medication' ELSE '' END AS [BP Medication]

The leading ', ' and trailing ',' are added so that you can handle the match regardless of where it is in the string (first entry, last entry, or anywhere in between).

That said, why are you storing data you want to search on as a comma-separated string? This violates all kinds of forms and best practices. You should consider normalizing your schema.

In addition: don't use 'single quotes' as identifier delimiters; this syntax is deprecated. Use [square brackets] (preferred) or "double quotes" if you must. See "string literals as column aliases" here: http://msdn.microsoft.com/en-us/library/bb510662%28SQL.100%29.aspx

EDIT If you have multiple values, you can do this (you can't short-hand this with the other CASE syntax variant or by using something like IN()):

CASE 
  WHEN ', ' + dbo.Table.Column +',' LIKE '%, lactulose,%' 
  WHEN ', ' + dbo.Table.Column +',' LIKE '%, amlodipine,%' 
  THEN 'BP Medication' ELSE '' END AS [BP Medication]

If you have more values, it might be worthwhile to use a split function, e.g.

USE tempdb;
GO

CREATE FUNCTION dbo.SplitStrings(@List NVARCHAR(MAX))
RETURNS TABLE
AS
   RETURN ( SELECT DISTINCT Item FROM
       ( SELECT Item = x.i.value('(./text())[1]', 'nvarchar(max)')
         FROM ( SELECT [XML] = CONVERT(XML, '<i>'
         + REPLACE(@List,',', '</i><i>') + '</i>').query('.')
           ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y
       WHERE Item IS NOT NULL
   );
GO

CREATE TABLE dbo.[Table](ID INT, [Column] VARCHAR(255));
GO

INSERT dbo.[Table] VALUES
(1,'lactulose, Lasix (furosemide), oxazepam, propranolol, rabeprazole, sertraline,'),
(2,'lactulite, Lasix (furosemide), lactulose, propranolol, rabeprazole, sertraline,'),
(3,'lactulite, Lasix (furosemide), oxazepam, propranolol, rabeprazole, sertraline,'),
(4,'lactulite, Lasix (furosemide), lactulose, amlodipine, rabeprazole, sertraline,');

SELECT t.ID
  FROM dbo.[Table] AS t
  INNER JOIN dbo.SplitStrings('lactulose,amlodipine') AS s
  ON ', ' + t.[Column] + ',' LIKE '%, ' + s.Item + ',%'
  GROUP BY t.ID;
GO

Results:

ID
----
1
2
4

How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting

I had this problem but I solved it by installing the version of the ruby that is specified in my gem file using the RVM

    rvm install (ruby version)

After the installation, I use the following command to use the the version that you installed.

    rvm --default use (ruby version)

You have to install bundler by using the following command in order to use the latest version

    gem install bundler 

After the above steps, you can now run following command to install the gems specified on the gemfile

    bundle install

How to read GET data from a URL using JavaScript?

The currently selected answer did not work well at all in my case, which I feel is a fairly typical one. I found the below function here and it works great!

function getAllUrlParams(url) {

  // get query string from url (optional) or window
  var queryString = url ? url.split('?')[1] : window.location.search.slice(1);

  // we'll store the parameters here
  var obj = {};

  // if query string exists
  if (queryString) {

    // stuff after # is not part of query string, so get rid of it
    queryString = queryString.split('#')[0];

    // split our query string into its component parts
    var arr = queryString.split('&');

    for (var i=0; i<arr.length; i++) {
      // separate the keys and the values
      var a = arr[i].split('=');

      // in case params look like: list[]=thing1&list[]=thing2
      var paramNum = undefined;
      var paramName = a[0].replace(/\[\d*\]/, function(v) {
        paramNum = v.slice(1,-1);
        return '';
      });

      // set parameter value (use 'true' if empty)
      var paramValue = typeof(a[1])==='undefined' ? true : a[1];

      // (optional) keep case consistent
      paramName = paramName.toLowerCase();
      paramValue = paramValue.toLowerCase();

      // if parameter name already exists
      if (obj[paramName]) {
        // convert value to array (if still string)
        if (typeof obj[paramName] === 'string') {
          obj[paramName] = [obj[paramName]];
        }
        // if no array index number specified...
        if (typeof paramNum === 'undefined') {
          // put the value on the end of the array
          obj[paramName].push(paramValue);
        }
        // if array index number specified...
        else {
          // put the value at that index number
          obj[paramName][paramNum] = paramValue;
        }
      }
      // if param name doesn't exist yet, set it
      else {
        obj[paramName] = paramValue;
      }
    }
  }

  return obj;
}

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

@chappers solution (in the comments) works as.integer(as.logical(data.frame$column.name))

Random character generator with a range of (A..Z, 0..9) and punctuation

Here is code for secure, easy, but a little bit more expensive session identifiers.

import java.security.SecureRandom;
import java.math.BigInteger;

public final class SessionIdentifierGenerator
{

  private SecureRandom random = new SecureRandom();

  public String nextSessionId()
  {
    return new BigInteger(130, random).toString(32);
  }

}

How to set default vim colorscheme

Once you’ve decided to change vim color scheme that you like, you’ll need to configure vim configuration file ~/.vimrc.

For e.g. to use the elflord color scheme just add these lines to your ~/.vimrc file:

colo elflord

For other names of color schemes you can look in /usr/share/vim/vimNN/colors where NN - version of VIM.

App crashing when trying to use RecyclerView on android 5.0

I had this problem when using Butterknife , I was using fragment

For Fragment, it should be ButterKnife.bind(this,view);

For Activity ButterKnife.bind(this);

How to Update Date and Time of Raspberry Pi With out Internet

Remember that Raspberry Pi does not have real time clock. So even you are connected to internet have to set the time every time you power on or restart.

This is how it works:

  1. Type sudo raspi-config in the Raspberry Pi command line
  2. Internationalization options
  3. Change Time Zone
  4. Select geographical area
  5. Select city or region
  6. Reboot your pi

Next thing you can set time using this command

sudo date -s "Mon Aug  12 20:14:11 UTC 2014"

More about data and time

man date

When Pi is connected to computer should have to manually set data and time

jQuery Multiple ID selectors

it should. Typically that's how you do multiple selectors. Otherwise it may not like you trying to assign the return values of three uploads to the same var.

I would suggest using .each or maybe push the returns to an array rather than assigning them to that value.

Hide axis and gridlines Highcharts

This has always worked well for me:

yAxes: [{
         ticks: {
                 display: false;
                },

Horizontal swipe slider with jQuery and touch devices support?

You might be interested in the following:

I realize this is not a jQuery solution, but Sencha Touch framework is pretty good for building your target UI. Example (click the Carousel sidebar link): http://dev.sencha.com/deploy/touch/examples/kitchensink/

C# Debug - cannot start debugging because the debug target is missing

Application Property

Switch Target framework to 4.5.2 or something higher and bring it back to your original version (example: 4.5) then when you build, it will work.

Looping over elements in jQuery

I have used the following before:

var my_form = $('#form-id');
var data = {};

$('input:not([type=checkbox]), input[type=checkbox]:selected, select, textarea', my_form).each(
    function() {
        var name = $(this).attr('name');
        var val = $(this).val();

        if (!data.hasOwnProperty(name)) {
            data[name] = new Array;
        }

        data[name].push(val);
    }
);

This is just written from memory, so might contain mistakes, but this should make an object called data that contains the values for all your inputs.

Note that you have to deal with checkboxes in a special way, to avoid getting the values of unchecked checkboxes. The same is probably true of radio inputs.

Also note using arrays for storing the values, as for one input name, you might have values from several inputs (checkboxes in particular).

DataGridView AutoFit and Fill

You need to use the DataGridViewColumn.AutoSizeMode property.

You can use one of these values for column 0 and 1:

AllCells: The column width adjusts to fit the contents of all cells in the column, including the header cell.
AllCellsExceptHeader: The column width adjusts to fit the contents of all cells in the column, excluding the header cell.
DisplayedCells: The column width adjusts to fit the contents of all cells in the column that are in rows currently displayed onscreen, including the header cell.
DisplayedCellsExceptHeader: The column width adjusts to fit the contents of all cells in the column that are in rows currently displayed onscreen, excluding the header cell.

Then you use the Fill value for column 2

The column width adjusts so that the widths of all columns exactly fills the display area of the control...

this.DataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
this.DataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
this.DataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

As pointed out by other users, the default value can be set at datagridview level with DataGridView.AutoSizeColumnsMode property.

this.DataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
this.DataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;

could be:

this.DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;

Important note:

If your grid is bound to a datasource and columns are auto-generated (AutoGenerateColumns property set to True), you need to use the DataBindingComplete event to apply style AFTER columns have been created.


In some scenarios (change cells value by code for example), I had to call DataGridView1.AutoResizeColumns(); to refresh the grid.

When is "java.io.IOException:Connection reset by peer" thrown?

java.io.IOException: Connection reset by peer

The other side has abruptly aborted the connection in midst of a transaction. That can have many causes which are not controllable from the server side on. E.g. the enduser decided to shutdown the client or change the server abruptly while still interacting with your server, or the client program has crashed, or the enduser's internet connection went down, or the enduser's machine crashed, etc, etc.

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

Check Following Things

  • Make Sure You Have MySQL Server Running
  • Check connection with default credentials i.e. username : 'root' & password : '' [Blank Password]
  • Try login phpmyadmin with same credentials
  • Try to put 127.0.0.1 instead localhost or your lan IP would do too.
  • Make sure you are running MySql on 3306 and if you have configured make sure to state it while making a connection

Partly JSON unmarshal into a map in Go

This can be accomplished by Unmarshaling into a map[string]json.RawMessage.

var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)

To further parse sendMsg, you could then do something like:

var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)

For say, you can do the same thing and unmarshal into a string:

var str string
err = json.Unmarshal(objmap["say"], &str)

EDIT: Keep in mind you will also need to export the variables in your sendMsg struct to unmarshal correctly. So your struct definition would be:

type sendMsg struct {
    User string
    Msg  string
}

Example: https://play.golang.org/p/OrIjvqIsi4-

How can I convert a string with dot and comma into a float in Python

If you don't know the locale and you want to parse any kind of number, use this parseNumber(text) function. It is not perfect but take into account most cases :

>>> parseNumber("a 125,00 €")
125
>>> parseNumber("100.000,000")
100000
>>> parseNumber("100 000,000")
100000
>>> parseNumber("100,000,000")
100000000
>>> parseNumber("100 000 000")
100000000
>>> parseNumber("100.001 001")
100.001
>>> parseNumber("$.3")
0.3
>>> parseNumber(".003")
0.003
>>> parseNumber(".003 55")
0.003
>>> parseNumber("3 005")
3005
>>> parseNumber("1.190,00 €")
1190
>>> parseNumber("1190,00 €")
1190
>>> parseNumber("1,190.00 €")
1190
>>> parseNumber("$1190.00")
1190
>>> parseNumber("$1 190.99")
1190.99
>>> parseNumber("1 000 000.3")
1000000.3
>>> parseNumber("1 0002,1.2")
10002.1
>>> parseNumber("")

>>> parseNumber(None)

>>> parseNumber(1)
1
>>> parseNumber(1.1)
1.1
>>> parseNumber("rrr1,.2o")
1
>>> parseNumber("rrr ,.o")

>>> parseNumber("rrr1rrr")
1

How would I find the second largest salary from the employee table?

Try this:

SELECT
    salary,
    employeeid
FROM
    employees
ORDER BY
    salary DESC
LIMIT 2

Then just get the second row.

Simulate a click on 'a' element using javascript/jquery

Try adding a function inside the click() method.

$('#gift-close').click(function(){
  //do something here
});

It worked for me with a function assigned inside the click() method rather than keeping it empty.

Creating table variable in SQL server 2008 R2

@tableName Table variables are alive for duration of the script running only i.e. they are only session level objects.

To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.

There is another type of table object which can be created for temporary use. They are #tableName objects declared like similar create statement for physical tables:

Create table #test (Id int, Name varchar(50))

This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.

IF OBJECT_ID('tempdb..#test') IS NOT NULL
  DROP TABLE #test 

Hope this makes sense !

jQuery AJAX cross domain

It is true that the same-origin policy prevents JavaScript from making requests across domains, but the CORS specification allows just the sort of API access you are looking for, and is supported by the current batch of major browsers.

See how to enable cross-origin resource sharing for client and server:

http://enable-cors.org/

"Cross-Origin Resource Sharing (CORS) is a specification that enables truly open access across domain-boundaries. If you serve public content, please consider using CORS to open it up for universal JavaScript/browser access."

Concatenating two std::vectors

Or you could use:

std::copy(source.begin(), source.end(), std::back_inserter(destination));

This pattern is useful if the two vectors don't contain exactly the same type of thing, because you can use something instead of std::back_inserter to convert from one type to the other.

Run a mySQL query as a cron job?

Try creating a shell script like the one below:

#!/bin/bash

mysql --user=[username] --password=[password] --database=[db name] --execute="DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) ,  timestamp ) >=7"

You can then add this to the cron

How to apply multiple transforms in CSS?

Transform Rotate and Translate in single line css:-How?

_x000D_
_x000D_
div.className{_x000D_
    transform : rotate(270deg) translate(-50%, 0);    _x000D_
    -webkit-transform: rotate(270deg) translate(-50%, -50%);    _x000D_
    -moz-transform: rotate(270deg) translate(-50%, -50%);    _x000D_
    -ms-transform: rotate(270deg) translate(-50%, -50%);    _x000D_
    -o-transform: rotate(270deg) translate(-50%, -50%); _x000D_
    float:left;_x000D_
    position:absolute;_x000D_
    top:50%;_x000D_
    left:50%;_x000D_
    }
_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<div class="className">_x000D_
  <span style="font-size:50px">A</span>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

await vs Task.Wait - Deadlock?

Based on what I read from different sources:

An await expression does not block the thread on which it is executing. Instead, it causes the compiler to sign up the rest of the async method as a continuation on the awaited task. Control then returns to the caller of the async method. When the task completes, it invokes its continuation, and execution of the async method resumes where it left off.

To wait for a single task to complete, you can call its Task.Wait method. A call to the Wait method blocks the calling thread until the single class instance has completed execution. The parameterless Wait() method is used to wait unconditionally until a task completes. The task simulates work by calling the Thread.Sleep method to sleep for two seconds.

This article is also a good read.

How do I test which class an object is in Objective-C?

if you want to get the name of the class simply call:-

id yourObject= [AnotherClass returningObject];

NSString *className=[yourObject className];

NSLog(@"Class name is : %@",className);

Setting Authorization Header of HttpClient

request.DefaultRequestHeaders.Authorization = 
    new AuthenticationHeaderValue(
        "Basic", Convert.ToBase64String(
            System.Text.ASCIIEncoding.ASCII.GetBytes(
               $"{yourusername}:{yourpwd}")));

How to handle anchor hash linking in AngularJS

On Route change it will scroll to the top of the page.

 $scope.$on('$routeChangeSuccess', function () {
      window.scrollTo(0, 0);
  });

put this code on your controller.

Getting reference to the top-most view/window in iOS application

Actually there could be more than one UIWindow in your application. For example, if a keyboard is on screen then [[UIApplication sharedApplication] windows] will contain at least two windows (your key-window and the keyboard window).

So if you want your view to appear ontop of both of them then you gotta do something like:

[[[[UIApplication sharedApplication] windows] lastObject] addSubview:view];

(Assuming lastObject contains the window with the highest windowLevel priority).

How can I make Visual Studio wrap lines at 80 characters?

I don't think you can make VS wrap at 80 columns (I'd find that terribly annoying) but you can insert a visual guideline at 80 columns so you know when is a good time to insert a newline.

Details on inserting a guideline at 80 characters for 3 different versions of visual studio.

Printf long long int in C with GCC?

For portable code, the macros in inttypes.h may be used. They expand to the correct ones for the platform.

E.g. for 64 bit integer, the macro PRId64 can be used.

int64_t n = 7;
printf("n is %" PRId64 "\n", n);

How to convert List to Json in Java

Look at the google gson library. It provides a rich api for dealing with this and is very straightforward to use.

JavaScript function to add X months to a date

I'm using moment.js library for date-time manipulations. Sample code to add one month:

var startDate = new Date(...);
var endDateMoment = moment(startDate); // moment(...) can also be used to parse dates in string format
endDateMoment.add(1, 'months');

How to fetch data from local JSON file on react native?

The following ways to fetch local JSON file-

ES6 version:

import customData from './customData.json'; or import customData from './customData';

If it's inside .js file instead of .json then import like -

import { customData } from './customData';

for more clarification/understanding refer example - Live working demo

How do I automatically update a timestamp in PostgreSQL

You'll need to write an insert trigger, and possible an update trigger if you want it to change when the record is changed. This article explains it quite nicely:

http://www.revsys.com/blog/2006/aug/04/automatically-updating-a-timestamp-column-in-postgresql/

CREATE OR REPLACE FUNCTION update_modified_column()   
RETURNS TRIGGER AS $$
BEGIN
    NEW.modified = now();
    RETURN NEW;   
END;
$$ language 'plpgsql';

Apply the trigger like this:

CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON customer FOR EACH ROW EXECUTE PROCEDURE  update_modified_column();

Android: How to change CheckBox size?

Starting with API Level 11 there is another approach exists:

<CheckBox
    ...
    android:scaleX="0.70"
    android:scaleY="0.70"
/>

Best way to handle list.index(might-not-exist) in python?

What about this:

otherfunction(thing_collection, thing)

Rather than expose something so implementation-dependent like a list index in a function interface, pass the collection and the thing and let otherfunction deal with the "test for membership" issues. If otherfunction is written to be collection-type-agnostic, then it would probably start with:

if thing in thing_collection:
    ... proceed with operation on thing

which will work if thing_collection is a list, tuple, set, or dict.

This is possibly clearer than:

if thing_index != MAGIC_VALUE_INDICATING_NOT_A_MEMBER:

which is the code you already have in otherfunction.

Open application after clicking on Notification

public static void notifyUser(Activity activity, String header,
        String message) {
    NotificationManager notificationManager = (NotificationManager) activity
            .getSystemService(Activity.NOTIFICATION_SERVICE);
    Intent notificationIntent = new Intent(
            activity.getApplicationContext(), YourActivityToLaunch.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(activity);
    stackBuilder.addParentStack(YourActivityToLaunch.class);
    stackBuilder.addNextIntent(notificationIntent);
    PendingIntent pIntent = stackBuilder.getPendingIntent(0,
            PendingIntent.FLAG_UPDATE_CURRENT);
    Notification notification = new Notification.Builder(activity)
            .setContentTitle(header)
            .setContentText(message)
            .setDefaults(
                    Notification.DEFAULT_SOUND
                            | Notification.DEFAULT_VIBRATE)
            .setContentIntent(pIntent).setAutoCancel(true)
            .setSmallIcon(drawable.notification_icon).build();
    notificationManager.notify(2, notification);
}

Center an element with "absolute" position and undefined width in CSS?

None of the solutions worked for me since I didn't want to change the styling of the container/wrapper element. This code worked for me:

position: absolute;
left: 50%;
margin-left: -50px;
top: 50%;
margin-top: -50px;

Ternary operator in AngularJS templates

  <body ng-app="app">
  <button type="button" ng-click="showme==true ? !showme :showme;message='Cancel Quiz'"  class="btn btn-default">{{showme==true ? 'Cancel Quiz': 'Take a Quiz'}}</button>
    <div ng-show="showme" class="panel panel-primary col-sm-4" style="margin-left:250px;">
      <div class="panel-heading">Take Quiz</div>
      <div class="form-group col-sm-8 form-inline" style="margin-top: 30px;margin-bottom: 30px;">

        <button type="button" class="btn btn-default">Start Quiz</button>
      </div>
    </div>
  </body>

Button toggle and change header of button and show/hide div panel. See the Plunkr

Npm install cannot find module 'semver'

just remove your node_modules

rm -rf node_modules

than

yarn

or

npm install

When to use "new" and when not to, in C++?

You should use new when you wish an object to remain in existence until you delete it. If you do not use new then the object will be destroyed when it goes out of scope. Some examples of this are:

void foo()
{
  Point p = Point(0,0);
} // p is now destroyed.

for (...)
{
  Point p = Point(0,0);
} // p is destroyed after each loop

Some people will say that the use of new decides whether your object is on the heap or the stack, but that is only true of variables declared within functions.

In the example below the location of 'p' will be where its containing object, Foo, is allocated. I prefer to call this 'in-place' allocation.

class Foo
{

  Point p;
}; // p will be automatically destroyed when foo is.

Allocating (and freeing) objects with the use of new is far more expensive than if they are allocated in-place so its use should be restricted to where necessary.

A second example of when to allocate via new is for arrays. You cannot* change the size of an in-place or stack array at run-time so where you need an array of undetermined size it must be allocated via new.

E.g.

void foo(int size)
{
   Point* pointArray = new Point[size];
   ...
   delete [] pointArray;
}

(*pre-emptive nitpicking - yes, there are extensions that allow variable sized stack allocations).

Extract time from moment js object

This is the good way using formats:

const now = moment()
now.format("hh:mm:ss K") // 1:00:00 PM
now.format("HH:mm:ss") // 13:00:00

Red more about moment sring format

Command not found error in Bash variable assignment

Drop the spaces around the = sign:

#!/bin/bash 
STR="Hello World" 
echo $STR 

Replacing accented characters php

I found this way to be a good one, without having to worry too much about charsets and arrays, or iconv:

function replace_accents($str) {
   $str = htmlentities($str, ENT_COMPAT, "UTF-8");
   $str = preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde|ring);/','$1',$str);
   return html_entity_decode($str);
}

What is the difference between '/' and '//' when used for division?

Python 2.x Clarification:

To clarify for the Python 2.x line, / is neither floor division nor true division.

/ is floor division when both args are int, but is true division when either of the args are float.

How to split the name string in mysql?

DELIMITER $$

DROP FUNCTION IF EXISTS `split_name`$$

CREATE FUNCTION split_name (p_fullname TEXT, p_part INTEGER)
RETURNS TEXT
    READS SQL DATA
BEGIN
    DECLARE v_words INT UNSIGNED;
    DECLARE v_name TEXT;

    SET p_fullname=RTRIM(LTRIM(p_fullname));

    SET v_words=(SELECT SUM(LENGTH(p_fullname) - LENGTH(REPLACE(p_fullname, ' ', ''))+1));

    IF v_words=1 THEN 
        IF p_part=1 THEN
            SET v_name=p_fullname;
        ELSEIF p_part=2 THEN
            SET v_name=NULL;
        ELSEIF p_part=3 THEN
            SET v_name=NULL;
        ELSE
            SET v_name=NULL;
        END IF; 
    ELSEIF v_words=2 THEN 
        IF p_part=1 THEN
            SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
        ELSEIF p_part=2 THEN
            SET v_name=SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1);
        ELSEIF p_part=3 THEN
            SET v_name=NULL;
        ELSE
            SET v_name=NULL;
        END IF; 
    ELSEIF v_words=3 THEN 
        IF p_part=1 THEN
            SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
        ELSEIF p_part=2 THEN
            SET p_fullname=SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1);
            SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
        ELSEIF p_part=3 THEN
            SET p_fullname=REVERSE (SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
            SET p_fullname=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
            SET v_name=REVERSE(p_fullname);
        ELSE
            SET v_name=NULL;
        END IF; 
    ELSEIF v_words>3 THEN 
        IF p_part=1 THEN
            SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
        ELSEIF p_part=2 THEN
            SET p_fullname=REVERSE(SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
            SET p_fullname=SUBSTRING(p_fullname, LOCATE(' ', p_fullname,SUBSTRING_INDEX(p_fullname,' ',1)+1) + 1);
            SET v_name=REVERSE(p_fullname);
        ELSEIF p_part=3 THEN
            SET p_fullname=REVERSE (SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
            SET p_fullname=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
            SET v_name=REVERSE(p_fullname);
        ELSE
            SET v_name=NULL;
        END IF;
    ELSE
        SET v_name=NULL;
    END IF;
 RETURN v_name; 
END;

SELECT split_name('Md. Obaidul Haque Sarker',1) AS first_name,
split_name('Md. Obaidul Haque Sarker',2) AS middle_name,
split_name('Md. Obaidul Haque Sarker',3) AS last_name

java: use StringBuilder to insert at the beginning

How about:

StringBuilder builder = new StringBuilder();
for(int i=99;i>=0;i--){
    builder.append(Integer.toString(i));
}
builder.toString();

OR

StringBuilder builder = new StringBuilder();
for(int i=0;i<100;i++){
  builder.insert(0, Integer.toString(i));
}
builder.toString();

But with this, you are making the operation O(N^2) instead of O(N).

Snippet from java docs:

Inserts the string representation of the Object argument into this character sequence. The overall effect is exactly as if the second argument were converted to a string by the method String.valueOf(Object), and the characters of that string were then inserted into this character sequence at the indicated offset.

C - function inside struct

You are trying to group code according to struct. C grouping is by file. You put all the functions and internal variables in a header or a header and a object ".o" file compiled from a c source file.

It is not necessary to reinvent object-orientation from scratch for a C program, which is not an object oriented language.

I have seen this before. It is a strange thing. Coders, some of them, have an aversion to passing an object they want to change into a function to change it, even though that is the standard way to do so.

I blame C++, because it hid the fact that the class object is always the first parameter in a member function, but it is hidden. So it looks like it is not passing the object into the function, even though it is.

Client.addClient(Client& c); // addClient first parameter is actually 
                             // "this", a pointer to the Client object.

C is flexible and can take passing things by reference.

A C function often returns only a status byte or int and that is often ignored. In your case a proper form might be

 err = addClient( container_t  cnt, client_t c);
 if ( err != 0 )
   { fprintf(stderr, "could not add client (%d) \n", err ); 

addClient would be in Client.h or Client.c

jQuery 'input' event

jQuery has the following signature for the .on() method: .on( events [, selector ] [, data ], handler )

Events could be anyone of the ones listed on this reference:

https://developer.mozilla.org/en-US/docs/Web/Events

Though, they are not all supported by every browser.

Mozilla states the following about the input event:

The DOM input event is fired synchronously when the value of an or element is changed. Additionally, it fires on contenteditable editors when its contents are changed.

Compare and contrast REST and SOAP web services?

SOAP uses WSDL for communication btw consumer and provider, whereas REST just uses XML or JSON to send and receive data

WSDL defines contract between client and service and is static by its nature. In case of REST contract is somewhat complicated and is defined by HTTP, URI, Media Formats and Application Specific Coordination Protocol. It's highly dynamic unlike WSDL.

SOAP doesn't return human readable result, whilst REST result is readable with is just plain XML or JSON

This is not true. Plain XML or JSON are not RESTful at all. None of them define any controls(i.e. links and link relations, method information, encoding information etc...) which is against REST as far as messages must be self contained and coordinate interaction between agent/client and service.

With links + semantic link relations clients should be able to determine what is next interaction step and follow these links and continue communication with service.

It is not necessary that messages be human readable, it's possible to use cryptic format and build perfectly valid REST applications. It doesn't matter whether message is human readable or not.

Thus, plain XML(application/xml) or JSON(application/json) are not sufficient formats for building REST applications. It's always reasonable to use subset of these generic media types which have strong semantic meaning and offer enough control information(links etc...) to coordinate interactions between client and server.

REST is over only HTTP

Not true, HTTP is most widely used and when we talk about REST web services we just assume HTTP. HTTP defines interface with it's methods(GET, POST, PUT, DELETE, PATCH etc) and various headers which can be used uniformly for interacting with resources. This uniformity can be achieved with other protocols as well.

P.S. Very simple, yet very interesting explanation of REST: http://www.looah.com/source/view/2284

Using different Web.config in development and production environment

You can also use the extension "Configuration Transform" works the same as "SlowCheetah",

Shrinking navigation bar when scrolling down (bootstrap3)

For those not willing to use jQuery here is a Vanilla Javascript way of doing the same using classList:

function runOnScroll() {
    var element = document.getElementsByTagName('nav')  ;
    if(document.body.scrollTop >= 50) {
        element[0].classList.add('shrink')
    } else {
        element[0].classList.remove('shrink')
    }
    console.log(topMenu[0].classList)

};

There might be a nicer way of doing it using toggle, but the above works fine in Chrome

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

quick note for those recently upgrading to "modern" ssh version [OpenSSH_8.1p1, OpenSSL 1.1.1d FIPS 10 Sep 2019] - supplied with fedora 31, seems not to be anymore accepting old DSA SHA256 keys (mine are dated 2006!) - created a new rsa key, public added to authorized, private on client, and everything works perfectly.

thanks for previous suggestions, especially the ssh -v has been very useful

How to Kill A Session or Session ID (ASP.NET/C#)

From what I tested:

Session.Abandon(); // Does nothing
Session.Clear();   // Removes the data contained in the session

Example:
001: Session["test"] = "test";
002: Session.Abandon();
003: Print(Session["test"]); // Outputs: "test"

Session.Abandon does only set a boolean flag in the session-object to true. The calling web-server may react to that or not, but there is NO immediate action caused by ASP. (I checked that myself with the .net-Reflector)

In fact, you can continue working with the old session, by hitting the browser's back button once, and continue browsing across the website normally.

So, to conclude this: Use Session.Clear() and save frustration.

Remark: I've tested this behaviour on the ASP.net development server. The actual IIS may behave differently.

How to plot two histograms together in R?

So many great answers but since I've just written a function (plotMultipleHistograms() in 'basicPlotteR' package) function to do this, I thought I would add another answer.

The advantage of this function is that it automatically sets appropriate X and Y axis limits and defines a common set of bins that it uses across all the distributions.

Here's how to use it:

# Install the plotteR package
install.packages("devtools")
devtools::install_github("JosephCrispell/basicPlotteR")
library(basicPlotteR)

# Set the seed
set.seed(254534)

# Create random samples from a normal distribution
distributions <- list(rnorm(500, mean=5, sd=0.5), 
                      rnorm(500, mean=8, sd=5), 
                      rnorm(500, mean=20, sd=2))

# Plot overlapping histograms
plotMultipleHistograms(distributions, nBins=20, 
                       colours=c(rgb(1,0,0, 0.5), rgb(0,0,1, 0.5), rgb(0,1,0, 0.5)), 
                       las=1, main="Samples from normal distribution", xlab="Value")

enter image description here

The plotMultipleHistograms() function can take any number of distributions, and all the general plotting parameters should work with it (for example: las, main, etc.).

How can one see content of stack with GDB?

Use:

  • bt - backtrace: show stack functions and args
  • info frame - show stack start/end/args/locals pointers
  • x/100x $sp - show stack memory
(gdb) bt
#0  zzz () at zzz.c:96
#1  0xf7d39cba in yyy (arg=arg@entry=0x0) at yyy.c:542
#2  0xf7d3a4f6 in yyyinit () at yyy.c:590
#3  0x0804ac0c in gnninit () at gnn.c:374
#4  main (argc=1, argv=0xffffd5e4) at gnn.c:389

(gdb) info frame
Stack level 0, frame at 0xffeac770:
 eip = 0x8049047 in main (goo.c:291); saved eip 0xf7f1fea1
 source language c.
 Arglist at 0xffeac768, args: argc=1, argv=0xffffd5e4
 Locals at 0xffeac768, Previous frame's sp is 0xffeac770
 Saved registers:
  ebx at 0xffeac75c, ebp at 0xffeac768, esi at 0xffeac760, edi at 0xffeac764, eip at 0xffeac76c

(gdb) x/10x $sp
0xffeac63c: 0xf7d39cba  0xf7d3c0d8  0xf7d3c21b  0x00000001
0xffeac64c: 0xf78d133f  0xffeac6f4  0xf7a14450  0xffeac678
0xffeac65c: 0x00000000  0xf7d3790e

How to make System.out.println() shorter

void p(String l){
System.out.println(l);
}

Shortest. Go for it.

Process.start: how to get the output?

Alright, for anyone who wants both Errors and Outputs read, but gets deadlocks with any of the solutions, provided in other answers (like me), here is a solution that I built after reading MSDN explanation for StandardOutput property.

Answer is based on T30's code:

static void runCommand()
{
    //* Create your Process
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/c DIR";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    //* Set ONLY ONE handler here.
    process.ErrorDataReceived += new DataReceivedEventHandler(ErrorOutputHandler);
    //* Start process
    process.Start();
    //* Read one element asynchronously
    process.BeginErrorReadLine();
    //* Read the other one synchronously
    string output = process.StandardOutput.ReadToEnd();
    Console.WriteLine(output);
    process.WaitForExit();
}

static void ErrorOutputHandler(object sendingProcess, DataReceivedEventArgs outLine) 
{
    //* Do your stuff with the output (write to console/log/StringBuilder)
    Console.WriteLine(outLine.Data);
}

Unable to merge dex

With Android Studio 3.0 stable build Below steps worked for me:

  1. Got to SdkManager-->Android Sdk --> Sdk Tools and Update Google play services to latest version to 46.
  2. Clean project and rebuild project.

Checking if a key exists in a JavaScript object?

yourArray.indexOf(yourArrayKeyName) > -1

fruit = ['apple', 'grapes', 'banana']

fruit.indexOf('apple') > -1

true


fruit = ['apple', 'grapes', 'banana']

fruit.indexOf('apple1') > -1

false

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

In my case (Windows 10 + IIS 10) i had to open "Turn Windows Features On or Off" and then go to Internet Information Services > World Wide Web Services > Application Development Features > and check ASP.NET 4.6

What's the best way to override a user agent CSS stylesheet rule that gives unordered-lists a 1em margin?

put this in your "head" of your index.html

 <style>
  html body{
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    margin: 0;
  }
  </style>

Set textbox to readonly and background color to grey in jquery

Can add disable like below and can get data on submit. something like this .. DEMO

Html

<input type="hidden" name="email" value="email" />
<input type="text" id="dis" class="disable" value="email"   name="email" >

JS

 $("#dis").attr('disabled','disabled');

CSS

    .disable { opacity : .35; background-color:lightgray; border:1px solid gray;}

Django: Redirect to previous page after login

See django docs for views.login(), you supply a 'next' value (as a hidden field) on the input form to redirect to after a successful login.

Change a Nullable column to NOT NULL with Default Value

you need to execute two queries:

One - to add the default value to the column required

ALTER TABLE 'Table_Name` ADD DEFAULT 'value' FOR 'Column_Name'

i want add default value to Column IsDeleted as below:

Example: ALTER TABLE [dbo].[Employees] ADD Default 0 for IsDeleted

Two - to alter the column value nullable to not null

ALTER TABLE 'table_name' ALTER COLUMN 'column_name' 'data_type' NOT NULL

i want to make the column IsDeleted as not null

ALTER TABLE [dbo].[Employees] Alter Column IsDeleted BIT NOT NULL

How to change symbol for decimal point in double.ToString()?

Some shortcut is to create a NumberFormatInfo class, set its NumberDecimalSeparator property to "." and use the class as parameter to ToString() method whenever u need it.

using System.Globalization;

NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ".";

value.ToString(nfi);

How to activate JMX on my JVM for access with jconsole?

On Linux, I used the following params:

-Djavax.management.builder.initial= 
-Dcom.sun.management.jmxremote 
-Dcom.sun.management.jmxremote.port=9010 
-Dcom.sun.management.jmxremote.local.only=false
-Dcom.sun.management.jmxremote.authenticate=false 
-Dcom.sun.management.jmxremote.ssl=false

and also I edited /etc/hosts so that the hostname resolves to the host address (192.168.0.x) rather than the loopback address (127.0.0.1)

Meaning of Open hashing and Closed hashing

The use of "closed" vs. "open" reflects whether or not we are locked in to using a certain position or data structure (this is an extremely vague description, but hopefully the rest helps).

For instance, the "open" in "open addressing" tells us the index (aka. address) at which an object will be stored in the hash table is not completely determined by its hash code. Instead, the index may vary depending on what's already in the hash table.

The "closed" in "closed hashing" refers to the fact that we never leave the hash table; every object is stored directly at an index in the hash table's internal array. Note that this is only possible by using some sort of open addressing strategy. This explains why "closed hashing" and "open addressing" are synonyms.

Contrast this with open hashing - in this strategy, none of the objects are actually stored in the hash table's array; instead once an object is hashed, it is stored in a list which is separate from the hash table's internal array. "open" refers to the freedom we get by leaving the hash table, and using a separate list. By the way, "separate list" hints at why open hashing is also known as "separate chaining".

In short, "closed" always refers to some sort of strict guarantee, like when we guarantee that objects are always stored directly within the hash table (closed hashing). Then, the opposite of "closed" is "open", so if you don't have such guarantees, the strategy is considered "open".

Convert SVG to image (JPEG, PNG, etc.) in the browser

I recently discovered a couple of image tracing libraries for JavaScript that indeed are able to build an acceptable approximation to the bitmap, both size and quality. I'm developing this JavaScript library and CLI :

https://www.npmjs.com/package/svg-png-converter

Which provides unified API for all of them, supporting browser and node, non depending on DOM, and a Command line tool.

For converting logos/cartoon/like images it does excellent job. For photos / realism some tweaking is needed since the output size can grow a lot.

It has a playground although right now I'm working on a better one, easier to use, since more features has been added:

https://cancerberosgx.github.io/demos/svg-png-converter/playground/#

Styling multi-line conditions in 'if' statements?

I usually use:

if ((cond1 == 'val1' and cond2 == 'val2' and
     cond3 == 'val3' and cond4 == 'val4')):
    do_something()

How to pass event as argument to an inline event handler in JavaScript?

Since inline events are executed as functions you can simply use arguments.

<p id="p" onclick="doSomething.apply(this, arguments)">

and

function doSomething(e) {
  if (!e) e = window.event;
  // 'e' is the event.
  // 'this' is the P element
}

The 'event' that is mentioned in the accepted answer is actually the name of the argument passed to the function. It has nothing to do with the global event.

Count rows with not empty value

As far as I can see, most of the solutions here count the number of non empty cells, and not the number of rows with non empty cell inside.

One possible solution for the range B3:E29 is for example

=SUM(ArrayFormula(IF(B3:B29&C3:C29&D3:D29&E3:E29="";0;1)))

Here ArrayFormula(IF(B3:B29&C3:C29&D3:D29&E3:E29="";0;1)) returns a column of 0 (if the row is empty) and 1 (else).

Another one is given in consideRatio's answer.

How to install libusb in Ubuntu

Usually to use the library you need to install the dev version.

Try

sudo apt-get install libusb-1.0-0-dev

Firing a Keyboard Event in Safari, using JavaScript

I am not very good with this but KeyboardEvent => see KeyboardEvent is initialized with initKeyEvent .
Here is an example for emitting event on <input type="text" /> element

_x000D_
_x000D_
document.getElementById("txbox").addEventListener("keypress", function(e) {_x000D_
  alert("Event " + e.type + " emitted!\nKey / Char Code: " + e.keyCode + " / " + e.charCode);_x000D_
}, false);_x000D_
_x000D_
document.getElementById("btn").addEventListener("click", function(e) {_x000D_
  var doc = document.getElementById("txbox");_x000D_
  var kEvent = document.createEvent("KeyboardEvent");_x000D_
  kEvent.initKeyEvent("keypress", true, true, null, false, false, false, false, 74, 74);_x000D_
  doc.dispatchEvent(kEvent);_x000D_
}, false);
_x000D_
<input id="txbox" type="text" value="" />_x000D_
<input id="btn" type="button" value="CLICK TO EMIT KEYPRESS ON TEXTBOX" />
_x000D_
_x000D_
_x000D_

Password Protect a SQLite DB. Is it possible?

You can encrypt your SQLite database with the SEE addon. This way you prevent unauthorized access/modification.

Quoting SQLite documentation:

The SQLite Encryption Extension (SEE) is an enhanced version of SQLite that encrypts database files using 128-bit or 256-Bit AES to help prevent unauthorized access or modification. The entire database file is encrypted so that to an outside observer, the database file appears to contain white noise. There is nothing that identifies the file as an SQLite database.

You can find more info about this addon in this link.

How can a add a row to a data frame in R?

There is a simpler way to append a record from one dataframe to another IF you know that the two dataframes share the same columns and types. To append one row from xx to yy just do the following where i is the i'th row in xx.

yy[nrow(yy)+1,] <- xx[i,]

Simple as that. No messy binds. If you need to append all of xx to yy, then either call a loop or take advantage of R's sequence abilities and do this:

zz[(nrow(zz)+1):(nrow(zz)+nrow(yy)),] <- yy[1:nrow(yy),]

Messagebox with input field

You can reference Microsoft.VisualBasic.dll.

Then using the code below.

Microsoft.VisualBasic.Interaction.InputBox("Question?","Title","Default Text");

Alternatively, by adding a using directive allowing for a shorter syntax in your code (which I'd personally prefer).

using Microsoft.VisualBasic;
...
Interaction.InputBox("Question?","Title","Default Text");

Or you can do what Pranay Rana suggests, that's what I would've done too...

Classes cannot be accessed from outside package

closeDrawers(boolean) is not public in android.support.v4.widget.DrawerLayout. Cannot be accessed from outside package

@Override
public void onBackPressed() {
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
       super.onBackPressed();
    }
}

Call a function with argument list in python

You can use *args and **kwargs syntax for variable length arguments.

What do *args and **kwargs mean?

And from the official python tutorial

http://docs.python.org/dev/tutorial/controlflow.html#more-on-defining-functions

How to get document height and width without using jquery

This is a cross-browser solution:

var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

Unicode characters in URLs

Use percent-encoded form. Some (mainly old) computers running Windows XP for example do not support Unicode, but rather ISO encodings. That is the reason percent-encoded URLs were invented. Also, if you give a URL printed on paper to a user, containing characters that cannot be easily typed, that user may have a hard time typing it (or just ignore it). Percent-encoded form can even be used in many of the oldest machines that ever existed (although they don't support internet of course).

There is a downside though, as percent-encoded characters are longer than the original ones, thus possibly resulting in really long URLs. But just try to ignore it, or use a URL shortener (I would recommend goo.gl in this case, which makes a 13-character long URL). Also, if you don't want to register for a Google account, try bit.ly (bit.ly makes slightly longer URLs, with the length being 14 characters).

How to check if a query string value is present via JavaScript?

var field = 'q';
var url = window.location.href;
if(url.indexOf('?' + field + '=') != -1)
    return true;
else if(url.indexOf('&' + field + '=') != -1)
    return true;
return false

Cannot retrieve string(s) from preferences (settings)

All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if to bind them all together in the way I believe you intend.

Email and phone Number Validation in android

I am always using this methode for Email Validation:

public boolean checkForEmail(Context c, EditText edit) {
    String str = edit.getText().toString();
    if (android.util.Patterns.EMAIL_ADDRESS.matcher(str).matches()) {
        return true;
    }
    Toast.makeText(c, "Email is not valid...", Toast.LENGTH_LONG).show();
    return false;
}

Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host

Calls to HTTPS services from one of our servers were also throwing the "Unable to read data from the transport connection : An existing connection was forcibly closed" exception. HTTP service, though, worked fine. Used Wireshark to see that it was a TLS handshake Failure. Ended up being that the cipher suite on the server needed to be updated.

node.js: cannot find module 'request'

I had same problem, for me npm install request --save solved the problem. Hope it helps.

Is there any way I can define a variable in LaTeX?

Use \def command:

\def \variable {Something that's better to use as a variable}

Be aware that \def overrides preexisting macros without any warnings and therefore can cause various subtle errors. To overcome this either use namespaced variables like my_var or fall back to \newcommand, \renewcommand commands instead.

QLabel: set color of text and background

This one is working perfect

QColorDialog *dialog = new QColorDialog(this);
QColor color=  dialog->getColor();
QVariant variant= color;
QString colcode = variant.toString();
ui->label->setStyleSheet("QLabel { background-color :"+colcode+" ; color : blue; }");

getColor() method returns the selected color. You can change label color using stylesheet

Trigger function when date is selected with jQuery UI datepicker

$(".datepicker").datepicker().on("changeDate", function(e) {
   console.log("Date changed: ", e.date);
});

Google Chrome forcing download of "f.txt" file

This issue appears to be causing ongoing consternation, so I will attempt to give a clearer answer than the previously posted answers, which only contain partial hints as to what's happening.

  • Some time around the summer of 2014, IT Security Engineer Michele Spagnuolo (apparently employed at Google Zurich) developed a proof-of-concept exploit and supporting tool called Rosetta Flash that demonstrated a way for hackers to run malicious Flash SWF files from a remote domain in a manner which tricks browsers into thinking it came from the same domain the user was currently browsing. This allows bypassing of the "same-origin policy" and can permit hackers a variety of exploits. You can read the details here: https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
    • Known affected browsers: Chrome, IE
    • Possibly unaffected browsers: Firefox
  • Adobe has released at least 5 different fixes over the past year while trying to comprehensively fix this vulnerability, but various major websites also introduced their own fixes earlier on in order to prevent mass vulnerability to their userbases. Among the sites to do so: Google, Youtube, Facebook, Github, and others. One component of the ad-hoc mitigation implemented by these website owners was to force the HTTP Header Content-Disposition: attachment; filename=f.txt on the returns from JSONP endpoints. This has the annoyance of causing the browser to automatically download a file called f.txt that you didn't request—but it is far better than your browser automatically running a possibly malicious Flash file.
  • In conclusion, the websites you were visiting when this file spontaneously downloaded are not bad or malicious, but some domain serving content on their pages (usually ads) had content with this exploit inside it. Note that this issue will be random and intermittent in nature because even visiting the same pages consecutively will often produce different ad content. For example, the advertisement domain ad.doubleclick.net probably serves out hundreds of thousands of different ads and only a small percentage likely contain malicious content. This is why various users online are confused thinking they fixed the issue or somehow affected it by uninstalling this program or running that scan, when in fact it is all unrelated. The f.txt download just means you were protected from a recent potential attack with this exploit and you should have no reason to believe you were compromised in any way.
  • The only way I'm aware that you could stop this f.txt file from being downloaded again in the future would be to block the most common domains that appear to be serving this exploit. I've put a short list below of some of the ones implicated in various posts. If you wanted to block these domains from touching your computer, you could add them to your firewall or alternatively you could use the HOSTS file technique described in the second section of this link: http://www.chromefans.org/chrome-tutorial/how-to-block-a-website-in-google-chrome.htm
  • Short list of domains you could block (by no means a comprehensive list). Most of these are highly associated with adware and malware:
    • ad.doubleclick.net
    • adclick.g.doubleclick.net
    • secure-us.imrworldwide.com
    • d.turn.com
    • ad.turn.com
    • secure.insightexpressai.com
    • core.insightexpressai.com

How to check View Source in Mobile Browsers (Both Android && Feature Phone)

This question is a few years old, and there are some good suggestions for workarounds, but I didn't really notice any answers that address the core of the original question head-on. So:

  • Providing a "universal" method for viewing source in a feature phone browser (or even arbitrary third-party smartphone browser) is impossible because "view source" — via any method — is a feature implemented in the browser. So how it's accessed, or even if it can be accessed, is up to the developers of the browser. I'm sure there are plenty of browsers that intentionally prevent the user from viewing page source, and if so then you're out of luck, except maybe for workarounds like the ones offered here.

  • Workarounds such as "view source" apps external to the browser, while useful in some cases, are at best an imperfect partial solution to the original request. It's never certain that any such app will display the source of the page in the same form as it's loaded by the phone's browser.

    Modern web content changes itself in all manner of ways through browser detection, session management, etc. so that the source loaded by any external app can never be relied on to represent the source as loaded by a different app. If you're going to use an external app to load a page because you want to see the source, you might as well just use Chrome (or, on an iOS device, Safari) instead.

How to change maven logging level to display only warning and errors?

You can achieve this with MAVEN_OPTS, for example
MAVEN_OPTS=-Dorg.slf4j.simpleLogger.defaultLogLevel=warn mvn clean

Rather than putting the system property directly on the command line. (At least for maven 3.3.1.)

Consider using ~/.mavenrc for setting MAVEN_OPTS if you would like logging changed for your login across all maven invocations.

batch file to check 64bit or 32bit OS

I really do not understand some of the answers given here (sorry for that). The top-voted answer for example does not return the Windows architecture, instead it will give you the processor architecture. While running a 32-bits Windows build on a 64-bits CPU you will get the wrong result (it's a query on hardware being used).

The safest option is to query the BuildLabEx value from the registry.

Determine x86 (intel) or x86-64 (amd)

reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion" /v "BuildLabEx" | >nul find /i ".x86fre."   && set "_ARCH_=x86" || set "_ARCH_=x86-64"

Determine x86 (intel), x86-64 (amd) or arm

set "_ARCH_=unknown"
reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion" /v "BuildLabEx" | >nul find /i ".x86fre."   && set "_ARCH_=x86" 
reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion" /v "BuildLabEx" | >nul find /i ".amd64fre." && set "_ARCH_=x86-64" 
reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion" /v "BuildLabEx" | >nul find /i ".armfre."   && set "_ARCH_=arm" 

An alternative option (mentioned before)

if defined ProgramFiles(x86) ( set "_ARCH_=x86-64" ) else ( set "_ARCH_=x86" )

The problem with the latter is when you mess up your variables, you are not able to use this method. Checking for the folder's existence will cause problems too when there are leftovers from a previous install (or some user purposely created the folder).

Resize image in the wiki of GitHub using Markdown

Updated:

Markdown syntax for images (external/internal):

![test](https://github.com/favicon.ico)

HTML code for sizing images (internal/external):

<img src="https://github.com/favicon.ico" width="48">

Example:

test


Old Answer:

This should work:

[[ http://url.to/image.png | height = 100px ]]

Source: https://guides.github.com/features/mastering-markdown/

How do I crop an image in Java?

There are two potentially major problem with the leading answer to this question. First, as per the docs:

public BufferedImage getSubimage(int x, int y, int w, int h)

Returns a subimage defined by a specified rectangular region. The returned BufferedImage shares the same data array as the original image.

Essentially, what this means is that result from getSubimage acts as a pointer which points at a subsection of the original image.

Why is this important? Well, if you are planning to edit the subimage for any reason, the edits will also happen to the original image. For example, I ran into this problem when I was using the smaller image in a separate window to zoom in on the original image. (kind of like a magnifying glass). I made it possible to invert the colors to see certain details more easily, but the area that was "zoomed" also got inverted in the original image! So there was a small section of the original image that had inverted colors while the rest of it remained normal. In many cases, this won't matter, but if you want to edit the image, or if you just want a copy of the cropped section, you might want to consider a method.

Which brings us to the second problem. Fortunately, it is not as big a problem as the first. getSubImage shares the same data array as the original image. That means that the entire original image is still stored in memory. Assuming that by "crop" the image you actually want a smaller image, you will need to redraw it as a new image rather than just get the subimage.

Try this:

BufferedImage img = image.getSubimage(startX, startY, endX, endY); //fill in the corners of the desired crop location here
BufferedImage copyOfImage = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = copyOfImage.createGraphics();
g.drawImage(img, 0, 0, null);
return copyOfImage; //or use it however you want

This technique will give you the cropped image you are looking for by itself, without the link back to the original image. This will preserve the integrity of the original image as well as save you the memory overhead of storing the larger image. (If you do dump the original image later)

How to load a controller from another controller in codeigniter?

yes you can (for version 2)

load like this inside your controller

 $this->load->library('../controllers/whathever');

and call the following method:

$this->whathever->functioname();

how to add json library

You can also install simplejson.

If you have pip (see https://pypi.python.org/pypi/pip) as your Python package manager you can install simplejson with:

 pip install simplejson

This is similar to the comment of installing with easy_install, but I prefer pip to easy_install as you can easily uninstall in pip with "pip uninstall package".

Get checkbox values using checkbox name using jquery

You are selecting inputs with name attribute of "bla", but your inputs have "bla[]" name attribute.

$("input[name='bla[]']").each(function (index, obj) {
        // loop all checked items
    });

http://jsfiddle.net/26axX/

Converting string to title case

You can directly change text or string to proper using this simple method, after checking for null or empty string values in order to eliminate errors:

public string textToProper(string text)
{
    string ProperText = string.Empty;
    if (!string.IsNullOrEmpty(text))
    {
        ProperText = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text);
    }
    else
    {
        ProperText = string.Empty;
    }
    return ProperText;
}

How do I view the list of functions a Linux shared library is exporting?

Among other already mentioned tools you can use also readelf (manual). It is similar to objdump but goes more into detail. See this for the difference explanation.

$ readelf -sW /lib/liblzma.so.5 |head -n10

Symbol table '.dynsym' contains 128 entries:
   Num:    Value  Size Type    Bind   Vis      Ndx Name
     0: 00000000     0 NOTYPE  LOCAL  DEFAULT  UND
     1: 00000000     0 FUNC    GLOBAL DEFAULT  UND pthread_mutex_unlock@GLIBC_2.0 (4)
     2: 00000000     0 FUNC    GLOBAL DEFAULT  UND pthread_mutex_destroy@GLIBC_2.0 (4)
     3: 00000000     0 NOTYPE  WEAK   DEFAULT  UND _ITM_deregisterTMCloneTable
     4: 00000000     0 FUNC    GLOBAL DEFAULT  UND memmove@GLIBC_2.0 (5)
     5: 00000000     0 FUNC    GLOBAL DEFAULT  UND free@GLIBC_2.0 (5)
     6: 00000000     0 FUNC    GLOBAL DEFAULT  UND memcpy@GLIBC_2.0 (5)

Creating folders inside a GitHub repository without using Git

Another thing you can do is just drag a folder from your computer into the GitHub repository page. This folder does have to have at least 1 item in it, though.

DisplayName attribute from Resources?

public class Person
{
    // Before C# 6.0
    [Display(Name = "Age", ResourceType = typeof(Testi18n.Resource))]
    public string Age { get; set; }

    // After C# 6.0
    // [Display(Name = nameof(Resource.Age), ResourceType = typeof(Resource))]
}
  1. Define ResourceType of the attribute so it looks for a resource
  2. Define Name of the attribute which is used for the key of resource, after C# 6.0, you can use nameof for strong typed support instead of hard coding the key.

  3. Set the culture of current thread in the controller.

Resource.Culture = CultureInfo.GetCultureInfo("zh-CN");

  1. Set the accessibility of the resource to public

  2. Display the label in cshtml like this

@Html.DisplayNameFor(model => model.Age)

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

This error comes when there is error in your query syntax check field names table name, mean check your query syntax.

Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0

I was using Postman to test my Laravel API.

I received an error that stated

"SQLSTATE[42S22]: Column not found: 1054 Unknown column" because Laravel was trying to automatically create two columns "created_at" and "updated_at".

I had to enter public $timestamps = false; to my model. Then, I tested again with Postman and saw that an "id" = 0 variable was being created in my database.

I finally had to add public $incrementing false; to fix my API.

Is it possible to specify proxy credentials in your web.config?

Directory Services/LDAP lookups can be used to serve this purpose. It involves some changes at infrastructure level, but most production environments have such provision

How can I convert a char to int in Java?

The ASCII table is arranged so that the value of the character '9' is nine greater than the value of '0'; the value of the character '8' is eight greater than the value of '0'; and so on.

So you can get the int value of a decimal digit char by subtracting '0'.

char x = '9';
int y = x - '0'; // gives the int value 9

How to search a list of tuples in Python

[i for i, v in enumerate(L) if v[0] == 53]

Adding the "Clear" Button to an iPhone UITextField

Swift 4+:

textField.clearButtonMode = UITextField.ViewMode.whileEditing

or even shorter:

textField.clearButtonMode = .whileEditing

Split Div Into 2 Columns Using CSS

Best way to divide a div vertically --

#parent {
    margin: 0;
    width: 100%;
}
.left {
    float: left;
    width: 60%;
}
.right {
    overflow: hidden;
    width: 40%;
}

How to concatenate multiple column values into a single column in Panda dataframe

I think you are missing one %s

df['combined']=df.apply(lambda x:'%s_%s_%s' % (x['bar'],x['foo'],x['new']),axis=1)

How do I send a POST request as a JSON?

This works perfect for Python 3.5, if the URL contains Query String / Parameter value,

Request URL = https://bah2.com/ws/rest/v1/concept/
Parameter value = 21f6bb43-98a1-419d-8f0c-8133669e40ca

import requests

url = 'https://bahbah2.com/ws/rest/v1/concept/21f6bb43-98a1-419d-8f0c-8133669e40ca'
data = {"name": "Value"}
r = requests.post(url, auth=('username', 'password'), verify=False, json=data)
print(r.status_code)

How to set back button text in Swift

You can do it from interface builder as follows:

click on the navigation item of previous view controller

enter image description here

from the attributes inspector set the back button text to whatever you want. Thats it!!

enter image description here

Angular2 Error: There is no directive with "exportAs" set to "ngForm"

If you are getting this instead:

Error: Template parse errors:

There is no directive with "exportAs" set to "ngModel"

Which was reported as a bug in github, then likely it is not a bug since you might:

  1. have a syntax error (e.g. an extra bracket: [(ngModel)]]=), OR
  2. be mixing Reactive forms directives, such as formControlName, with the ngModel directive. This "has been deprecated in Angular v6 and will be removed in Angular v7", since this mixes both form strategies, making it:
  • seem like the actual ngModel directive is being used, but in fact it's an input/output property named ngModel on the reactive form directive that simply approximates (some of) its behavior. Specifically, it allows getting/setting the value and intercepting value events. However, some of ngModel's other features - like delaying updates withngModelOptions or exporting the directive - simply don't work (...)

  • this pattern mixes template-driven and reactive forms strategies, which we generally don't recommend because it doesn't take advantage of the full benefits of either strategy. (...)

  • To update your code before v7, you'll want to decide whether to stick with reactive form directives (and get/set values using reactive forms patterns) or switch over to template-driven directives.

When you have an input like this:

<input formControlName="first" [(ngModel)]="value">

It will show a warning about mixed form strategies in the browser's console:

It looks like you're using ngModel on the same form field as formControlName.

However, if you add the ngModel as a value in a reference variable, example:

<input formControlName="first" #firstIn="ngModel" [(ngModel)]="value">

The error above is then triggered and no warning about strategy mixing is shown.

WordPress: get author info from post id

<?php
  $field = 'display_name';
  the_author_meta($field);
?>

Valid values for the $field parameter include:

  • admin_color
  • aim
  • comment_shortcuts
  • description
  • display_name
  • first_name
  • ID
  • jabber
  • last_name
  • nickname
  • plugins_last_view
  • plugins_per_page
  • rich_editing
  • syntax_highlighting
  • user_activation_key
  • user_description
  • user_email
  • user_firstname
  • user_lastname
  • user_level
  • user_login
  • user_nicename
  • user_pass
  • user_registered
  • user_status
  • user_url
  • yim

Filtering DataGridView without changing datasource

A simpler way is to transverse the data, and hide the lines with the Visible property.

// Prevent exception when hiding rows out of view
CurrencyManager currencyManager = (CurrencyManager)BindingContext[dataGridView3.DataSource];
currencyManager.SuspendBinding();

// Show all lines
for (int u = 0; u < dataGridView3.RowCount; u++)
{
    dataGridView3.Rows[u].Visible = true;
    x++;
}

// Hide the ones that you want with the filter you want.
for (int u = 0; u < dataGridView3.RowCount; u++)
{
    if (dataGridView3.Rows[u].Cells[4].Value == "The filter string")
    {
        dataGridView3.Rows[u].Visible = true;
    }
    else
    {
        dataGridView3.Rows[u].Visible = false;
    }
}

// Resume data grid view binding
currencyManager.ResumeBinding();

Just an idea... it works for me.

How can I find which tables reference a given table in Oracle SQL Developer?

To add to the above answer for sql developer plugin, using the below xml will help in getting the column associated with the foreign key.

    <items>
        <item type="editor" node="TableNode" vertical="true">
        <title><![CDATA[FK References]]></title>
        <query>
            <sql>
                <![CDATA[select a.owner,
                                a.constraint_name,
                                a.table_name,
                                b.column_name,
                                a.status
                         from   all_constraints a
                         join   all_cons_columns b ON b.constraint_name = a.constraint_name
                         where  a.constraint_type = 'R'
                                and exists(
                                   select 1
                                   from   all_constraints
                                   where  constraint_name=a.r_constraint_name
                                          and constraint_type in ('P', 'U')
                                          and table_name = :OBJECT_NAME
                                          and owner = :OBJECT_OWNER)
                                   order by table_name, constraint_name]]>
            </sql>
        </query>
        </item>
    </items>

HTML5 input type range show range value

This uses javascript, not jquery directly. It might help get you started.

_x000D_
_x000D_
function updateTextInput(val) {_x000D_
          document.getElementById('textInput').value=val; _x000D_
        }
_x000D_
<input type="range" name="rangeInput" min="0" max="100" onchange="updateTextInput(this.value);">_x000D_
<input type="text" id="textInput" value="">
_x000D_
_x000D_
_x000D_

How to parse string into date?

You can use:

SELECT CONVERT(datetime, '24.04.2012', 103) AS Date

Reference: CAST and CONVERT (Transact-SQL)

Execute Python script via crontab

As you have mentioned it doesn't change anything.

First, you should redirect both standard input and standard error from the crontab execution like below:

*/2 * * * * /usr/bin/python /home/souza/Documets/Listener/listener.py > /tmp/listener.log 2>&1

Then you can view the file /tmp/listener.log to see if the script executed as you expected.

Second, I guess what you mean by change anything is by watching the files created by your program:

f = file('counter', 'r+w')
json_file = file('json_file_create_server.json', 'r+w')

The crontab job above won't create these file in directory /home/souza/Documets/Listener, as the cron job is not executed in this directory, and you use relative path in the program. So to create this file in directory /home/souza/Documets/Listener, the following cron job will do the trick:

*/2 * * * * cd /home/souza/Documets/Listener && /usr/bin/python listener.py > /tmp/listener.log 2>&1

Change to the working directory and execute the script from there, and then you can view the files created in place.

How to add a second x-axis in matplotlib

From matplotlib 3.1 onwards you may use ax.secondary_xaxis

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(1,13, num=301)
y = (np.sin(x)+1.01)*3000

# Define function and its inverse
f = lambda x: 1/(1+x)
g = lambda x: 1/x-1

fig, ax = plt.subplots()
ax.semilogy(x, y, label='DM')

ax2 = ax.secondary_xaxis("top", functions=(f,g))

ax2.set_xlabel("1/(x+1)")
ax.set_xlabel("x")
plt.show()

Set background color of WPF Textbox in C# code

You can use hex colors:

your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)

Mixing a PHP variable with a string literal

echo "{$test}y";

You can use braces to remove ambiguity when interpolating variables directly in strings.

Also, this doesn't work with single quotes. So:

echo '{$test}y';

will output

{$test}y

C++ Fatal Error LNK1120: 1 unresolved externals

In my case, the argument type was different in the header file and .cpp file. In the header file the type was std::wstring and in the .cpp file it was LPCWSTR.

How do I style a <select> dropdown with only CSS?

I had this exact problem, except I couldn't use images and was not limited by browser support. This should be «on spec» and with luck start working everywhere eventually.

It uses layered rotated background layers to «cut out» a dropdown arrow, as pseudo-elements wouldn't work for the select element.

Edit: In this updated version I am using CSS variables and a tiny theming system.

_x000D_
_x000D_
:root {_x000D_
  --radius: 2px;_x000D_
  --baseFg: dimgray;_x000D_
  --baseBg: white;_x000D_
  --accentFg: #006fc2;_x000D_
  --accentBg: #bae1ff;_x000D_
}_x000D_
_x000D_
.theme-pink {_x000D_
  --radius: 2em;_x000D_
  --baseFg: #c70062;_x000D_
  --baseBg: #ffe3f1;_x000D_
  --accentFg: #c70062;_x000D_
  --accentBg: #ffaad4;_x000D_
}_x000D_
_x000D_
.theme-construction {_x000D_
  --radius: 0;_x000D_
  --baseFg: white;_x000D_
  --baseBg: black;_x000D_
  --accentFg: black;_x000D_
  --accentBg: orange;_x000D_
}_x000D_
_x000D_
select {_x000D_
  font: 400 12px/1.3 sans-serif;_x000D_
  -webkit-appearance: none;_x000D_
  appearance: none;_x000D_
  color: var(--baseFg);_x000D_
  border: 1px solid var(--baseFg);_x000D_
  line-height: 1;_x000D_
  outline: 0;_x000D_
  padding: 0.65em 2.5em 0.55em 0.75em;_x000D_
  border-radius: var(--radius);_x000D_
  background-color: var(--baseBg);_x000D_
  background-image: linear-gradient(var(--baseFg), var(--baseFg)),_x000D_
    linear-gradient(-135deg, transparent 50%, var(--accentBg) 50%),_x000D_
    linear-gradient(-225deg, transparent 50%, var(--accentBg) 50%),_x000D_
    linear-gradient(var(--accentBg) 42%, var(--accentFg) 42%);_x000D_
  background-repeat: no-repeat, no-repeat, no-repeat, no-repeat;_x000D_
  background-size: 1px 100%, 20px 22px, 20px 22px, 20px 100%;_x000D_
  background-position: right 20px center, right bottom, right bottom, right bottom;   _x000D_
}_x000D_
_x000D_
select:hover {_x000D_
  background-image: linear-gradient(var(--accentFg), var(--accentFg)),_x000D_
    linear-gradient(-135deg, transparent 50%, var(--accentFg) 50%),_x000D_
    linear-gradient(-225deg, transparent 50%, var(--accentFg) 50%),_x000D_
    linear-gradient(var(--accentFg) 42%, var(--accentBg) 42%);_x000D_
}_x000D_
_x000D_
select:active {_x000D_
  background-image: linear-gradient(var(--accentFg), var(--accentFg)),_x000D_
    linear-gradient(-135deg, transparent 50%, var(--accentFg) 50%),_x000D_
    linear-gradient(-225deg, transparent 50%, var(--accentFg) 50%),_x000D_
    linear-gradient(var(--accentFg) 42%, var(--accentBg) 42%);_x000D_
  color: var(--accentBg);_x000D_
  border-color: var(--accentFg);_x000D_
  background-color: var(--accentFg);_x000D_
}
_x000D_
<select>_x000D_
  <option>So many options</option>_x000D_
  <option>...</option>_x000D_
</select>_x000D_
_x000D_
<select class="theme-pink">_x000D_
  <option>So many options</option>_x000D_
  <option>...</option>_x000D_
</select>_x000D_
_x000D_
<select class="theme-construction">_x000D_
  <option>So many options</option>_x000D_
  <option>...</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Logical Operators, || or OR?

They are used for different purposes and in fact have different operator precedences. The && and || operators are intended for Boolean conditions, whereas and and or are intended for control flow.

For example, the following is a Boolean condition:

if ($foo == $bar && $baz != $quxx) {

This differs from control flow:

doSomething() or die();

JavaFX 2.1 TableView refresh items

Well after looking for all the possible solutions. Tried clearing data first and then added in tableview tableView.getItems().clear(); still that does not resolved my problem. I tried all the answers given here but did not worked for me and I still had stale objects in my table as shown in image below:

enter image description here

In order to fix it I created a DUMMY label and used setGraphic as follows:

enter image description here

Copy files without overwrite

You can try this:

echo n | copy /-y <SOURCE> <DESTINATION>

-y simply prompts before overwriting and we can pipe n to all those questions. So this would in essence just copy non-existing files. :)

Excluding Maven dependencies

You can utilize the dependency management mechanism.

If you create entries in the <dependencyManagement> section of your pom for spring-security-web and spring-web with the desired 3.1.0 version set the managed version of the artifact will override those specified in the transitive dependency tree.

I'm not sure if that really saves you any code, but it is a cleaner solution IMO.

Print the data in ResultSet along with column names

use further as

rs.getString(1);
rs.getInt(2);

1, 2 is the column number of table and set int or string as per data-type of coloumn

refresh both the External data source and pivot tables together within a time schedule

I used the above answer but made use of the RefreshAll method. I also changed it to allow for multiple connections without having to specify the names. I then linked this to a button on my spreadsheet.

Sub Refresh()

    Dim conn As Variant

    For Each conn In ActiveWorkbook.Connections
        conn.ODBCConnection.BackgroundQuery = False
    Next conn

    ActiveWorkbook.RefreshAll
End Sub

Git on Mac OS X v10.7 (Lion)

You have to find where the Git executable is and then add the folder to the PATH environment variable in file .bash_profile.

Using terminal:

  1. Search for Git:

     sudo find / -name git
    
  2. Edit the .bash_profile file. Add:

     PATH="<Directory of Git>:$PATH"
    

Git is back :-)

Anyway, I suggest you to install Git using MacPorts. In this way you can easily upgrade your Git instance to the newest release.

Array versus linked-list

Another good reason is that linked lists lend themselves nicely to efficient multi-threaded implementations. The reason for this is that changes tend to be local - affecting only a pointer or two for insert and remove at a localized part of the data structure. So, you can have many threads working on the same linked list. Even more, it's possible to create lock-free versions using CAS-type operations and avoid heavy-weight locks altogether.

With a linked list, iterators can also traverse the list while modifications are occurring. In the optimistic case where modifications don't collide, iterators can continue without contention.

With an array, any change that modifies the size of the array is likely to require locking a large portion of the array and in fact, it's rare that this is done without a global lock across the whole array so modifications become stop the world affairs.

textarea character limit

I believe if you use delegates, it would work..

$("textarea").on('change paste keyup', function () {
    var currText = $(this).val();
    if (currText.length > 500) {
        var text = $(this).text();
        $(this).text(text.substr(0, 500));
        alert("You have reached the maximum length for this field");
    }
});

Find the number of downloads for a particular app in apple appstore

There is no way to know unless the particular company reveals the info. The best you can do is find a few companies that are sharing and then extrapolate based on app ranking (which is available publicly). The best you'll get is a ball park estimate.

What are the date formats available in SimpleDateFormat class?

Let me throw out some example code that I got from http://www3.ntu.edu.sg/home/ehchua/programming/java/DateTimeCalendar.html Then you can play around with different options until you understand it.

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTest {
   public static void main(String[] args) {
       Date now = new Date();

       //This is just Date's toString method and doesn't involve SimpleDateFormat
       System.out.println("toString(): " + now);  // dow mon dd hh:mm:ss zzz yyyy
       //Shows  "Mon Oct 08 08:17:06 EDT 2012"

       SimpleDateFormat dateFormatter = new SimpleDateFormat("E, y-M-d 'at' h:m:s a z");
       System.out.println("Format 1:   " + dateFormatter.format(now));
       // Shows  "Mon, 2012-10-8 at 8:17:6 AM EDT"

       dateFormatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
       System.out.println("Format 2:   " + dateFormatter.format(now));
       // Shows  "Mon 2012.10.08 at 08:17:06 AM EDT"

       dateFormatter = new SimpleDateFormat("EEEE, MMMM d, yyyy");
       System.out.println("Format 3:   " + dateFormatter.format(now));
       // Shows  "Monday, October 8, 2012"

       // SimpleDateFormat can be used to control the date/time display format:
       //   E (day of week): 3E or fewer (in text xxx), >3E (in full text)
       //   M (month): M (in number), MM (in number with leading zero)
       //              3M: (in text xxx), >3M: (in full text full)
       //   h (hour): h, hh (with leading zero)
       //   m (minute)
       //   s (second)
       //   a (AM/PM)
       //   H (hour in 0 to 23)
       //   z (time zone)
       //  (there may be more listed under the API - I didn't check)

   }

}

Good luck!

Bootstrap NavBar with left, center or right aligned items

I found the following was a better solution depending on the content of your left, center and right items. A width of 100% without a margin caused overlapping of divs and was preventing anchor tags to work correctly - that is without the messy use of z-indexes.

.navbar-brand
{
    position: absolute;
    width: 100%;
    left: 0;
    margin: auto;
    margin-left: 48%;
}

stale element reference: element is not attached to the page document

To handle it, I use the following click method. This will attempt to find and click the element. If the DOM changes between the find and click, it will try again. The idea is that if it failed and I try again immediately the second attempt will succeed. If the DOM changes are very rapid then this will not work.

public boolean retryingFindClick(By by) {
    boolean result = false;
    int attempts = 0;
    while(attempts < 2) {
        try {
            driver.findElement(by).click();
            result = true;
            break;
        } catch(StaleElementException e) {
        }
        attempts++;
    }
    return result;
}

implement time delay in c

For delays as large as one minute, sleep() is a nice choice.

If someday, you want to pause on delays smaller than one second, you may want to consider poll() with a timeout.

Both are POSIX.

Choosing the best concurrency list in Java

If set is sufficient, ConcurrentSkipListSet might be used. (Its implementation is based on ConcurrentSkipListMap which implements a skip list.)

The expected average time cost is log(n) for the contains, add, and remove operations; the size method is not a constant-time operation.

Background image jumps when address bar hides iOS/Android/Mobile Chrome

I've got a similar issue on a header of our website.

html, body {
    height:100%;
}
.header {
    height:100%;
}

This will end up in a jumpy scrolling experience on android chrome, because the .header-container will rescale after the url-bar hides and the finger is removed from screen.

CSS-Solution:

Adding the following two lines, will prevent that the url-bar hides and vertical scrolling is still possible:

html {
    overflow: hidden;
}
body {
    overflow-y: scroll;
    -webkit-overflow-scrolling:touch;
}

Leaflet - How to find existing markers, and delete markers?

Here is the code and demo for Adding the marker, deleting any of the marker and also getting all the present/added markers :

Here is the entire JSFiddle code . Also here is the full page demo.

Adding the marker :

// Script for adding marker on map click
map.on('click', onMapClick);

function onMapClick(e) {

    var geojsonFeature = {

        "type": "Feature",
        "properties": {},
        "geometry": {
                "type": "Point",
                "coordinates": [e.latlng.lat, e.latlng.lng]
        }
    }

    var marker;

    L.geoJson(geojsonFeature, {

        pointToLayer: function(feature, latlng){

            marker = L.marker(e.latlng, {

                title: "Resource Location",
                alt: "Resource Location",
                riseOnHover: true,
                draggable: true,

            }).bindPopup("<input type='button' value='Delete this marker' class='marker-delete-button'/>");

            marker.on("popupopen", onPopupOpen);

            return marker;
        }
    }).addTo(map);
}

Deleting the Marker :

// Function to handle delete as well as other events on marker popup open

function onPopupOpen() {

    var tempMarker = this;

    // To remove marker on click of delete button in the popup of marker
    $(".marker-delete-button:visible").click(function () {
        map.removeLayer(tempMarker);
    });
}

Getting all the markers in the map :

// getting all the markers at once
function getAllMarkers() {

    var allMarkersObjArray = []; // for marker objects
    var allMarkersGeoJsonArray = []; // for readable geoJson markers

    $.each(map._layers, function (ml) {

        if (map._layers[ml].feature) {

            allMarkersObjArray.push(this)
            allMarkersGeoJsonArray.push(JSON.stringify(this.toGeoJSON()))
        }
    })

    console.log(allMarkersObjArray);
}

// any html element such as button, div to call the function()
$(".get-markers").on("click", getAllMarkers);

Handling optional parameters in javascript

I think you want to use typeof() here:

function f(id, parameters, callback) {
  console.log(typeof(parameters)+" "+typeof(callback));
}

f("hi", {"a":"boo"}, f); //prints "object function"
f("hi", f, {"a":"boo"}); //prints "function object"

boolean in an if statement

In the plain "if" the variable will be coerced to a Boolean and it uses toBoolean on the object:-

    Argument Type   Result

    Undefined       false
    Null            false
    Boolean         The result equals the input argument (no conversion).
    Number          The result is false if the argument is +0, -0, or NaN;
                    otherwise the result is true.
    String          The result is false if the argument is the empty 
                    String (its length is zero); otherwise the result is true.
    Object          true.

But comparison with === does not have any type coercion, so they must be equal without coercion.

If you are saying that the object may not even be a Boolean then you may have to consider more than just true/false.

if(x===true){
...
} else if(x===false){
....
} else {
....
}

Escape double quotes in a string

You're misunderstanding escaping.

The extra " characters are part of the string literal; they are interpreted by the compiler as a single ".

The actual value of your string is still He said to me , "Hello World".How are you ?, as you'll see if you print it at runtime.

Access a URL and read Data with R

Often data on webpages is in the form of an XML table. You can read an XML table into R using the package XML.

In this package, the function

readHTMLTable(<url>)

will look through a page for XML tables and return a list of data frames (one for each table found).

docker container ssl certificates

You can use relative path to mount the volume to container:

docker run -v `pwd`/certs:/container/path/to/certs ...

Note the back tick on the pwd which give you the present working directory. It assumes you have the certs folder in current directory that the docker run is executed. Kinda great for local development and keep the certs folder visible to your project.

Getting the text that follows after the regex match

Your regex "sentence(.*)" is right. To retrieve the contents of the group in parenthesis, you would call:

Pattern p = Pattern.compile( "sentence(.*)" );
Matcher m = p.matcher( "some lame sentence that is awesome" );
if ( m.find() ) {
   String s = m.group(1); // " that is awesome"
}

Note the use of m.find() in this case (attempts to find anywhere on the string) and not m.matches() (would fail because of the prefix "some lame"; in this case the regex would need to be ".*sentence(.*)")

Why can't I use background image and color together?

Actually there is a way you can use a background color with a background image. In this case, the background part will be filled with that specified color instead of a white/transparent one.

In order to achieve that, you need to set the background property like this:

.bg-image-with-color {
    background: url("example.png") no-repeat, #ff0000;
}

Note the comma and the color code after no-repeat; this sets the background color you wish.

I discovered this in this YouTube video, however I'm not affiliated with that channel or video in any means.

How to get a function name as a string?

This function will return the caller's function name.

def func_name():
    import traceback
    return traceback.extract_stack(None, 2)[0][2]

It is like Albert Vonpupp's answer with a friendly wrapper.