Programs & Examples On #Svnkit

SVNKit is a pure Java Subversion toolkit. SVNKit allows a Java developer to access Subversion features from within a Java application.

How to make space between LinearLayout children?

Since API Level 14 you can just add a (transparent) divider drawable:

android:divider="@drawable/divider"
android:showDividers="middle"

and it will handle the rest for you!

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

In your Case you can write the following jquery code:

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").attr("readonly", false); 
     }
     else{ 
         $("#no_of_staff").attr("readonly", true); 
     }
   });
});

Here is the Fiddle: http://jsfiddle.net/P4QWx/3/

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

You could use moment.js with Postman to give you that timestamp format.

You can add this to the pre-request script:

const moment = require('moment');
pm.globals.set("today", moment().format("MM/DD/YYYY"));

Then reference {{today}} where ever you need it.

If you add this to the Collection Level Pre-request Script, it will be run for each request in the Collection. Rather than needing to add it to all the requests individually.

For more information about using moment in Postman, I wrote a short blog post: https://dannydainton.com/2018/05/21/hold-on-wait-a-moment/

Why do we need to use flatMap?

It's not an array of arrays. It's an observable of observable(s).

The following returns an observable stream of string.

requestStream
  .map(function(requestUrl) {
    return requestUrl;
  });

While this returns an observable stream of observable stream of json

requestStream
  .map(function(requestUrl) {
    return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));
  });

flatMap flattens the observable automatically for us so we can observe the json stream directly

iOS - Calling App Delegate method from ViewController

Update for Swift 3.0 and higher

//
// Step 1:- Create a method in AppDelegate.swift
//
func someMethodInAppDelegate() {

    print("someMethodInAppDelegate called")
}

calling above method from your controller by followings

//
// Step 2:- Getting a reference to the AppDelegate & calling the require method...
//
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {

    appDelegate.someMethodInAppDelegate()
}

Output:

enter image description here

How can I make an EXE file from a Python program?

Auto PY to EXE - A .py to .exe converter using a simple graphical interface built using Eel and PyInstaller in Python.


py2exe is probably what you want, but it only works on Windows.
PyInstaller works on Windows and Linux.
Py2app works on the Mac.

Animate scroll to ID on page load

You are only scrolling the height of your element. offset() returns the coordinates of an element relative to the document, and top param will give you the element's distance in pixels along the y-axis:

$("html, body").animate({ scrollTop: $('#title1').offset().top }, 1000);

And you can also add a delay to it:

$("html, body").delay(2000).animate({scrollTop: $('#title1').offset().top }, 2000);

How to get HttpContext.Current in ASP.NET Core?

There is a solution to this if you really need a static access to the current context. In Startup.Configure(….)

app.Use(async (httpContext, next) =>
{
    CallContext.LogicalSetData("CurrentContextKey", httpContext);
    try
    {
        await next();
    }
    finally
    {
        CallContext.FreeNamedDataSlot("CurrentContextKey");
    }
});

And when you need it you can get it with :

HttpContext context = CallContext.LogicalGetData("CurrentContextKey") as HttpContext;

I hope that helps. Keep in mind this workaround is when you don’t have a choice. The best practice is to use de dependency injection.

How to style dt and dd so they are on the same line?

Because I have yet to see an example that works for my use case, here is the most full-proof solution that I was able to realize.

_x000D_
_x000D_
dd {_x000D_
    margin: 0;_x000D_
}_x000D_
dd::after {_x000D_
    content: '\A';_x000D_
    white-space: pre-line;_x000D_
}_x000D_
dd:last-of-type::after {_x000D_
    content: '';_x000D_
}_x000D_
dd, dt {_x000D_
    display: inline;_x000D_
}_x000D_
dd, dt, .address {_x000D_
    vertical-align: middle;_x000D_
}_x000D_
dt {_x000D_
    font-weight: bolder;_x000D_
}_x000D_
dt::after {_x000D_
    content: ': ';_x000D_
}_x000D_
.address {_x000D_
    display: inline-block;_x000D_
    white-space: pre;_x000D_
}
_x000D_
Surrounding_x000D_
_x000D_
<dl>_x000D_
  <dt>Phone Number</dt>_x000D_
  <dd>+1 (800) 555-1234</dd>_x000D_
  <dt>Email Address</dt>_x000D_
  <dd><a href="#">[email protected]</a></dd>_x000D_
  <dt>Postal Address</dt>_x000D_
  <dd><div class="address">123 FAKE ST<br />EXAMPLE EX  00000</div></dd>_x000D_
</dl>_x000D_
_x000D_
Text
_x000D_
_x000D_
_x000D_

Strangely enough, it doesn't work with display: inline-block. I suppose that if you need to set the size of any of the dt elements or dd elements, you could set the dl's display as display: flexbox; display: -webkit-flex; display: flex; and the flex shorthand of the dd elements and the dt elements as something like flex: 1 1 50% and display as display: inline-block. But I haven't tested that, so approach with caution.

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

The particular exception message is telling you that the mentioned class is missing in the classpath. As the org.apache.commons.io package name hints, the mentioned class is part of the http://commons.apache.org/io project.

And indeed, Commons FileUpload has Commons IO as a dependency. You need to download and drop commons-io.jar in the /WEB-INF/lib as well.

See also:

JQuery show and hide div on mouse click (animate)

Use slideToggle(500) function with a duration in milliseconds for getting a better effect.

Sample Html

<body>
    <div class="growth-step js--growth-step">
        <div class="step-title">
            <div class="num">2.</div>
            <h3>How Can Aria Help Your Business</h3>
        </div>
        <div class="step-details ">
            <p>At Aria solutions, we’ve taken the consultancy concept one step further by offering a full service
                management organization with expertise. </p>
        </div>
    </div>
    <div class="growth-step js--growth-step">
        <div class="step-title">
            <div class="num">3.</div>
            <h3>How Can Aria Help Your Business</h3>
        </div>
        <div class="step-details">
            <p>At Aria solutions, we’ve taken the consultancy concept one step further by offering a full service
                management organization with expertise. </p>
        </div>
    </div>
</body>

In your js file, if you need child propagation for the animation then remove the second click event function and its codes.

$(document).ready(function(){
    $(".js--growth-step").click(function(event){
       $(this).children(".step-details").slideToggle(500);
         return false;
    });
//for stoping child to manipulate the animation
    $(".js--growth-step .step-details").click(function(event) {
        event.stopPropagation();
   });
});

Difference between object and class in Scala

Scala class same as Java Class but scala not gives you any entry method in class, like main method in java. The main method associated with object keyword. You can think of the object keyword as creating a singleton object of a class that is defined implicitly.

more information check this article class and object keyword in scala programming

Detecting IE11 using CSS Capability/Feature Detection

So I found my own solution to this problem in the end.

After searching through Microsoft documentation I managed to find a new IE11 only style msTextCombineHorizontal

In my test, I check for IE10 styles and if they are a positive match, then I check for the IE11 only style. If I find it, then it's IE11+, if I don't, then it's IE10.

Code Example: Detect IE10 and IE11 by CSS Capability Testing (JSFiddle)

_x000D_
_x000D_
 /**_x000D_
  Target IE 10 with JavaScript and CSS property detection._x000D_
  _x000D_
  # 2013 by Tim Pietrusky_x000D_
  # timpietrusky.com_x000D_
 **/_x000D_
_x000D_
 // IE 10 only CSS properties_x000D_
 var ie10Styles = [_x000D_
     'msTouchAction',_x000D_
     'msWrapFlow',_x000D_
     'msWrapMargin',_x000D_
     'msWrapThrough',_x000D_
     'msOverflowStyle',_x000D_
     'msScrollChaining',_x000D_
     'msScrollLimit',_x000D_
     'msScrollLimitXMin',_x000D_
     'msScrollLimitYMin',_x000D_
     'msScrollLimitXMax',_x000D_
     'msScrollLimitYMax',_x000D_
     'msScrollRails',_x000D_
     'msScrollSnapPointsX',_x000D_
     'msScrollSnapPointsY',_x000D_
     'msScrollSnapType',_x000D_
     'msScrollSnapX',_x000D_
     'msScrollSnapY',_x000D_
     'msScrollTranslation',_x000D_
     'msFlexbox',_x000D_
     'msFlex',_x000D_
     'msFlexOrder'];_x000D_
_x000D_
 var ie11Styles = [_x000D_
     'msTextCombineHorizontal'];_x000D_
_x000D_
 /*_x000D_
  * Test all IE only CSS properties_x000D_
  */_x000D_
 var d = document;_x000D_
 var b = d.body;_x000D_
 var s = b.style;_x000D_
 var ieVersion = null;_x000D_
 var property;_x000D_
_x000D_
 // Test IE10 properties_x000D_
 for (var i = 0; i < ie10Styles.length; i++) {_x000D_
     property = ie10Styles[i];_x000D_
_x000D_
     if (s[property] != undefined) {_x000D_
         ieVersion = "ie10";_x000D_
         createEl("IE10 style found: " + property);_x000D_
     }_x000D_
 }_x000D_
_x000D_
 // Test IE11 properties_x000D_
 for (var i = 0; i < ie11Styles.length; i++) {_x000D_
     property = ie11Styles[i];_x000D_
_x000D_
     if (s[property] != undefined) {_x000D_
         ieVersion = "ie11";_x000D_
         createEl("IE11 style found: " + property);_x000D_
     }_x000D_
 }_x000D_
_x000D_
 if (ieVersion) {_x000D_
     b.className = ieVersion;_x000D_
     $('#versionId').html('Version: ' + ieVersion);_x000D_
 } else {_x000D_
     createEl('Not IE10 or 11.');_x000D_
 }_x000D_
_x000D_
 /*_x000D_
  * Just a little helper to create a DOM element_x000D_
  */_x000D_
 function createEl(content) {_x000D_
     el = d.createElement('div');_x000D_
     el.innerHTML = content;_x000D_
     b.appendChild(el);_x000D_
 }_x000D_
_x000D_
 /*_x000D_
  * List of IE CSS stuff:_x000D_
  * http://msdn.microsoft.com/en-us/library/ie/hh869403(v=vs.85).aspx_x000D_
  */
_x000D_
body {_x000D_
    font: 1.25em sans-serif;_x000D_
}_x000D_
div {_x000D_
    background: red;_x000D_
    color:#fff;_x000D_
    padding: 1em;_x000D_
}_x000D_
.ie10 div {_x000D_
    background: green;_x000D_
    margin-bottom:.5em;_x000D_
}_x000D_
.ie11 div {_x000D_
    background: purple;_x000D_
    margin-bottom:.5em;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<h1>Detect IE10 and IE11 by CSS Capability Testing</h1>_x000D_
_x000D_
_x000D_
<h2 id="versionId"></h2>
_x000D_
_x000D_
_x000D_

I will update the code example with more styles when I discover them.

NOTE: This will almost certainly identify IE12 and IE13 as "IE11", as those styles will probably carry forward. I will add further tests as new versions roll out, and hopefully be able to rely again on Modernizr.

I'm using this test for fallback behavior. The fallback behavior is just less glamorous styling, it doesn't have reduced functionality.

How to prevent scientific notation in R?

Try format function:

> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"

SSH library for Java

There is a brand new version of Jsch up on github: https://github.com/vngx/vngx-jsch Some of the improvements include: comprehensive javadoc, enhanced performance, improved exception handling, and better RFC spec adherence. If you wish to contribute in any way please open an issue or send a pull request.

Difference between clustered and nonclustered index

You should be using indexes to help SQL server performance. Usually that implies that columns that are used to find rows in a table are indexed.

Clustered indexes makes SQL server order the rows on disk according to the index order. This implies that if you access data in the order of a clustered index, then the data will be present on disk in the correct order. However if the column(s) that have a clustered index is frequently changed, then the row(s) will move around on disk, causing overhead - which generally is not a good idea.

Having many indexes is not good either. They cost to maintain. So start out with the obvious ones, and then profile to see which ones you miss and would benefit from. You do not need them from start, they can be added later on.

Most column datatypes can be used when indexing, but it is better to have small columns indexed than large. Also it is common to create indexes on groups of columns (e.g. country + city + street).

Also you will not notice performance issues until you have quite a bit of data in your tables. And another thing to think about is that SQL server needs statistics to do its query optimizations the right way, so make sure that you do generate that.

Docker is in volume in use, but there aren't any Docker containers

Perhaps the volume was created via docker-compose? If so, it should get removed by:

docker-compose down --volumes

Credit to Niels Bech Nielsen!

How to pass values between Fragments

I think a good way to solve this problem is to use a custom interface.

Lets say you have two fragments (A and B) which are inside of the same activity and you want to send data from A to B.

Interface :

public interface OnDataSentListener{
    void onDataSent(Object data);
}

Activity:

    public class MyActivity extends AppCompatActivity{

            private OnDataSentListener onDataSentListener;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_activity);

                FragmentTransaction trans = getFragmentManager().beginTransaction();

                FragmentA fa = new FragmentA();
                FragmentB fb = new FragmentB();

               fa.setOnDataSentListener(new Listeners.OnDataSentListener() {
                    @Override
                    public void onDataSent(Object data) {
                         if(onDataSentListener != null)  onDataSentListener.onDataSent(data);
                    }
               });

                transaction.add(R.id.frame_a, fa);
                transaction.add(R.id.frame_b, fb);

                transaction.commit();
            }

            public void setOnDataSentListener(OnDataSentListener listener){
                this.onDataSentListener = listener;
            }
        }

Fragment A:

public class FragmentA extends Fragment{

    private OnDataSentListener onDataSentListener;

    private void sendDataToFragmentB(Object data){
        if(onDataSentListener != null) onDataSentListener.onDataSent(data);
    }

    public void setOnDataSentListener(OnDataSentListener listener){
        this.onDataSentListener = listener;
    }
}

Fragment B:

public class FragmentB extends Fragment{

    private void initReceiver(){
        ((MyActivity) getActivity()).setOnDataSentListener(new OnDataSentListener() {
            @Override
            public void onDataSent(Object data) {
                //Here you receive the data from fragment A
            }
        });
    }
}

What is the purpose of a question mark after a type (for example: int? myVariable)?

int? is shorthand for Nullable<int>. The two forms are interchangeable.

Nullable<T> is an operator that you can use with a value type T to make it accept null.

In case you don't know it: value types are types that accepts values as int, bool, char etc...

They can't accept references to values: they would generate a compile-time error if you assign them a null, as opposed to reference types, which can obviously accept it.

Why would you need that? Because sometimes your value type variables could receive null references returned by something that didn't work very well, like a missing or undefined variable returned from a database.

I suggest you to read the Microsoft Documentation because it covers the subject quite well.

R cannot be resolved - Android error

And another thing which may cause this problem:

I installed the new ADT (v. 22). It stopped creating gen folder which includes R.java. The solution was to also install new Android SDK Build Tools from Android SDK Manager.

Solution found here

How to change a string into uppercase

>>> s = 'sdsd'
>>> s.upper()
'SDSD'

See String Methods.

How to delete last character from a string using jQuery?

@skajfes and @GolezTrol provided the best methods to use. Personally, I prefer using "slice()". It's less code, and you don't have to know how long a string is. Just use:

//-----------------------------------------
// @param begin  Required. The index where 
//               to begin the extraction. 
//               1st character is at index 0
//
// @param end    Optional. Where to end the
//               extraction. If omitted, 
//               slice() selects all 
//               characters from the begin 
//               position to the end of 
//               the string.
var str = '123-4';
alert(str.slice(0, -1));

How to count the number of lines of a string in javascript

I was testing out the speed of the functions, and I found consistently that this solution that I had written was much faster than matching. We check the new length of the string as compared to the previous length.

const lines = str.length - str.replace(/\n/g, "").length+1;

_x000D_
_x000D_
let str = `Line1
Line2
Line3`;
console.time("LinesTimer")
console.log("Lines: ",str.length - str.replace(/\n/g, "").length+1);
console.timeEnd("LinesTimer")
_x000D_
_x000D_
_x000D_

How to get the path of src/test/resources directory in JUnit?

You don't need to mess with class loaders. In fact it's a bad habit to get into because class loader resources are not java.io.File objects when they are in a jar archive.

Maven automatically sets the current working directory before running tests, so you can just use:

    File resourcesDirectory = new File("src/test/resources");

resourcesDirectory.getAbsolutePath() will return the correct value if that is what you really need.

I recommend creating a src/test/data directory if you want your tests to access data via the file system. This makes it clear what you're doing.

Removing duplicate values from a PowerShell array

Another option is to use Sort-Object (whose alias is sort, but only on Windows) with the
-Unique switch, which combines sorting with removal of duplicates:

$a | sort -unique

Using C++ base class constructors?

You'll need to declare constructors in each of the derived classes, and then call the base class constructor from the initializer list:

class D : public A
{
public:
    D(const string &val) : A(0) {}
    D( int val ) : A( val ) {}
};

D variable1( "Hello" );
D variable2( 10 );

C++11 allows you to use the using A::A syntax you use in your decleration of D, but C++11 features aren't supported by all compilers just now, so best to stick with the older C++ methods until this feature is implemented in all the compilers your code will be used with.

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

I think the most important thing to keep in mind is: is the name descriptive enough? Can you tell by looking at the name what the Class is supposed to do? Using words like "Manager", "Service" or "Handler" in your class names can be considered too generic, but since a lot of programmers use them it also helps understanding what the class is for.

I myself have been using the facade-pattern a lot (at least, I think that's what it is called). I could have a User class that describes just one user, and a Users class that keeps track of my "collection of users". I don't call the class a UserManager because I don't like managers in real-life and I don't want to be reminded of them :) Simply using the plural form helps me understand what the class does.

vertical align middle in <div>

_x000D_
_x000D_
 div {_x000D_
    height:200px;_x000D_
    text-align: center;_x000D_
    padding: 2px;_x000D_
    border: 1px solid #000;_x000D_
    background-color: green;_x000D_
}_x000D_
_x000D_
.text-align-center {_x000D_
    display: flex;_x000D_
    align-items: center;_x000D_
    justify-content: center;_x000D_
}
_x000D_
<div class="text-align-center"> Align center</div>
_x000D_
_x000D_
_x000D_

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Scripts"

While working through the ASP.NET MVC 4 Tutorial with Visual Studio 2012 I encountered the same error in the "Accessing Your Model's Data from a Controller section". The fix is quite simple.

When creating a new ASP.NET MVC 4 Web Application in Visual Studio 2012 within the _Layout.cshtml document in the shared folder the "scripts" section is commented out.

    @*@RenderSection("scripts", required: false)*@

Simply un-comment the line and the sample code should work.

    @RenderSection("scripts", required: false)

What does the symbol \0 mean in a string-literal?

What is the length of str array, and with how much 0s it is ending?

Let's find out:

int main() {
  char str[] = "Hello\0";
  int length = sizeof str / sizeof str[0];
  // "sizeof array" is the bytes for the whole array (must use a real array, not
  // a pointer), divide by "sizeof array[0]" (sometimes sizeof *array is used)
  // to get the number of items in the array
  printf("array length: %d\n", length);
  printf("last 3 bytes: %02x %02x %02x\n",
         str[length - 3], str[length - 2], str[length - 1]);
  return 0;
}

Background thread with QThread in PyQt

In PyQt there are a lot of options for getting asynchronous behavior. For things that need event processing (ie. QtNetwork, etc) you should use the QThread example I provided in my other answer on this thread. But for the vast majority of your threading needs, I think this solution is far superior than the other methods.

The advantage of this is that the QThreadPool schedules your QRunnable instances as tasks. This is similar to the task pattern used in Intel's TBB. It's not quite as elegant as I like but it does pull off excellent asynchronous behavior.

This allows you to utilize most of the threading power of Qt in Python via QRunnable and still take advantage of signals and slots. I use this same code in several applications, some that make hundreds of asynchronous REST calls, some that open files or list directories, and the best part is using this method, Qt task balances the system resources for me.

import time
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4.QtCore import Qt


def async(method, args, uid, readycb, errorcb=None):
    """
    Asynchronously runs a task

    :param func method: the method to run in a thread
    :param object uid: a unique identifier for this task (used for verification)
    :param slot updatecb: the callback when data is receieved cb(uid, data)
    :param slot errorcb: the callback when there is an error cb(uid, errmsg)

    The uid option is useful when the calling code makes multiple async calls
    and the callbacks need some context about what was sent to the async method.
    For example, if you use this method to thread a long running database call
    and the user decides they want to cancel it and start a different one, the
    first one may complete before you have a chance to cancel the task.  In that
    case, the "readycb" will be called with the cancelled task's data.  The uid
    can be used to differentiate those two calls (ie. using the sql query).

    :returns: Request instance
    """
    request = Request(method, args, uid, readycb, errorcb)
    QtCore.QThreadPool.globalInstance().start(request)
    return request


class Request(QtCore.QRunnable):
    """
    A Qt object that represents an asynchronous task

    :param func method: the method to call
    :param list args: list of arguments to pass to method
    :param object uid: a unique identifier (used for verification)
    :param slot readycb: the callback used when data is receieved
    :param slot errorcb: the callback used when there is an error

    The uid param is sent to your error and update callbacks as the
    first argument. It's there to verify the data you're returning

    After created it should be used by invoking:

    .. code-block:: python

       task = Request(...)
       QtCore.QThreadPool.globalInstance().start(task)

    """
    INSTANCES = []
    FINISHED = []
    def __init__(self, method, args, uid, readycb, errorcb=None):
        super(Request, self).__init__()
        self.setAutoDelete(True)
        self.cancelled = False

        self.method = method
        self.args = args
        self.uid = uid
        self.dataReady = readycb
        self.dataError = errorcb

        Request.INSTANCES.append(self)

        # release all of the finished tasks
        Request.FINISHED = []

    def run(self):
        """
        Method automatically called by Qt when the runnable is ready to run.
        This will run in a separate thread.
        """
        # this allows us to "cancel" queued tasks if needed, should be done
        # on shutdown to prevent the app from hanging
        if self.cancelled:
            self.cleanup()
            return

        # runs in a separate thread, for proper async signal/slot behavior
        # the object that emits the signals must be created in this thread.
        # Its not possible to run grabber.moveToThread(QThread.currentThread())
        # so to get this QObject to properly exhibit asynchronous
        # signal and slot behavior it needs to live in the thread that
        # we're running in, creating the object from within this thread
        # is an easy way to do that.
        grabber = Requester()
        grabber.Loaded.connect(self.dataReady, Qt.QueuedConnection)
        if self.dataError is not None:
            grabber.Error.connect(self.dataError, Qt.QueuedConnection)

        try:
            result = self.method(*self.args)
            if self.cancelled:
                # cleanup happens in 'finally' statement
                return
            grabber.Loaded.emit(self.uid, result)
        except Exception as error:
            if self.cancelled:
                # cleanup happens in 'finally' statement
                return
            grabber.Error.emit(self.uid, unicode(error))
        finally:
            # this will run even if one of the above return statements
            # is executed inside of the try/except statement see:
            # https://docs.python.org/2.7/tutorial/errors.html#defining-clean-up-actions
            self.cleanup(grabber)

    def cleanup(self, grabber=None):
        # remove references to any object or method for proper ref counting
        self.method = None
        self.args = None
        self.uid = None
        self.dataReady = None
        self.dataError = None

        if grabber is not None:
            grabber.deleteLater()

        # make sure this python obj gets cleaned up
        self.remove()

    def remove(self):
        try:
            Request.INSTANCES.remove(self)

            # when the next request is created, it will clean this one up
            # this will help us avoid this object being cleaned up
            # when it's still being used
            Request.FINISHED.append(self)
        except ValueError:
            # there might be a race condition on shutdown, when shutdown()
            # is called while the thread is still running and the instance
            # has already been removed from the list
            return

    @staticmethod
    def shutdown():
        for inst in Request.INSTANCES:
            inst.cancelled = True
        Request.INSTANCES = []
        Request.FINISHED = []


class Requester(QtCore.QObject):
    """
    A simple object designed to be used in a separate thread to allow
    for asynchronous data fetching
    """

    #
    # Signals
    #

    Error = QtCore.pyqtSignal(object, unicode)
    """
    Emitted if the fetch fails for any reason

    :param unicode uid: an id to identify this request
    :param unicode error: the error message
    """

    Loaded = QtCore.pyqtSignal(object, object)
    """
    Emitted whenever data comes back successfully

    :param unicode uid: an id to identify this request
    :param list data: the json list returned from the GET
    """

    NetworkConnectionError = QtCore.pyqtSignal(unicode)
    """
    Emitted when the task fails due to a network connection error

    :param unicode message: network connection error message
    """

    def __init__(self, parent=None):
        super(Requester, self).__init__(parent)


class ExampleObject(QtCore.QObject):
    def __init__(self, parent=None):
        super(ExampleObject, self).__init__(parent)
        self.uid = 0
        self.request = None

    def ready_callback(self, uid, result):
        if uid != self.uid:
            return
        print "Data ready from %s: %s" % (uid, result)

    def error_callback(self, uid, error):
        if uid != self.uid:
            return
        print "Data error from %s: %s" % (uid, error)

    def fetch(self):
        if self.request is not None:
            # cancel any pending requests
            self.request.cancelled = True
            self.request = None

        self.uid += 1
        self.request = async(slow_method, ["arg1", "arg2"], self.uid,
                             self.ready_callback,
                             self.error_callback)


def slow_method(arg1, arg2):
    print "Starting slow method"
    time.sleep(1)
    return arg1 + arg2


if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)

    obj = ExampleObject()

    dialog = QtGui.QDialog()
    layout = QtGui.QVBoxLayout(dialog)
    button = QtGui.QPushButton("Generate", dialog)
    progress = QtGui.QProgressBar(dialog)
    progress.setRange(0, 0)
    layout.addWidget(button)
    layout.addWidget(progress)
    button.clicked.connect(obj.fetch)
    dialog.show()

    app.exec_()
    app.deleteLater() # avoids some QThread messages in the shell on exit
    # cancel all running tasks avoid QThread/QTimer error messages
    # on exit
    Request.shutdown()

When exiting the application you'll want to make sure you cancel all of the tasks or the application will hang until every scheduled task has completed

How can I find whitespace in a String?

You could use Regex to determine if there's a whitespace character. \s.

More info of regex here.

Uncaught syntaxerror: unexpected identifier?

There are errors here :

var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");

The code must change to:

var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");

By the way, there is another error at line 129 :

var createLi.appendChild(createSubList);

Replace it with:

createLi.appendChild(createSubList);

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

Why are only a few video games written in Java?

It was talked about it a lot already, u can find even on Wiki the reasons...

  • C/C++ for the game engine and all intensive stuff.
  • Lua or Python for scripting in the game.
  • Java - very-very bad performance, big memory usage + it's not available on Game Consoles(It is used for some very simple games(Yes, Runescape counts in here, it's not Battlefield or Crysis or what else is there) just because there are a lot of programmers that know this programming language).
  • C# - big memory usage(It is used for some very simple games just because there are pretty much programmers that know this programming language).

And I hear more and more Java programmers that try to convince people that Java is not slow, it is not slow for drawing a widget on the screen and drawing some ASCII characters on the widget, to receive and send data through network(And it is recommended to use it in this cases(network data manipulation) instead of C/C++)... But it is damn slow when it comes to serious stuff like math calculations, memory allocation/manipulation and a lot of this good stuff.

I remember an article on MIT site where they show what C/C++ can do if u use the language and compiler features: A matrix multiplier(2 matrices), 1 implementation in Java and 1 implementation in C/C++, with C/C++ features and appropriate compiler optimisations activated, the C/C++ implementation was ~296 260 times faster than the Java implementation.

I hope you understand now why people use C/C++ instead of Java in games, imagine Crysis in Java, there would not be any computer in this world which could handle that... + Garbage collection works ok for Widgets which just destroyed an image but it's still cached in there and needs to be cleaned but not for games, for sure, u will have even more lags on every garbage collection activation.

Edit: Because somebody asked for the article, here, I searched in the web archive to get that, I hope you are satisfied...MIT Case Study

And to add, no, Java for gaming is still an awful idea. Just a few days ago a big company that I will not name started rewriting their game client from Java to C++ because a very simple game(In terms of Graphics) was lagging and heating i7 Laptops with powerful nVidia GT 5xx and 6xx generation video cards(not only nVidia, the point here is that this powerful cards that can handle on Max settings most of the new games and can't handle this game) and the memory consumption was ~2.5 - 2.6 GB Ram. For such simple graphics it needs a beast of a machine.

count of entries in data frame in R

You could use table:

R> x <- read.table(textConnection('
   Believe Age Gender Presents Behaviour
1    FALSE   9   male       25   naughty
2     TRUE   5   male       20      nice
3     TRUE   4 female       30      nice
4     TRUE   4   male       34   naughty'
), header=TRUE)

R> table(x$Believe)

FALSE  TRUE 
    1     3 

Can I use if (pointer) instead of if (pointer != NULL)?

The relevant use cases for null pointers are

  • Redirection to something like a deeper tree node, which may not exist or has not been linked yet. That's something you should always keep closely encapsulated in a dedicated class, so readability or conciseness isn't that much of an issue here.
  • Dynamic casts. Casting a base-class pointer to a particular derived-class one (something you should again try to avoid, but may at times find necessary) always succeeds, but results in a null pointer if the derived class doesn't match. One way to check this is

    Derived* derived_ptr = dynamic_cast<Derived*>(base_ptr);
    if(derived_ptr != nullptr) { ... }
    

    (or, preferrably, auto derived_ptr = ...). Now, this is bad, because it leaves the (possibly invalid, i.e. null) derived pointer outside of the safety-guarding if block's scope. This isn't necessary, as C++ allows you to introduce boolean-convertable variables inside an if-condition:

    if(auto derived_ptr = dynamic_cast<Derived*>(base_ptr)) { ... }
    

    which is not only shorter and scope-safe, it's also much more clear in its intend: when you check for null in a separate if-condition, the reader wonders "ok, so derived_ptr must not be null here... well, why would it be null?" Whereas the one-line version says very plainly "if you can safely cast base_ptr to Derived*, then use it for...".

    The same works just as well for any other possible-failure operation that returns a pointer, though IMO you should generally avoid this: it's better to use something like boost::optional as the "container" for results of possibly failing operations, rather than pointers.

So, if the main use case for null pointers should always be written in a variation of the implicit-cast-style, I'd say it's good for consistency reasons to always use this style, i.e. I'd advocate for if(ptr) over if(ptr!=nullptr).


I'm afraid I have to end with an advert: the if(auto bla = ...) syntax is actually just a slightly cumbersome approximation to the real solution to such problems: pattern matching. Why would you first force some action (like casting a pointer) and then consider that there might be a failure... I mean, it's ridiculous, isn't it? It's like, you have some foodstuff and want to make soup. You hand it to your assistant with the task to extract the juice, if it happens to be a soft vegetable. You don't first look it at it. When you have a potato, you still give it to your assistant but they slap it back in your face with a failure note. Ah, imperative programming!

Much better: consider right away all the cases you might encounter. Then act accordingly. Haskell:

makeSoupOf :: Foodstuff -> Liquid
makeSoupOf p@(Potato{..}) = mash (boil p) <> water
makeSoupOf vegetable
 | isSoft vegetable  = squeeze vegetable <> salt
makeSoupOf stuff  = boil (throwIn (water<>salt) stuff)

Haskell also has special tools for when there is really a serious possibility of failure (as well as for a whole bunch of other stuff): monads. But this isn't the place for explaining those.

⟨/advert⟩

C compiling - "undefined reference to"?

Make sure your declare the tolayer5 function as a prototype, or define the full function definition, earlier in the file where you use it.

Regex Named Groups in Java

(Update: August 2011)

As geofflane mentions in his answer, Java 7 now support named groups.
tchrist points out in the comment that the support is limited.
He details the limitations in his great answer "Java Regex Helper"

Java 7 regex named group support was presented back in September 2010 in Oracle's blog.

In the official release of Java 7, the constructs to support the named capturing group are:

  • (?<name>capturing text) to define a named group "name"
  • \k<name> to backreference a named group "name"
  • ${name} to reference to captured group in Matcher's replacement string
  • Matcher.group(String name) to return the captured input subsequence by the given "named group".

Other alternatives for pre-Java 7 were:


(Original answer: Jan 2009, with the next two links now broken)

You can not refer to named group, unless you code your own version of Regex...

That is precisely what Gorbush2 did in this thread.

Regex2

(limited implementation, as pointed out again by tchrist, as it looks only for ASCII identifiers. tchrist details the limitation as:

only being able to have one named group per same name (which you don’t always have control over!) and not being able to use them for in-regex recursion.

Note: You can find true regex recursion examples in Perl and PCRE regexes, as mentioned in Regexp Power, PCRE specs and Matching Strings with Balanced Parentheses slide)

Example:

String:

"TEST 123"

RegExp:

"(?<login>\\w+) (?<id>\\d+)"

Access

matcher.group(1) ==> TEST
matcher.group("login") ==> TEST
matcher.name(1) ==> login

Replace

matcher.replaceAll("aaaaa_$1_sssss_$2____") ==> aaaaa_TEST_sssss_123____
matcher.replaceAll("aaaaa_${login}_sssss_${id}____") ==> aaaaa_TEST_sssss_123____ 

(extract from the implementation)

public final class Pattern
    implements java.io.Serializable
{
[...]
    /**
     * Parses a group and returns the head node of a set of nodes that process
     * the group. Sometimes a double return system is used where the tail is
     * returned in root.
     */
    private Node group0() {
        boolean capturingGroup = false;
        Node head = null;
        Node tail = null;
        int save = flags;
        root = null;
        int ch = next();
        if (ch == '?') {
            ch = skip();
            switch (ch) {

            case '<':   // (?<xxx)  look behind or group name
                ch = read();
                int start = cursor;
[...]
                // test forGroupName
                int startChar = ch;
                while(ASCII.isWord(ch) && ch != '>') ch=read();
                if(ch == '>'){
                    // valid group name
                    int len = cursor-start;
                    int[] newtemp = new int[2*(len) + 2];
                    //System.arraycopy(temp, start, newtemp, 0, len);
                    StringBuilder name = new StringBuilder();
                    for(int i = start; i< cursor; i++){
                        name.append((char)temp[i-1]);
                    }
                    // create Named group
                    head = createGroup(false);
                    ((GroupTail)root).name = name.toString();

                    capturingGroup = true;
                    tail = root;
                    head.next = expr(tail);
                    break;
                }

Git diff --name-only and copy that list

The following should work fine:

git diff -z --name-only commit1 commit2 | xargs -0 -IREPLACE rsync -aR REPLACE /home/changes/protected/

To explain further:

  • The -z to with git diff --name-only means to output the list of files separated with NUL bytes instead of newlines, just in case your filenames have unusual characters in them.

  • The -0 to xargs says to interpret standard input as a NUL-separated list of parameters.

  • The -IREPLACE is needed since by default xargs would append the parameters to the end of the rsync command. Instead, that says to put them where the later REPLACE is. (That's a nice tip from this Server Fault answer.)

  • The -a parameter to rsync means to preserve permissions, ownership, etc. if possible. The -R means to use the full relative path when creating the files in the destination.

Update: if you have an old version of xargs, you'll need to use the -i option instead of -I. (The former is deprecated in later versions of findutils.)

Column standard deviation R

The general idea is to sweep the function across. You have many options, one is apply():

R> set.seed(42)
R> M <- matrix(rnorm(40),ncol=4)
R> apply(M, 2, sd)
[1] 0.835449 1.630584 1.156058 1.115269
R> 

Print a list of all installed node.js modules

Use npm ls (there is even json output)

From the script:

test.js:

function npmls(cb) {
  require('child_process').exec('npm ls --json', function(err, stdout, stderr) {
    if (err) return cb(err)
    cb(null, JSON.parse(stdout));
  });
}
npmls(console.log);

run:

> node test.js
null { name: 'x11', version: '0.0.11' }

How to return a resolved promise from an AngularJS Service using $q?

Return your promise , return deferred.promise.
It is the promise API that has the 'then' method.

https://docs.angularjs.org/api/ng/service/$q

Calling resolve does not return a promise it only signals the promise that the promise is resolved so it can execute the 'then' logic.

Basic pattern as follows, rinse and repeat
http://plnkr.co/edit/fJmmEP5xOrEMfLvLWy1h?p=preview

<!DOCTYPE html>
<html>

<head>
  <script data-require="angular.js@*" data-semver="1.3.0-beta.5" 
        src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>

<div ng-controller="test">
  <button ng-click="test()">test</button>
</div>
<script>
  var app = angular.module("app",[]);

  app.controller("test",function($scope,$q){

    $scope.$test = function(){
      var deferred = $q.defer();
      deferred.resolve("Hi");
      return deferred.promise;
    };

    $scope.test=function(){
      $scope.$test()
      .then(function(data){
        console.log(data);
      });
    }      
  });

  angular.bootstrap(document,["app"]);

</script>

Oracle SQL Query for listing all Schemas in a DB

Most likely, you want

SELECT username
  FROM dba_users

That will show you all the users in the system (and thus all the potential schemas). If your definition of "schema" allows for a schema to be empty, that's what you want. However, there can be a semantic distinction where people only want to call something a schema if it actually owns at least one object so that the hundreds of user accounts that will never own any objects are excluded. In that case

SELECT username
  FROM dba_users u
 WHERE EXISTS (
    SELECT 1
      FROM dba_objects o
     WHERE o.owner = u.username )

Assuming that whoever created the schemas was sensible about assigning default tablespaces and assuming that you are not interested in schemas that Oracle has delivered, you can filter out those schemas by adding predicates on the default_tablespace, i.e.

SELECT username
  FROM dba_users
 WHERE default_tablespace not in ('SYSTEM','SYSAUX')

or

SELECT username
  FROM dba_users u
 WHERE EXISTS (
    SELECT 1
      FROM dba_objects o
     WHERE o.owner = u.username )
   AND default_tablespace not in ('SYSTEM','SYSAUX')

It is not terribly uncommon to come across a system where someone has incorrectly given a non-system user a default_tablespace of SYSTEM, though, so be certain that the assumptions hold before trying to filter out the Oracle-delivered schemas this way.

How to install Jdk in centos

I advise you to use the same JDK as you may use with Windows: the Oracle one.

http://www.oracle.com/technetwork/java/javase/downloads/index.html
Go to the Java SE 7u67 section and click on JDK7 Download button on the right.

On the new page select the option "(¤) Accept License Agreement"
Then click on jdk-7u67-linux-x64.rpm

On your CentOS, as root, run:

$ rpm -Uvh jdk-7u67-linux-x64.rpm
$ alternatives --install /usr/bin/java java /usr/java/latest/bin/java 2

You may already have a Java 5 installed on your box... before installing the downloaded rpm remove previous Java by running this command yum remove java

How to retrieve data from sqlite database in android and display it in TextView

First cast your Edit text like this:

TextView tekst = (TextView) findViewById(R.id.editText1);
tekst.setText(text);

And after that close the DB not befor this line...

 myDataBaseHelper.close(); 

Let JSON object accept bytes or let urlopen output strings

This one works for me, I used 'request' library with json() check out the doc in requests for humans

import requests

url = 'here goes your url'

obj = requests.get(url).json() 

How to use UTF-8 in resource properties with ResourceBundle

package com.varaneckas.utils;  

import java.io.UnsupportedEncodingException;  
import java.util.Enumeration;  
import java.util.PropertyResourceBundle;  
import java.util.ResourceBundle;  

/** 
 * UTF-8 friendly ResourceBundle support 
 *  
 * Utility that allows having multi-byte characters inside java .property files. 
 * It removes the need for Sun's native2ascii application, you can simply have 
 * UTF-8 encoded editable .property files. 
 *  
 * Use:  
 * ResourceBundle bundle = Utf8ResourceBundle.getBundle("bundle_name"); 
 *  
 * @author Tomas Varaneckas <[email protected]> 
 */  
public abstract class Utf8ResourceBundle {  

    /** 
     * Gets the unicode friendly resource bundle 
     *  
     * @param baseName 
     * @see ResourceBundle#getBundle(String) 
     * @return Unicode friendly resource bundle 
     */  
    public static final ResourceBundle getBundle(final String baseName) {  
        return createUtf8PropertyResourceBundle(  
                ResourceBundle.getBundle(baseName));  
    }  

    /** 
     * Creates unicode friendly {@link PropertyResourceBundle} if possible. 
     *  
     * @param bundle  
     * @return Unicode friendly property resource bundle 
     */  
    private static ResourceBundle createUtf8PropertyResourceBundle(  
            final ResourceBundle bundle) {  
        if (!(bundle instanceof PropertyResourceBundle)) {  
            return bundle;  
        }  
        return new Utf8PropertyResourceBundle((PropertyResourceBundle) bundle);  
    }  

    /** 
     * Resource Bundle that does the hard work 
     */  
    private static class Utf8PropertyResourceBundle extends ResourceBundle {  

        /** 
         * Bundle with unicode data 
         */  
        private final PropertyResourceBundle bundle;  

        /** 
         * Initializing constructor 
         *  
         * @param bundle 
         */  
        private Utf8PropertyResourceBundle(final PropertyResourceBundle bundle) {  
            this.bundle = bundle;  
        }  

        @Override  
        @SuppressWarnings("unchecked")  
        public Enumeration getKeys() {  
            return bundle.getKeys();  
        }  

        @Override  
        protected Object handleGetObject(final String key) {  
            final String value = bundle.getString(key);  
            if (value == null)  
                return null;  
            try {  
                return new String(value.getBytes("ISO-8859-1"), "UTF-8");  
            } catch (final UnsupportedEncodingException e) {  
                throw new RuntimeException("Encoding not supported", e);  
            }  
        }  
    }  
}  

Simple CSS: Text won't center in a button

padding: 0px solves the horizontal centering

whereas,

setting line-height equal to or less than the height of the button solves the vertical alignment.

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

^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,7}$

[domain - lower case letters and 0-9 only] [can have a hyphen] + [TLD - lower case only, must be beween 2 and 7 letters long]
http://rubular.com/ is brilliant for testing regular expressions!
Edit: Updated TLD maximum to 7 characters for '.rentals' as Dan Caddigan pointed out.

Is there an operator to calculate percentage in Python?

Brian's answer (a custom function) is the correct and simplest thing to do in general.

But if you really wanted to define a numeric type with a (non-standard) '%' operator, like desk calculators do, so that 'X % Y' means X * Y / 100.0, then from Python 2.6 onwards you can redefine the mod() operator:

import numbers

class MyNumberClasswithPct(numbers.Real):
    def __mod__(self,other):
        """Override the builtin % to give X * Y / 100.0 """
        return (self * other)/ 100.0
    # Gotta define the other 21 numeric methods...
    def __mul__(self,other):
        return self * other # ... which should invoke other.__rmul__(self)
    #...

This could be dangerous if you ever use the '%' operator across a mixture of MyNumberClasswithPct with ordinary integers or floats.

What's also tedious about this code is you also have to define all the 21 other methods of an Integral or Real, to avoid the following annoying and obscure TypeError when you instantiate it

("Can't instantiate abstract class MyNumberClasswithPct with abstract methods __abs__,  __add__, __div__, __eq__, __float__, __floordiv__, __le__, __lt__, __mul__,  __neg__, __pos__, __pow__, __radd__, __rdiv__, __rfloordiv__, __rmod__, __rmul__,  __rpow__, __rtruediv__, __truediv__, __trunc__")

Convert String to Integer in XSLT 1.0

Adding to jelovirt's answer, you can use number() to convert the value to a number, then round(), floor(), or ceiling() to get a whole integer.

Example

<xsl:variable name="MyValAsText" select="'5.14'"/>
<xsl:value-of select="number($MyValAsText) * 2"/> <!-- This outputs 10.28 -->
<xsl:value-of select="floor($MyValAsText)"/> <!-- outputs 5 -->
<xsl:value-of select="ceiling($MyValAsText)"/> <!-- outputs 6 -->
<xsl:value-of select="round($MyValAsText)"/> <!-- outputs 5 -->

java collections - keyset() vs entrySet() in map

To make things simple , please note that every time you do itr2.next() the pointer moves to the next element i.e. here if you notice carefully, then the output is perfectly fine according to the logic you have written .
This may help you in understanding better:

1st Iteration of While loop(pointer is before the 1st element):
Key: if ,value: 2 {itr2.next()=if; m.get(itr2.next()=it)=>2}

2nd Iteration of While loop(pointer is before the 3rd element):
Key: is ,value: 2 {itr2.next()=is; m.get(itr2.next()=to)=>2}

3rd Iteration of While loop(pointer is before the 5th element):
Key: be ,value: 1 {itr2.next()="be"; m.get(itr2.next()="up")=>"1"}

4th Iteration of While loop(pointer is before the 7th element):
Key: me ,value: 1 {itr2.next()="me"; m.get(itr2.next()="delegate")=>"1"}

Key: if ,value: 1
Key: it ,value: 2
Key: is ,value: 2
Key: to ,value: 2
Key: be ,value: 1
Key: up ,value: 1
Key: me ,value: 1
Key: delegate ,value: 1

It prints:

Key: if ,value: 2
Key: is ,value: 2
Key: be ,value: 1
Key: me ,value: 1

Why is "except: pass" a bad programming practice?

Why is “except: pass” a bad programming practice?

Why is this bad?

try:
    something
except:
    pass

This catches every possible exception, including GeneratorExit, KeyboardInterrupt, and SystemExit - which are exceptions you probably don't intend to catch. It's the same as catching BaseException.

try:
    something
except BaseException:
    pass

Older versions of the documentation say:

Since every error in Python raises an exception, using except: can make many programming errors look like runtime problems, which hinders the debugging process.

Python Exception Hierarchy

If you catch a parent exception class, you also catch all of their child classes. It is much more elegant to only catch the exceptions you are prepared to handle.

Here's the Python 3 exception hierarchy - do you really want to catch 'em all?:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
           +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

Don't Do this

If you're using this form of exception handling:

try:
    something
except: # don't just do a bare except!
    pass

Then you won't be able to interrupt your something block with Ctrl-C. Your program will overlook every possible Exception inside the try code block.

Here's another example that will have the same undesirable behavior:

except BaseException as e: # don't do this either - same as bare!
    logging.info(e)

Instead, try to only catch the specific exception you know you're looking for. For example, if you know you might get a value-error on a conversion:

try:
    foo = operation_that_includes_int(foo)
except ValueError as e:
    if fatal_condition(): # You can raise the exception if it's bad,
        logging.info(e)   # but if it's fatal every time,
        raise             # you probably should just not catch it.
    else:                 # Only catch exceptions you are prepared to handle.
        foo = 0           # Here we simply assign foo to 0 and continue. 

Further Explanation with another example

You might be doing it because you've been web-scraping and been getting say, a UnicodeError, but because you've used the broadest Exception catching, your code, which may have other fundamental flaws, will attempt to run to completion, wasting bandwidth, processing time, wear and tear on your equipment, running out of memory, collecting garbage data, etc.

If other people are asking you to complete so that they can rely on your code, I understand feeling compelled to just handle everything. But if you're willing to fail noisily as you develop, you will have the opportunity to correct problems that might only pop up intermittently, but that would be long term costly bugs.

With more precise error handling, you code can be more robust.

How to create and handle composite primary key in JPA

The MyKey class (@Embeddable) should not have any relationships like @ManyToOne

What is an efficient way to implement a singleton pattern in Java?

If you do not need lazy loading then simply try:

public class Singleton {
    private final static Singleton INSTANCE = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() { return Singleton.INSTANCE; }

    protected Object clone() {
        throw new CloneNotSupportedException();
    }
}

If you want lazy loading and you want your singleton to be thread-safe, try the double-checking pattern:

public class Singleton {
    private static Singleton instance = null;

    private Singleton() {}

    public static Singleton getInstance() {
        if(null == instance) {
            synchronized(Singleton.class) {
                if(null == instance) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    protected Object clone() {
        throw new CloneNotSupportedException();
    }
}

As the double checking pattern is not guaranteed to work (due to some issue with compilers, I don't know anything more about that), you could also try to synchronize the whole getInstance-method or create a registry for all your singletons.

How to getElementByClass instead of GetElementById with JavaScript?

Append IDs at the class declaration

.aclass, #hashone, #hashtwo{ ...codes... }
document.getElementById( "hashone" ).style.visibility = "hidden";

Saving data to a file in C#

Here's an article from MSDN on a guide for how to write text to a file:

http://msdn.microsoft.com/en-us/library/8bh11f1k.aspx

I'd start there, then post additional, more specific questions as you continue your development.

Escape curly brace '{' in String.Format

Use double braces {{ or }} so your code becomes:

sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}", 
prop.Type, prop.Name));

// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }

Java - Relative path of a file in a java web application

You may be able to simply access a pre-arranged file path on the system. This is preferable since files added to the webapp directory might be lost or the webapp may not be unpacked depending on system configuration.

In our server, we define a system property set in the App Server's JVM which points to the "home directory" for our app's external data. Of course this requires modification of the App Server's configuration (-DAPP_HOME=... added to JVM_OPTS at startup), we do it mainly to ease testing of code run outside the context of an App Server.

You could just as easily retrieve a path from the servlet config:

<web-app>
<context-param>
    <param-name>MyAppHome</param-name>
    <param-value>/usr/share/myapp</param-value>
</context-param>
...
</web-app>

Then retrieve this path and use it as the base path to read the file supplied by the client.

public class MyAppConfig implements ServletContextListener {

    // NOTE: static references are not a great idea, shown here for simplicity
    static File appHome;
    static File customerDataFile;

    public void contextInitialized(ServletContextEvent e) {

        appHome = new File(e.getServletContext().getInitParameter("MyAppHome"));
        File customerDataFile = new File(appHome, "SuppliedFile.csv");
    }
}

class DataProcessor {
    public void processData() {
        File dataFile = MyAppConfig.customerDataFile;
        // ...
    }
}

As I mentioned the most likely problem you'll encounter is security restrictions. Nothing guarantees webapps can ready any files above their webapp root. But there are generally simple methods for granting exceptions for specific paths to specific webapps.

Regardless of the code in which you then need to access this file, since you are running within a web application you are guaranteed this is initialized first, and can stash it's value somewhere convenient for the rest of your code to refer to, as in my example or better yet, just simply pass the path as a paramete to the code which needs it.

Python interpreter error, x takes no arguments (1 given)

Your updateVelocity() method is missing the explicit self parameter in its definition.

Should be something like this:

def updateVelocity(self):    
    for x in range(0,len(self.velocity)):
        self.velocity[x] = 2*random.random()*(self.pbestx[x]-self.current[x]) + 2 \
          * random.random()*(self.gbest[x]-self.current[x])

Your other methods (except for __init__) have the same problem.

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I think there is MID() and maybe LEFT() and RIGHT() in Access.

Split string and get first value only

These are the two options I managed to build, not having the luxury of working with var type, nor with additional variables on the line:

string f = "aS.".Substring(0, "aS.".IndexOf("S"));
Console.WriteLine(f);

string s = "aS.".Split("S".ToCharArray(),StringSplitOptions.RemoveEmptyEntries)[0];
Console.WriteLine(s);

This is what it gets:

enter image description here

How do I find a particular value in an array and return its index?

the fancy answer. Use std::vector and search with std::find

the simple answer

use a for loop

How do I set a ViewModel on a window in XAML using DataContext property?

You might want to try Catel. It allows you to define a DataWindow class (instead of Window), and that class automatically creates the view model for you. This way, you can use the declaration of the ViewModel as you did in your original post, and the view model will still be created and set as DataContext.

See this article for an example.

Can I add an image to an ASP.NET button?

I dont know if I quite get what the issue is. You can add an image into the ASP button but it depends how its set up as to whether it fits in properly. putting in a background images to asp buttons regularly gives you a dodgy shaped button or a background image with a text overlay because its missing an image tag. such as the image with "SUBMIT QUERY" over the top of it.

As an easy way of doing it I use a "blankspace.gif" file across my website. its a 1x1 pixel blank gif file and I resize it to replace an image on the website.

as I dont use CSS to replace an image I use CSS Sprites to reduce queries. My website was originally 150kb for the homepage and had about 140-150 requests to load the home page. By creating a sprite I killed off the requests compressed the image size to a fraction of the size and it works perfect and any of the areas you need an image file to size it up properly just use the same blankspace.gif image.

<asp:ImageButton class="signup" ID="btn_newsletter" ImageUrl="~/xx/xx/blankspace.gif" Width="87px" Height="28px" runat="server" /

If you see the above the class loads the background image in the css but this leaves the button with the "submit Query" text over it as it needs an image so replacing it with a preloaded image means you got rid of the request and still have the image in the css.

Done.

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

SQLException : String or binary data would be truncated

With Linq To SQL I debugged by logging the context, eg. Context.Log = Console.Out Then scanned the SQL to check for any obvious errors, there were two:

-- @p46: Input Char (Size = -1; Prec = 0; Scale = 0) [some long text value1]
-- @p8: Input Char (Size = -1; Prec = 0; Scale = 0) [some long text value2]

the last one I found by scanning the table schema against the values, the field was nvarchar(20) but the value was 22 chars

-- @p41: Input NVarChar (Size = 4000; Prec = 0; Scale = 0) [1234567890123456789012]

What's the difference between VARCHAR and CHAR?

What's the difference between VARCHAR and CHAR in MySQL?

To already given answers I would like to add that in OLTP systems or in systems with frequent updates consider using CHAR even for variable size columns because of possible VARCHAR column fragmentation during updates.

I am trying to store MD5 hashes.

MD5 hash is not the best choice if security really matters. However, if you will use any hash function, consider BINARY type for it instead (e.g. MD5 will produce 16-byte hash, so BINARY(16) would be enough instead of CHAR(32) for 32 characters representing hex digits. This would save more space and be performance effective.

How to replace � in a string

dissect the URL code and unicode error. this symbol came to me as well on google translate in the armenian text and sometimes the broken burmese.

How do I dynamically set HTML5 data- attributes using react?

Note - if you want to pass a data attribute to a React Component, you need to handle them a little differently than other props.

2 options

Don't use camel case

<Option data-img-src='value' ... />

And then in the component, because of the dashes, you need to refer to the prop in quotes.

// @flow
class Option extends React.Component {

  props: {
    'data-img-src': string
  }

And when you refer to it later, you don't use the dot syntax

  render () {
    return (
      <option data-img-src={this.props['data-img-src']} >...</option>
    )
  }
}

Or use camel case

<Option dataImgSrc='value' ... />

And then in the component, you need to convert.

// @flow
class Option extends React.Component {

  props: {
    dataImgSrc: string
  }

And when you refer to it later, you don't use the dot syntax

  render () {
    return (
      <option data-img-src={this.props.dataImgSrc} >...</option>
    )
  }
}

Mainly just realize data- attributes and aria- attributes are treated specially. You are allowed to use hyphens in the attribute name in those two cases.

Mocking Extension Methods with Moq

I like to use the wrapper (adapter pattern) when I am wrapping the object itself. I'm not sure I'd use that for wrapping an extension method, which is not part of the object.

I use an internal Lazy Injectable Property of either type Action, Func, Predicate, or delegate and allow for injecting (swapping out) the method during a unit test.

    internal Func<IMyObject, string, object> DoWorkMethod
    {
        [ExcludeFromCodeCoverage]
        get { return _DoWorkMethod ?? (_DoWorkMethod = (obj, val) => { return obj.DoWork(val); }); }
        set { _DoWorkMethod = value; }
    } private Func<IMyObject, string, object> _DoWorkMethod;

Then you call the Func instead of the actual method.

    public object SomeFunction()
    {
        var val = "doesn't matter for this example";
        return DoWorkMethod.Invoke(MyObjectProperty, val);
    }

For a more complete example, check out http://www.rhyous.com/2016/08/11/unit-testing-calls-to-complex-extension-methods/

How to write loop in a Makefile?

You can use set -e as a prefix for the for-loop. Example:

all:
    set -e; for a in 1 2 3; do /bin/false; echo $$a; done

make will exit immediately with an exit code <> 0.

How to place a JButton at a desired location in a JFrame using Java

Define somewhere the consts :

private static final int BUTTON_LOCATION_X = 300;  // location x 
private static final int BUTTON_LOCATION_Y = 50;   // location y 
private static final int BUTTON_SIZE_X = 140;      // size height
private static final int BUTTON_SIZE_Y = 50;       // size width

and then below :

                JButton startButton = new JButton("Click Me To Start!");
                // startButton.setBounds(300, 50,140, 50 );
                startButton.setBounds(BUTTON_LOCATION_X
                                    , BUTTON_LOCATION_Y,
                                      BUTTON_SIZE_X, 
                                      BUTTON_SIZE_Y );
                contentPane.add(startButton);

where contentPane is the Container object that holds the entire frame :

 JFrame frame = new JFrame("Some name goes here");
 Container contentPane = frame.getContentPane();

I hope this helps , works great for me ...

Remove a git commit which has not been pushed

Actually, when you use git reset, you should refer to the commit that you are resetting to; so you would want the db0c078 commit, probably.

An easier version would be git reset --hard HEAD^, to reset to the previous commit before the current head; that way you don't have to be copying around commit IDs.

Beware when you do any git reset --hard, as you can lose any uncommitted changes you have. You might want to check git status to make sure your working copy is clean, or that you do want to blow away any changes that are there.

In addition, instead of HEAD you can use origin/master as reference, as suggested by @bdonlan in the comments: git reset --hard origin/master

Error:Execution failed for task ':app:dexDebug'. com.android.ide.common.process.ProcessException

I changed :

compile 'com.google.android.gms:play-services:9.0.0'

compile 'com.google.android.gms:play-services-auth:9.0.0'

to :

compile 'com.google.android.gms:play-services-maps:9.0.0'

compile 'com.google.android.gms:play-services-auth:9.0.0'

How to declare a local variable in Razor?

I think the variable should be in the same block:

@{bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);
    if (isUserConnected)
    { // meaning that the viewing user has not been saved
        <div>
            <div> click to join us </div>
            <a id="login" href="javascript:void(0);" style="display: inline; ">join</a>
        </div>
    }
    }

How do I prevent site scraping?

I have done a lot of web scraping and summarized some techniques to stop web scrapers on my blog based on what I find annoying.

It is a tradeoff between your users and scrapers. If you limit IP's, use CAPTCHA's, require login, etc, you make like difficult for the scrapers. But this may also drive away your genuine users.

Kotlin Ternary Conditional Operator

fun max(x:Int,y:Int) : String = if (x>y) "max = $x" else "max = $y"

inline funcation

COUNT DISTINCT with CONDITIONS

This may also work:

SELECT 
    COUNT(DISTINCT T.tag) as DistinctTag,
    COUNT(DISTINCT T2.tag) as DistinctPositiveTag
FROM Table T
    LEFT JOIN Table T2 ON T.tag = T2.tag AND T.entryID = T2.entryID AND T2.entryID > 0

You need the entryID condition in the left join rather than in a where clause in order to make sure that any items that only have a entryID of 0 get properly counted in the first DISTINCT.

Encode/Decode URLs in C++

cpp-netlib has functions

namespace boost {
  namespace network {
    namespace uri {    
      inline std::string decoded(const std::string &input);
      inline std::string encoded(const std::string &input);
    }
  }
}

they allow to encode and decode URL strings very easy.

How to make Scrollable Table with fixed headers using CSS

I can think of a cheeky way to do it, I don't think this will be the best option but it will work.

Create the header as a separate table then place the other in a div and set a max size, then allow the scroll to come in by using overflow.

_x000D_
_x000D_
table {_x000D_
  width: 500px;_x000D_
}_x000D_
_x000D_
.scroll {_x000D_
  max-height: 60px;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<table border="1">_x000D_
  <tr>_x000D_
  <th>head1</th>_x000D_
  <th>head2</th>_x000D_
  <th>head3</th>_x000D_
  <th>head4</th>_x000D_
  </tr>_x000D_
</table>_x000D_
<div class="scroll">_x000D_
  <table>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>More Text</td><td>More Text</td><td>More Text</td><td>More Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td></tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Difference between EXISTS and IN in SQL?

In certain circumstances, it is better to use IN rather than EXISTS. In general, if the selective predicate is in the subquery, then use IN. If the selective predicate is in the parent query, then use EXISTS.

https://docs.oracle.com/cd/B19306_01/server.102/b14211/sql_1016.htm#i28403

The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

iOS 9 (may) force developers to use App Transport Security exclusively. I overheard this somewhere randomly so I don't know whether this is true myself. But I suspect it and have come to this conclusion:

The app running on iOS 9 will (maybe) no longer connect to a Meteor server without SSL.

This means running meteor run ios or meteor run ios-device will (probably?) no longer work.

In the app's info.plist, NSAppTransportSecurity [Dictionary] needs to have a key NSAllowsArbitraryLoads [Boolean] to be set to YES or Meteor needs to use https for its localhost server soon.

Counting Chars in EditText Changed Listener

TextWatcher maritalStatusTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        try {
            if (charSequence.length()==0){
                topMaritalStatus.setVisibility(View.GONE);
            }else{
                topMaritalStatus.setVisibility(View.VISIBLE);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
};

How do I debug Node.js applications?

You may use pure Node.js and debug the application in the console if you wish.

For example let's create a dummy debug.js file that we want to debug and put breakpoints in it (debugger statement):

_x000D_
_x000D_
let a = 5;_x000D_
debugger;_x000D_
_x000D_
a *= 2;_x000D_
debugger;_x000D_
_x000D_
let b = 10;_x000D_
debugger;_x000D_
_x000D_
let c = a + b;_x000D_
debugger;_x000D_
_x000D_
console.log(c);
_x000D_
_x000D_
_x000D_

Then you may run this file for debugging using inspect command:

node inspect debug.js

This will launch the debugger in the console and you'll se the output that is similar to:

< Debugger listening on ws://127.0.0.1:9229/6da25f21-63a0-480d-b128-83a792b516fc
< For help, see: https://nodejs.org/en/docs/inspector
< Debugger attached.
Break on start in debug.js:1
> 1 (function (exports, require, module, __filename, __dirname) { let a = 5;
  2 debugger;
  3

You may notice here that file execution has been stopped at first line. From this moment you may go through the file step by step using following commands (hot-keys):

  • cont to continue,
  • next to go to the next breakpoint,
  • in to step in,
  • out to step out
  • pause to pause it

Let's type cont several times and see how we get from breakpoint to breakpoint:

debug> next
break in misc/debug.js:1
> 1 (function (exports, require, module, __filename, __dirname) { let a = 5;
  2 debugger;
  3
debug> next
break in misc/debug.js:2
  1 (function (exports, require, module, __filename, __dirname) { let a = 5;
> 2 debugger;
  3
  4 a *= 2;
debug> next
break in misc/debug.js:4
  2 debugger;
  3
> 4 a *= 2;
  5 debugger;
  6

What we may do now is we may check the variable values at this point by writing repl command. This will allow you to write variable name and see its value:

debug> repl
Press Ctrl + C to leave debug repl
> a
5
> b
undefined
> c
undefined
>

You may see that we have a = 5 at this moment and b and c are undefined.

Of course for more complex debugging you may want to use some external tools (IDE, browser). You may read more here.

How to send a simple string between two programs using pipes?

A regular pipe can only connect two related processes. It is created by a process and will vanish when the last process closes it.

A named pipe, also called a FIFO for its behavior, can be used to connect two unrelated processes and exists independently of the processes; meaning it can exist even if no one is using it. A FIFO is created using the mkfifo() library function.

Example

writer.c

#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
    int fd;
    char * myfifo = "/tmp/myfifo";

    /* create the FIFO (named pipe) */
    mkfifo(myfifo, 0666);

    /* write "Hi" to the FIFO */
    fd = open(myfifo, O_WRONLY);
    write(fd, "Hi", sizeof("Hi"));
    close(fd);

    /* remove the FIFO */
    unlink(myfifo);

    return 0;
}

reader.c

#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>

#define MAX_BUF 1024

int main()
{
    int fd;
    char * myfifo = "/tmp/myfifo";
    char buf[MAX_BUF];

    /* open, read, and display the message from the FIFO */
    fd = open(myfifo, O_RDONLY);
    read(fd, buf, MAX_BUF);
    printf("Received: %s\n", buf);
    close(fd);

    return 0;
}

Note: Error checking was omitted from the above code for simplicity.

React - Component Full Screen (with height 100%)

While this may not be the ideal answer but try this:

style={{top:'0', bottom:'0', left:'0', right:'0', position: 'absolute'}}

It keeps the size attached to borders which is not what you want but gives you somewhat same effect.

How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

"UnicodeDecodeError: 'ascii' codec can't decode byte"

Cause of this error: input_string must be unicode but str was given

"TypeError: Decoding Unicode is not supported"

Cause of this error: trying to convert unicode input_string into unicode


So first check that your input_string is str and convert to unicode if necessary:

if isinstance(input_string, str):
   input_string = unicode(input_string, 'utf-8')

Secondly, the above just changes the type but does not remove non ascii characters. If you want to remove non-ascii characters:

if isinstance(input_string, str):
   input_string = input_string.decode('ascii', 'ignore').encode('ascii') #note: this removes the character and encodes back to string.

elif isinstance(input_string, unicode):
   input_string = input_string.encode('ascii', 'ignore')

How to normalize a histogram in MATLAB?

There is an excellent three part guide for Histogram Adjustments in MATLAB (broken original link, archive.org link), the first part is on Histogram Stretching.

Check if a number is odd or even in python

Similarly to other languages, the fastest "modulo 2" (odd/even) operation is done using the bitwise and operator:

if x & 1:
    return 'odd'
else:
    return 'even'

Using Bitwise AND operator

  • The idea is to check whether the last bit of the number is set or not. If last bit is set then the number is odd, otherwise even.
  • If a number is odd & (bitwise AND) of the Number by 1 will be 1, because the last bit would already be set. Otherwise it will give 0 as output.

What does /p mean in set /p?

For future reference, you can get help for any command by using the /? switch, which should explain what switches do what.

According to the set /? screen, the format for set /p is SET /P variable=[promptString] which would indicate that the p in /p is "prompt." It just prints in your example because <nul passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.

/L in for /L generates a List of numbers.

From ping /?:

Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
            [-r count] [-s count] [[-j host-list] | [-k host-list]]
            [-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name

Options:
    -t             Ping the specified host until stopped.
                   To see statistics and continue - type Control-Break;
                   To stop - type Control-C.
    -a             Resolve addresses to hostnames.
    -n count       Number of echo requests to send.
    -l size        Send buffer size.
    -f             Set Don't Fragment flag in packet (IPv4-only).
    -i TTL         Time To Live.
    -v TOS         Type Of Service (IPv4-only. This setting has been deprecated
                   and has no effect on the type of service field in the IP Header).
    -r count       Record route for count hops (IPv4-only).
    -s count       Timestamp for count hops (IPv4-only).
    -j host-list   Loose source route along host-list (IPv4-only).
    -k host-list   Strict source route along host-list (IPv4-only).
    -w timeout     Timeout in milliseconds to wait for each reply.
    -R             Use routing header to test reverse route also (IPv6-only).
    -S srcaddr     Source address to use.
    -4             Force using IPv4.
    -6             Force using IPv6.

Returning an empty array

I'm pretty sure you should go with bar(); because with foo(); it creates a List (for nothing) since you create a new File[0] in the end anyway, so why not go with directly returning it!

How to disable button in React.js

very simple solution for this is by using useRef hook

const buttonRef = useRef();

const disableButton = () =>{
  buttonRef.current.disabled = true; // this disables the button
 }

<button
className="btn btn-primary mt-2"
ref={buttonRef}
onClick={disableButton}
>
    Add
</button>

Similarly you can enable the button by using buttonRef.current.disabled = false

Viewing root access files/folders of android on windows

I was looking long and hard for a solution to this problem and the best I found was a root FTP server on the phone that you connect to on Windows with an FTP client like FileZilla, on the same WiFi network of course.

The root FTP server app I ended up using is FTP Droid. I tried a lot of other FTP apps with bigger download numbers but none of them worked for me for whatever reason. So install this app and set a user with home as / or wherever you want.

Then make note of the phone IP and connect with FileZilla and you should have access to the root of the phone. The biggest benefit I found is I can download entire folders and FTP will just queue it up and take care of it. So I downloaded all of my /data/data/ folder when I was looking for an app and could search on my PC. Very handy.

Jackson - best way writes a java list to a json array

In objectMapper we have writeValueAsString() which accepts object as parameter. We can pass object list as parameter get the string back.

List<Apartment> aptList =  new ArrayList<Apartment>();
    Apartment aptmt = null;
    for(int i=0;i<5;i++){
         aptmt= new Apartment();
         aptmt.setAptName("Apartment Name : ArrowHead Ranch");
         aptmt.setAptNum("3153"+i);
         aptmt.setPhase((i+1));
         aptmt.setFloorLevel(i+2);
         aptList.add(aptmt);
    }
mapper.writeValueAsString(aptList)

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 3 2: ordinal not in range(128)

I had the same problem. This work fine for me:

str(objdata).encode('utf-8')

Styling input radio with css

See this Fiddle

<input type="radio" id="radio-2-1" name="radio-2-set" class="regular-radio" /><label for="radio-2-1"></label>
<input type="radio" id="radio-2-2" name="radio-2-set" class="regular-radio" /><label for="radio-2-2"></label>
<input type="radio" id="radio-2-3" name="radio-2-set" class="regular-radio" /><label for="radio-2-3"></label>

.regular-radio {
    display: none;
}

.regular-radio + label {
    -webkit-appearance: none;
    background-color: #e1e1e1;
    border: 4px solid #e1e1e1;
    border-radius: 10px;
    width: 100%;
    display: inline-block;
    position: relative;
    width: 10px;
    height: 10px;
}

.regular-radio:checked + label {
    background: grey;
    border: 4px solid #e1e1e1;
}

How to get date in BAT file

Locale-independent one liner to get any date format you like. I use it to generate archive names. Back quote option is needed because PowerShell command line is using single quotes.

:: Get date in yyyyMMdd_HHmm format to use with file name.
FOR /f "usebackq" %%i IN (`PowerShell ^(Get-Date^).ToString^('yyyy-MM-dd'^)`) DO SET DTime=%%i

:: Get formatted yesterday date.
FOR /f "usebackq" %%i IN (`PowerShell ^(Get-Date^).AddDays^(-1^).ToString^('yyyy-MM-dd'^)`) DO SET DTime=%%i

:: Show file name with the date.
echo Archive.%DTime%.zip

Oracle "ORA-01008: not all variables bound" Error w/ Parameters

The ODP.Net provider from oracle uses bind by position as default. To change the behavior to bind by name. Set property BindByName to true. Than you can dismiss the double definition of parameters.

using(OracleCommand cmd = con.CreateCommand()) {
    ...
    cmd.BindByName = true;
    ...
}

What are the differences between struct and class in C++?

According to Stroustrup in the C++ Programming Language:

Which style you use depends on circumstances and taste. I usually prefer to use struct for classes that have all data public. I think of such classes as "not quite proper types, just data structures."

Functionally, there is no difference other than the public / private

How to set a:link height/width with css?

From the definition of height:

Applies to: all elements but non-replaced inline elements, table columns, and column groups

An a element is, by default an inline element (and it is non-replaced).

You need to change the display (directly with the display property or indirectly, e.g. with float).

How to export DataTable to Excel

I would recommend ClosedXML -

You can turn a DataTable into an Excel worksheet with some very readable code:

XLWorkbook wb = new XLWorkbook();
DataTable dt = GetDataTableOrWhatever();
wb.Worksheets.Add(dt,"WorksheetName");

The developer is responsive and helpful. The project is actively developed, and the documentation is superb.

bash shell nested for loop

The question does not contain a nested loop, just a single loop. But THIS nested version works, too:

# for i in c d; do for j in a b; do echo $i $j; done; done
c a
c b
d a
d b

LD_LIBRARY_PATH vs LIBRARY_PATH

Since I link with gcc why ld is being called, as the error message suggests?

gcc calls ld internally when it is in linking mode.

Classes residing in App_Code is not accessible

Put this at the top of the other files where you want to access the class:

using CLIck10.App_Code;

OR access the class from other files like this:

CLIck10.App_Code.Glob

Not sure if that's your issue or not but if you were new to C# then this is an easy one to get tripped up on.

Update: I recently found that if I add an App_Code folder to a project, then I must close/reopen Visual Studio for it to properly recognize this "special" folder.

Android Studio - Failed to notify project evaluation listener error

you need check your gradle version. gradle -v

then you should know your gradle version and your gradle plugin version compatible.

Example:

gradle 4.6 is not compatible with gradle plugin 2.2.

so need update com.android.tools.build:gradle version to 2.3.3.

then you need check gradle/wrapper/gradle-wrapper.properties distributionUrl gradle version

google Android Plugin for Gradle Release Notes

enter image description here

on the other hand

using newer plugin version might require to update Android Studio

thanks @antek

proper name for python * operator?

I call it "positional expansion", as opposed to ** which I call "keyword expansion".

Replacing Numpy elements if condition is met

I am not sure I understood your question, but if you write:

mask_data[:3, :3] = 1
mask_data[3:, 3:] = 0

This will make all values of mask data whose x and y indexes are less than 3 to be equal to 1 and all rest to be equal to 0

Collections.emptyList() vs. new instance

The main difference is that Collections.emptyList() returns an immutable list, i.e., a list to which you cannot add elements. (Same applies to the List.of() introduced in Java 9.)

In the rare cases where you do want to modify the returned list, Collections.emptyList() and List.of() are thus not a good choices.

I'd say that returning an immutable list is perfectly fine (and even the preferred way) as long as the contract (documentation) does not explicitly state differently.


In addition, emptyList() might not create a new object with each call.

Implementations of this method need not create a separate List object for each call. Using this method is likely to have comparable cost to using the like-named field. (Unlike this method, the field does not provide type safety.)

The implementation of emptyList looks as follows:

public static final <T> List<T> emptyList() {
    return (List<T>) EMPTY_LIST;
}

So if your method (which returns an empty list) is called very often, this approach may even give you slightly better performance both CPU and memory wise.

jackson deserialization json to java-objects

Your product class needs a parameterless constructor. You can make it private, but Jackson needs the constructor.

As a side note: You should use Pascal casing for your class names. That is Product, and not product.

Saving and loading objects and using pickle

It seems you want to save your class instances across sessions, and using pickle is a decent way to do this. However, there's a package called klepto that abstracts the saving of objects to a dictionary interface, so you can choose to pickle objects and save them to a file (as shown below), or pickle the objects and save them to a database, or instead of use pickle use json, or many other options. The nice thing about klepto is that by abstracting to a common interface, it makes it easy so you don't have to remember the low-level details of how to save via pickling to a file, or otherwise.

Note that It works for dynamically added class attributes, which pickle cannot do...

dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive 
>>> db = file_archive('fruits.txt')
>>> class Fruits: pass
... 
>>> banana = Fruits()
>>> banana.color = 'yellow'
>>> banana.value = 30
>>> 
>>> db['banana'] = banana 
>>> db.dump()
>>> 

Then we restart…

dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive
>>> db = file_archive('fruits.txt')
>>> db.load()
>>> 
>>> db['banana'].color
'yellow'
>>> 

Klepto works on python2 and python3.

Get the code here: https://github.com/uqfoundation

Eclipse keyboard shortcut to indent source code to the left?

In any version of Eclipse IDE for source code indentation.

Select the source code and use the following keys

  1. For default java indentation Ctrl + I

  2. For right indentation Tab

  3. For left indentation Shift + Tab

Remove android default action bar

You can set it as a no title bar theme in the activity's xml in the AndroidManifest

    <activity 
        android:name=".AnActivity"
        android:label="@string/a_string"
        android:theme="@android:style/Theme.NoTitleBar">
    </activity>

ajax jquery simple get request

var dataString = "flag=fetchmediaaudio&id="+id;

$.ajax
({
  type: "POST",
  url: "ajax.php",
  data: dataString,
  success: function(html)
  {
     alert(html);
  }
});

Setting Camera Parameters in OpenCV/Python

I had the same problem with openCV on Raspberry Pi... don't know if this can solve your problem, but what worked for me was

import time
import cv2


cap = cv2.VideoCapture(0)

cap.set(3,1280)

cap.set(4,1024)

time.sleep(2)

cap.set(15, -8.0)

the time you have to use can be different

Getting String Value from Json Object Android

Please see my answer below, inspired by answers above but a bit more detailed...

// Get The Json Response (With Try Catch)
try {

    String s = null;

    if (response.body() != null) {

        s = response.body().string();

        // Convert Response Into Json Object (With Try Catch)
        JSONObject json = null;

        try {
            json = new JSONObject(s);

            // Extract The User Id From Json Object (With Try Catch)
            String stringToExtract = null;

            try {
                stringToExtract = json.getString("NeededString");

            } catch (JSONException e) {
                e.printStackTrace();
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

} catch (IOException e) {
    e.printStackTrace();
}

No module named 'openpyxl' - Python 3.4 - Ubuntu

I had the same problem solved using instead of pip install :

sudo apt-get install python-openpyxl
sudo apt-get install python3-openpyxl

The sudo command also works better for other packages.

How can I know if Object is String type object?

 object instanceof Type

is true if the object is a Type or a subclass of Type

 object.getClass().equals(Type.class) 

is true only if the object is a Type

CSS way to horizontally align table

Steven is right, in theory:

the “correct” way to center a table using CSS. Conforming browsers ought to center tables if the left and right margins are equal. The simplest way to accomplish this is to set the left and right margins to “auto.” Thus, one might write in a style sheet:

table
{ 
    margin-left: auto;
    margin-right: auto;
}

But the article mentioned in the beginning of this answer gives you all the other way to center a table.

An elegant css cross-browser solution: This works in both MSIE 6 (Quirks and Standards), Mozilla, Opera and even Netscape 4.x without setting any explicit widths:

div.centered 
{
    text-align: center;
}

div.centered table 
{
    margin: 0 auto; 
    text-align: left;
}


<div class="centered">
    <table>
    …
    </table>
</div>

Can't accept license agreement Android SDK Platform 24

For me I was Building the Ionic using "ionic build android" command and I was getting the same problem! The solution was simply

  • To install the required sdk
  • Run the same command in CMD must be as administrater

How to Delete a directory from Hadoop cluster which is having comma(,) in its name?

Run the command in the terminal

$hadoop fs -rm -r /path/to/directory

Changing Underline color

No. The best you can do is to use a border-bottom with a different color, but that isn't really underlining.

How to detect Adblock on my website?

No need for timeouts and DOM sniffing. Simply attempt to load a script from popular ad networks, and see if the ad blocker intercepted the HTTP request.

/**
 * Attempt to load a script from a popular ad network. Ad blockers will intercept the HTTP request.
 *
 * @param {string} url
 * @param {Function} cb
 */
function detectAdBlockerAsync(url, cb){
    var script = document.createElement('script');

    script.onerror = function(){
        script.onerror = null;
        document.body.removeChild(script);
        cb();
    }

    script.src = url;
    document.body.appendChild(script);
}

detectAdBlockerAsync('http://ads.pubmatic.com/AdServer/js/gshowad.js', function(){
    document.body.style.background = '#c00';
});

Spring: @Component versus @Bean

Let's consider I want specific implementation depending on some dynamic state. @Bean is perfect for that case.

@Bean
@Scope("prototype")
public SomeService someService() {
    switch (state) {
    case 1:
        return new Impl1();
    case 2:
        return new Impl2();
    case 3:
        return new Impl3();
    default:
        return new Impl();
    }
}

However there is no way to do that with @Component.

How to implode array with key and value without foreach in PHP

I would use serialize() or json_encode().

While it won't give your the exact result string you want, it would be much easier to encode/store/retrieve/decode later on.

Match exact string

"^" For the begining of the line "$" for the end of it. Eg.:

var re = /^abc$/;

Would match "abc" but not "1abc" or "abc1". You can learn more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

is it possible to add colors to python output?

being overwhelmed by being VERY NEW to python i missed some very simple and useful commands given here: Print in terminal with colors using Python? -

eventually decided to use CLINT as an answer that was given there by great and smart people

SQL RANK() over PARTITION on joined tables

SELECT a.C_ID,a.QRY_ID,a.RES_ID,b.SCORE,ROW_NUMBER() OVER (ORDER BY SCORE DESC) AS [RANK]
FROM CONTACTS a JOIN RSLTS b ON a.QRY_ID=b.QRY_ID AND a.RES_ID=b.RES_ID
ORDER BY a.C_ID

How do I measure request and response times at once using cURL?

Another option that is perhaps the simplest one in terms of the command line is adding the built-in --trace-time option:

curl -X POST -d @file server:port --trace-time

Even though it technically does not output the timings of the various steps as requested by the OP, it does display the timestamps for all steps of the request as shown below. Using this, you can (fairly easily) calculate how long each step has taken.

$ curl https://www.google.com --trace-time -v -o /dev/null
13:29:11.148734 * Rebuilt URL to: https://www.google.com/
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     013:29:11.149958 *   Trying 172.217.20.36...
13:29:11.149993 * TCP_NODELAY set
13:29:11.163177 * Connected to www.google.com (172.217.20.36) port 443 (#0)
13:29:11.164768 * ALPN, offering h2
13:29:11.164804 * ALPN, offering http/1.1
13:29:11.164833 * successfully set certificate verify locations:
13:29:11.164863 *   CAfile: none
  CApath: /etc/ssl/certs
13:29:11.165046 } [5 bytes data]
13:29:11.165099 * (304) (OUT), TLS handshake, Client hello (1):
13:29:11.165128 } [512 bytes data]
13:29:11.189518 * (304) (IN), TLS handshake, Server hello (2):
13:29:11.189537 { [100 bytes data]
13:29:11.189628 * TLSv1.2 (IN), TLS handshake, Certificate (11):
13:29:11.189658 { [2104 bytes data]
13:29:11.190243 * TLSv1.2 (IN), TLS handshake, Server key exchange (12):
13:29:11.190277 { [115 bytes data]
13:29:11.190507 * TLSv1.2 (IN), TLS handshake, Server finished (14):
13:29:11.190539 { [4 bytes data]
13:29:11.190770 * TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
13:29:11.190797 } [37 bytes data]
13:29:11.190890 * TLSv1.2 (OUT), TLS change cipher, Client hello (1):
13:29:11.190915 } [1 bytes data]
13:29:11.191023 * TLSv1.2 (OUT), TLS handshake, Finished (20):
13:29:11.191053 } [16 bytes data]
13:29:11.204324 * TLSv1.2 (IN), TLS handshake, Finished (20):
13:29:11.204358 { [16 bytes data]
13:29:11.204417 * SSL connection using TLSv1.2 / ECDHE-ECDSA-CHACHA20-POLY1305
13:29:11.204451 * ALPN, server accepted to use h2
13:29:11.204483 * Server certificate:
13:29:11.204520 *  subject: C=US; ST=California; L=Mountain View; O=Google LLC; CN=www.google.com
13:29:11.204555 *  start date: Oct  2 07:29:00 2018 GMT
13:29:11.204585 *  expire date: Dec 25 07:29:00 2018 GMT
13:29:11.204623 *  subjectAltName: host "www.google.com" matched cert's "www.google.com"
13:29:11.204663 *  issuer: C=US; O=Google Trust Services; CN=Google Internet Authority G3
13:29:11.204701 *  SSL certificate verify ok.
13:29:11.204754 * Using HTTP2, server supports multi-use
13:29:11.204795 * Connection state changed (HTTP/2 confirmed)
13:29:11.204840 * Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
13:29:11.204881 } [5 bytes data]
13:29:11.204983 * Using Stream ID: 1 (easy handle 0x55846ef24520)
13:29:11.205034 } [5 bytes data]
13:29:11.205104 > GET / HTTP/2
13:29:11.205104 > Host: www.google.com
13:29:11.205104 > User-Agent: curl/7.61.0
13:29:11.205104 > Accept: */*
13:29:11.205104 > 
13:29:11.218116 { [5 bytes data]
13:29:11.218173 * Connection state changed (MAX_CONCURRENT_STREAMS == 100)!
13:29:11.218211 } [5 bytes data]
13:29:11.251936 < HTTP/2 200 
13:29:11.251962 < date: Fri, 19 Oct 2018 10:29:11 GMT
13:29:11.251998 < expires: -1
13:29:11.252046 < cache-control: private, max-age=0
13:29:11.252085 < content-type: text/html; charset=ISO-8859-1
13:29:11.252119 < p3p: CP="This is not a P3P policy! See g.co/p3phelp for more info."
13:29:11.252160 < server: gws
13:29:11.252198 < x-xss-protection: 1; mode=block
13:29:11.252228 < x-frame-options: SAMEORIGIN
13:29:11.252262 < set-cookie: 1P_JAR=2018-10-19-10; expires=Sun, 18-Nov-2018 10:29:11 GMT; path=/; domain=.google.com
13:29:11.252297 < set-cookie: NID=141=pzXxp1jrJmLwFVl9bLMPFdGCtG8ySQKxB2rlDWgerrKJeXxfdmB1HhJ1UXzX-OaFQcnR1A9LKYxi__PWMigjMBQHmI3xkU53LI_TsYRbkMNJNdxs-caQQ7fEcDGE694S; expires=Sat, 20-Apr-2019 10:29:11 GMT; path=/; domain=.google.com; HttpOnly
13:29:11.252336 < alt-svc: quic=":443"; ma=2592000; v="44,43,39,35"
13:29:11.252368 < accept-ranges: none
13:29:11.252408 < vary: Accept-Encoding
13:29:11.252438 < 
13:29:11.252473 { [5 bytes data]
100 12215    0 12215    0     0   112k      0 --:--:-- --:--:-- --:--:--  112k
13:29:11.255674 * Connection #0 to host www.google.com left intact

How to set shadows in React Native for android?

Set elevation: 3 and you should see the shadow in bottom of component without a 3rd party lib. At least in RN 0.57.4

Dynamically load a JavaScript file

If you have jQuery loaded already, you should use $.getScript.

This has an advantage over the other answers here in that you have a built in callback function (to guarantee the script is loaded before the dependant code runs) and you can control caching.

How do I trim whitespace?

Generally, I am using the following method:

>>> myStr = "Hi\n Stack Over \r flow!"
>>> charList = [u"\u005Cn",u"\u005Cr",u"\u005Ct"]
>>> import re
>>> for i in charList:
        myStr = re.sub(i, r"", myStr)

>>> myStr
'Hi Stack Over  flow'

Note: This is only for removing "\n", "\r" and "\t" only. It does not remove extra spaces.

How to print number with commas as thousands separators?

I have a python 2 and python 3 version of this code. I know that the question was asked for python 2 but now (8 years later lol) people will probably be using python 3.

Python 3 Code:

import random
number = str(random.randint(1, 10000000))
comma_placement = 4
print('The original number is: {}. '.format(number))
while True:
    if len(number) % 3 == 0:
        for i in range(0, len(number) // 3 - 1):
            number = number[0:len(number) - comma_placement + 1] + ',' + number[len(number) - comma_placement + 1:]
            comma_placement = comma_placement + 4
    else:
        for i in range(0, len(number) // 3):
            number = number[0:len(number) - comma_placement + 1] + ',' + number[len(number) - comma_placement + 1:]
    break
print('The new and improved number is: {}'.format(number))        


Python 2 Code: (Edit. The python 2 code isn't working. I am thinking that the syntax is different).

import random
number = str(random.randint(1, 10000000))
comma_placement = 4
print 'The original number is: %s.' % (number)
while True:
    if len(number) % 3 == 0:
        for i in range(0, len(number) // 3 - 1):
            number = number[0:len(number) - comma_placement + 1] + ',' + number[len(number) - comma_placement + 1:]
            comma_placement = comma_placement + 4
    else:
        for i in range(0, len(number) // 3):
            number = number[0:len(number) - comma_placement + 1] + ',' + number[len(number) - comma_placement + 1:]
    break
print 'The new and improved number is: %s.' % (number) 

CodeIgniter - accessing $config variable in view

Your controller should collect all the information from databases, configs, etc. There are many good reasons to stick to this. One good reason is that this will allow you to change the source of that information quite easily and not have to make any changes to your views.

Passing parameters to a Bash function

Drop the parentheses and commas:

 myBackupFunction ".." "..." "xx"

And the function should look like this:

function myBackupFunction() {
    # Here $1 is the first parameter, $2 the second, etc.
}

jQuery Data vs Attr?

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

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

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

Data set with attr()

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

Data set with .data()

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

PHP - Copy image to my server direct from URL

This SO thread will solve your problem. Solution in short:

$url = 'http://www.google.co.in/intl/en_com/images/srpr/logo1w.png';
$img = '/my/folder/my_image.gif';
file_put_contents($img, file_get_contents($url));

Regular Expression For Duplicate Words

The below expression should work correctly to find any number of consecutive words. The matching can be case insensitive.

String regex = "\\b(\\w+)(\\s+\\1\\b)*";
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);

Matcher m = p.matcher(input);

// Check for subsequences of input that match the compiled pattern
while (m.find()) {
     input = input.replaceAll(m.group(0), m.group(1));
}

Sample Input : Goodbye goodbye GooDbYe

Sample Output : Goodbye

Explanation:

The regex expression:

\b : Start of a word boundary

\w+ : Any number of word characters

(\s+\1\b)* : Any number of space followed by word which matches the previous word and ends the word boundary. Whole thing wrapped in * helps to find more than one repetitions.

Grouping :

m.group(0) : Shall contain the matched group in above case Goodbye goodbye GooDbYe

m.group(1) : Shall contain the first word of the matched pattern in above case Goodbye

Replace method shall replace all consecutive matched words with the first instance of the word.

How to use pagination on HTML tables?

There's a easy way to paginate a table using breedjs (jQuery plugin), see the example:

HTML

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Gender</th>
      <th>Age</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <tr b-scope="people" b-loop="person in people" b-paginate="5">
      <td>{{person.name}}</td>
      <td>{{person.gender}}</td>
      <td>{{person.age}}</td>
      <td>{{person.email}}</td>
    </tr>
  </tbody>
</table>
<ul></ul>

JS

var data={ people: [ {...}, {...}, ...] };

$(function() {
  breed.run({
    scope: 'people',
    input: data,
    runEnd: function(){ //This runEnd is just to mount the page buttons
        for(i=1 ; i<=breed.getPageCount('people') ; i++){
        $('ul').append(
            $('<li>',{
            html: i,
            onclick: "breed.paginate({scope: 'people', page: " + i + "});"
          })
        );
      }
    }
  });
});

Every time you want to change pages, just call:

breed.paginate({scope: 'people', page: pageNumber);

More info.

Working example.

how to add script inside a php code?

You can just echo all the HTML as normal:

<?php
   echo '<input type="button" onclick="alert(\'Clicky!\')"/>';
?>

Ansible: How to delete files and folders inside a directory?

I want to make sure that the find command only deletes everything inside the directory and leave the directory intact because in my case the directory is a filesystem. The system will generate an error when trying to delete a filesystem but that is not a nice option. Iam using the shell option because that is the only working option I found so far for this question.

What I did:

Edit the hosts file to put in some variables:

[all:vars]
COGNOS_HOME=/tmp/cognos
find=/bin/find

And create a playbook:

- hosts: all
  tasks:
  - name: Ansible remove files
    shell: "{{ find }} {{ COGNOS_HOME }} -xdev -mindepth 1 -delete"

This will delete all files and directories in the COGNOS_HOME variable directory/filesystem. The "-mindepth 1" option makes sure that the current directory will not be touched.

Implement a simple factory pattern with Spring 3 annotations

You could also declaratively define a bean of type ServiceLocatorFactoryBean that will act as a Factory class. it supported by Spring 3.

A FactoryBean implementation that takes an interface which must have one or more methods with the signatures (typically, MyService getService() or MyService getService(String id)) and creates a dynamic proxy which implements that interface

Here's an example of implementing the Factory pattern using Spring

One more clearly example

Connecting to TCP Socket from browser using javascript

This will be possible via the navigator interface as shown below:

navigator.tcpPermission.requestPermission({remoteAddress:"127.0.0.1", remotePort:6789}).then(
  () => {
    // Permission was granted
    // Create a new TCP client socket and connect to remote host
    var mySocket = new TCPSocket("127.0.0.1", 6789);

    // Send data to server
    mySocket.writeable.write("Hello World").then(
        () => {

            // Data sent sucessfully, wait for response
            console.log("Data has been sent to server");
            mySocket.readable.getReader().read().then(
                ({ value, done }) => {
                    if (!done) {
                        // Response received, log it:
                        console.log("Data received from server:" + value);
                    }

                    // Close the TCP connection
                    mySocket.close();
                }
            );
        },
        e => console.error("Sending error: ", e)
    );
  }
);

More details are outlined in the w3.org tcp-udp-sockets documentation.

http://raw-sockets.sysapps.org/#interface-tcpsocket

https://www.w3.org/TR/tcp-udp-sockets/

Another alternative is to use Chrome Sockets

Creating connections

chrome.sockets.tcp.create({}, function(createInfo) {
  chrome.sockets.tcp.connect(createInfo.socketId,
    IP, PORT, onConnectedCallback);
});

Sending data

chrome.sockets.tcp.send(socketId, arrayBuffer, onSentCallback);

Receiving data

chrome.sockets.tcp.onReceive.addListener(function(info) {
  if (info.socketId != socketId)
    return;
  // info.data is an arrayBuffer.
});

You can use also attempt to use HTML5 Web Sockets (Although this is not direct TCP communication):

var connection = new WebSocket('ws://IPAddress:Port');

connection.onopen = function () {
  connection.send('Ping'); // Send the message 'Ping' to the server
};

http://www.html5rocks.com/en/tutorials/websockets/basics/

Your server must also be listening with a WebSocket server such as pywebsocket, alternatively you can write your own as outlined at Mozilla

How to use Python to execute a cURL command?

import requests
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
data = requests.get(url).json

maybe?

if you are trying to send a file

files = {'request_file': open('request.json', 'rb')}
r = requests.post(url, files=files)
print r.text, print r.json

ahh thanks @LukasGraf now i better understand what his original code is doing

import requests,json
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
my_json_data = json.load(open("request.json"))
req = requests.post(url,data=my_json_data)
print req.text
print 
print req.json # maybe? 

Put icon inside input element in a form

use this css class for your input at start, then customize accordingly:

_x000D_
_x000D_
    _x000D_
 .inp-icon{_x000D_
background: url(https://i.imgur.com/kSROoEB.png)no-repeat 100%;_x000D_
background-size: 16px;_x000D_
 }
_x000D_
<input class="inp-icon" type="text">
_x000D_
_x000D_
_x000D_

Is there such a thing as min-font-size and max-font-size?

You can use Sass to control min and max font sizes. Here is a brilliant solution by Eduardo Boucas.

https://eduardoboucas.com/blog/2015/06/18/viewport-sized-typography-with-minimum-and-maximum-sizes.html

@mixin responsive-font($responsive, $min, $max: false, $fallback: false) {
  $responsive-unitless: $responsive / ($responsive - $responsive + 1);
  $dimension: if(unit($responsive) == 'vh', 'height', 'width');
  $min-breakpoint: $min / $responsive-unitless * 100;

  @media (max-#{$dimension}: #{$min-breakpoint}) {
    font-size: $min;
  }

  @if $max {
    $max-breakpoint: $max / $responsive-unitless * 100;

    @media (min-#{$dimension}: #{$max-breakpoint}) {
      font-size: $max;
    }
  }

  @if $fallback {
    font-size: $fallback;
  }

  font-size: $responsive;
}

.limit-min {
  @include responsive-font(3vw, 20px);
}

.limit-min-max {
  @include responsive-font(3vw, 20px, 50px);
}

What GRANT USAGE ON SCHEMA exactly do?

For a production system, you can use this configuration :

--ACCESS DB
REVOKE CONNECT ON DATABASE nova FROM PUBLIC;
GRANT  CONNECT ON DATABASE nova  TO user;

--ACCESS SCHEMA
REVOKE ALL     ON SCHEMA public FROM PUBLIC;
GRANT  USAGE   ON SCHEMA public  TO user;

--ACCESS TABLES
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC ;
GRANT SELECT                         ON ALL TABLES IN SCHEMA public TO read_only ;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO read_write ;
GRANT ALL                            ON ALL TABLES IN SCHEMA public TO admin ;

Bootstrap 3 unable to display glyphicon properly

Here's the fix that worked for me. Firefox has a file origin policy that causes this. To fix do the following steps:

  1. open about:config in firefox
  2. Find security.fileuri.strict_origin_policy property and change it from ‘true’ to ‘false.’
  3. Voial! you are good to go!

Details: http://stuffandnonsense.co.uk/blog/about/firefoxs_file_uri_origin_policy_and_web_fonts

You will only see this issue when accessing a file using file:/// protocol

Call An Asynchronous Javascript Function Synchronously

You can also convert it into callbacks.

function thirdPartyFoo(callback) {    
  callback("Hello World");    
}

function foo() {    
  var fooVariable;

  thirdPartyFoo(function(data) {
    fooVariable = data;
  });

  return fooVariable;
}

var temp = foo();  
console.log(temp);

Submit form without reloading page

I guess this is what you need. Try this .

<form action="" method="get">
                <input name="search" type="text">
                <input type="button" value="Search" onclick="return updateTable();">
                </form>

and your javascript code is the same

function updateTable()
    {   
        var photoViewer = document.getElementById('photoViewer');
        var photo = document.getElementById('photo1').href;
        var numOfPics = 5;
        var columns = 3; 
        var rows = Math.ceil(numOfPics/columns);
        var content="";
        var count=0;

        content = "<table class='photoViewer' id='photoViewer'>";
            for (r = 0; r < rows; r++) {
                content +="<tr>";
                for (c = 0; c < columns; c++) {
                    count++;
                    if(count == numOfPics)break; // here is check if number of cells equal Number of Pictures to stop
                        content +="<td><a href='"+photo+"' id='photo1'><img class='photo' src='"+photo+"' alt='Photo'></a><p>City View</p></td>";
                }
                content +="</tr>";
            }
        content += "</table>";

        photoViewer.innerHTML = content; 
}

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'?

I ran into this issue after updating the Java JDK, but had not yet restarted my command prompt. After restarting the command prompt, everything worked fine. Presumably, because the PATH variable need to be reset after the JDK update.

How can I bind to the change event of a textarea in jQuery?

After some experimentation I came up with this implementation:

$('.detect-change')
    .on('change cut paste', function(e) {
        console.log("Change detected.");
        contentModified = true;
    })
    .keypress(function(e) {
        if (e.which !== 0 && e.altKey == false && e.ctrlKey == false && e.metaKey == false) {
            console.log("Change detected.");
            contentModified = true;
        }
    });

Handles changes to any kind of input and select as well as textareas ignoring arrow keys and things like ctrl, cmd, function keys, etc.

Note: I've only tried this in FF since it's for a FF add-on.

Read large files in Java

Unless you accidentally read in the whole input file instead of reading it line by line, then your primary limitation will be disk speed. You may want to try starting with a file containing 100 lines and write it to 100 different files one line in each and make the triggering mechanism work on the number of lines written to the current file. That program will be easily scalable to your situation.

Printing all properties in a Javascript Object

Your syntax is incorrect. The var keyword in your for loop must be followed by a variable name, in this case its propName

var propValue;
for(var propName in nyc) {
    propValue = nyc[propName]

    console.log(propName,propValue);
}

I suggest you have a look here for some basics:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

CSS:Defining Styles for input elements inside a div

CSS 3

divContainer input[type="text"] {
    width:150px;
}

CSS2 add a class "text" to the text inputs then in your css

.divContainer.text{
    width:150px;
}

Why doesn't Java support unsigned ints?

This is an older question and pat did briefly mention char, I just thought I should expand upon this for others who will look at this down the road. Let's take a closer look at the Java primitive types:

byte - 8-bit signed integer

short - 16-bit signed integer

int - 32-bit signed integer

long - 64-bit signed integer

char - 16-bit character (unsigned integer)

Although char does not support unsigned arithmetic, it essentially can be treated as an unsigned integer. You would have to explicitly cast arithmetic operations back into char, but it does provide you with a way to specify unsigned numbers.

char a = 0;
char b = 6;
a += 1;
a = (char) (a * b);
a = (char) (a + b);
a = (char) (a - 16);
b = (char) (b % 3);
b = (char) (b / a);
//a = -1; // Generates complier error, must be cast to char
System.out.println(a); // Prints ? 
System.out.println((int) a); // Prints 65532
System.out.println((short) a); // Prints -4
short c = -4;
System.out.println((int) c); // Prints -4, notice the difference with char
a *= 2;
a -= 6;
a /= 3;
a %= 7;
a++;
a--;

Yes, there isn't direct support for unsigned integers (obviously, I wouldn't have to cast most of my operations back into char if there was direct support). However, there certainly exists an unsigned primitive data type. I would liked to have seen an unsigned byte as well, but I guess doubling the memory cost and instead use char is a viable option.


Edit

With JDK8 there are new APIs for Long and Integer which provide helper methods when treating long and int values as unsigned values.

  • compareUnsigned
  • divideUnsigned
  • parseUnsignedInt
  • parseUnsignedLong
  • remainderUnsigned
  • toUnsignedLong
  • toUnsignedString

Additionally, Guava provides a number of helper methods to do similar things for at the integer types which helps close the gap left by the lack of native support for unsigned integers.

Android device is not connected to USB for debugging (Android studio)

For me, this simple trick worked:

I actually enabled and disabled the listed USB Adapter for android in the device manager (Control Panel -> Hardware & Sound -> Device Manager). And holy moly it's working! :D

How to query for today's date and 7 days before data?

Query in Parado's answer is correct, if you want to use MySql too instead GETDATE() you must use (because you've tagged this question with Sql server and Mysql):

select * from tab
where DateCol between adddate(now(),-7) and now() 

How do I give text or an image a transparent background using CSS?

If you are a Photoshop guy, you can also use:

 #some-element {
  background-color: hsla(170, 50%, 45%, 0.9); // **0.9 is the opacity range from 0 - 1**
 }

Or:

#some-element {
  background-color: rgba(170, 190, 45, 0.9); // **0.9 is the opacity range from 0 - 1**
}

List an Array of Strings in alphabetical order

Arrays.sort(stringArray); This sorts the string array based on the Unicode characters values. All strings that contain uppercase characters at the beginning of the string will be at the top of the sorted list alphabetically followed by all strings with lowercase characters. Hence if the array contains strings beginning with both uppercase characters and lowercase characters, the sorted array would not return a case insensitive order alphabetical list

String[] strArray = { "Carol", "bob", "Alice" };
Arrays.sort(strList);
System.out.println(Arrays.toString(hotel));

Output is : Alice, Carol, bob,

If you require the Strings to be sorted without regards to case, you'll need a second argument, a Comparator, for Arrays.sort(). Such a comparator has already been written for us and can be accessed as a static on the String class named CASE_INSENSITIVE_ORDER.

String[] strArray = { "Carol", "bob", "Alice" };
Arrays.sort(stringArray, String.CASE_INSENSITIVE_ORDER);
System.out.println(Arrays.toString(strArray ));

Output is : Alice, bob, Carol

How can I send an email through the UNIX mailx command?

If you want to send more than two person or DL :

echo "Message Body" | mailx -s "Message Title" -r [email protected] [email protected],[email protected]

here:

  • -s = subject or mail title
  • -r = sender mail or DL

Decreasing height of bootstrap 3.0 navbar

Simply override the min-height set in .navbar like so:

.navbar{
  min-height:20px; //* or whatever height you require
}

Altering an elements height to something smaller than the min-height won't make a difference...

How can I get column names from a table in Oracle?

describe YOUR_TABLE;

In your case :

describe EVENT_LOG;

Spring MVC Controller redirect using URL parameters instead of in response

You can have processForm() return a View object instead, and have it return the concrete type RedirectView which has a parameter for setExposeModelAttributes().

When you return a view name prefixed with "redirect:", Spring MVC transforms this to a RedirectView object anyway, it just does so with setExposeModelAttributes to true (which I think is an odd value to default to).

How can I scroll a div to be visible in ReactJS?

Another example which uses function in ref rather than string

class List extends React.Component {
  constructor(props) {
    super(props);
    this.state = { items:[], index: 0 };
    this._nodes = new Map();

    this.handleAdd = this.handleAdd.bind(this);
    this.handleRemove = this.handleRemove.bind(this);
   }

  handleAdd() {
    let startNumber = 0;
    if (this.state.items.length) {
      startNumber = this.state.items[this.state.items.length - 1];
    }

    let newItems = this.state.items.splice(0);
    for (let i = startNumber; i < startNumber + 100; i++) {
      newItems.push(i);
    }

    this.setState({ items: newItems });
  }

  handleRemove() {
    this.setState({ items: this.state.items.slice(1) });
  }

  handleShow(i) {
    this.setState({index: i});
    const node = this._nodes.get(i);
    console.log(this._nodes);
    if (node) {
      ReactDOM.findDOMNode(node).scrollIntoView({block: 'end', behavior: 'smooth'});
    }
  }

  render() {
    return(
      <div>
        <ul>{this.state.items.map((item, i) => (<Item key={i} ref={(element) => this._nodes.set(i, element)}>{item}</Item>))}</ul>
        <button onClick={this.handleShow.bind(this, 0)}>0</button>
        <button onClick={this.handleShow.bind(this, 50)}>50</button>
        <button onClick={this.handleShow.bind(this, 99)}>99</button>
        <button onClick={this.handleAdd}>Add</button>
        <button onClick={this.handleRemove}>Remove</button>
        {this.state.index}
      </div>
    );
  }
}

class Item extends React.Component
{
  render() {
    return (<li ref={ element => this.listItem = element }>
      {this.props.children}
    </li>);
  }
}

Demo: https://codepen.io/anon/pen/XpqJVe

How to access Winform textbox control from another class?

// Take the Active form to a form variable.

Form F1 = myForm1.ActiveForm;

//Findout the Conntrol and Change the properties

F1.Controls.Find("Textbox1", true).ElementAt(0).Text= "Whatever you want to write";

How to display an unordered list in two columns?

I like the solution for modern browsers, but the bullets are missing, so I add it a little trick:

http://jsfiddle.net/HP85j/419/

ul {
    list-style-type: none;
    columns: 2;
    -webkit-columns: 2;
    -moz-columns: 2;
}


li:before {
  content: "• ";
}

enter image description here

How to convert an enum type variable to a string?

To extend James' answer, someone want some example code to support enum define with int value, I also have this requirement, so here is my way:

First one the is internal use macro, which is used by FOR_EACH:

#define DEFINE_ENUM_WITH_STRING_CONVERSIONS_EXPAND_VALUE(r, data, elem)         \
    BOOST_PP_IF(                                                                \
        BOOST_PP_EQUAL(BOOST_PP_TUPLE_SIZE(elem), 2),                           \
        BOOST_PP_TUPLE_ELEM(0, elem) = BOOST_PP_TUPLE_ELEM(1, elem),            \
        BOOST_PP_TUPLE_ELEM(0, elem) ),

And, here is the define macro:

#define DEFINE_ENUM_WITH_STRING_CONVERSIONS(name, enumerators)                  \
    enum name {                                                                 \
        BOOST_PP_SEQ_FOR_EACH(DEFINE_ENUM_WITH_STRING_CONVERSIONS_EXPAND_VALUE, \
                              0, enumerators) };

So when using it, you may like to write like this:

DEFINE_ENUM_WITH_STRING_CONVERSIONS(MyEnum,
    ((FIRST, 1))
    ((SECOND))
    ((MAX, SECOND)) )

which will expand to:

enum MyEnum
{
    FIRST = 1,
    SECOND,
    MAX = SECOND,
};

The basic idea is to define a SEQ, which every element is a TUPLE, so we can put addition value for enum member. In FOR_EACH loop, check the item TUPLE size, if the size is 2, expand the code to KEY = VALUE, else just keep the first element of TUPLE.

Because the input SEQ is actually TUPLEs, so if you want to define STRINGIZE functions, you may need to pre-process the input enumerators first, here is the macro to do the job:

#define DEFINE_ENUM_WITH_STRING_CONVERSIONS_FIRST_ELEM(r, data, elem)           \
    BOOST_PP_TUPLE_ELEM(0, elem),

#define DEFINE_ENUM_WITH_STRING_CONVERSIONS_FIRST_ELEM_SEQ(enumerators)         \
    BOOST_PP_SEQ_SUBSEQ(                                                        \
        BOOST_PP_TUPLE_TO_SEQ(                                                  \
            (BOOST_PP_SEQ_FOR_EACH(                                             \
                DEFINE_ENUM_WITH_STRING_CONVERSIONS_FIRST_ELEM, 0, enumerators) \
            )),                                                                 \
            0,                                                                  \
            BOOST_PP_SEQ_SIZE(enumerators))

The macro DEFINE_ENUM_WITH_STRING_CONVERSIONS_FIRST_ELEM_SEQ will only keep the first element in every TUPLE, and later convert to SEQ, now modify James' code, you will have the full power.

My implementation maybe not the simplest one, so if you do not find any clean code, mine for your reference.

Deleting elements from std::set while iterating

I think using the STL method 'remove_if' from could help to prevent some weird issue when trying to attempt to delete the object that is wrapped by the iterator.

This solution may be less efficient.

Let's say we have some kind of container, like vector or a list called m_bullets:

Bullet::Ptr is a shared_pr<Bullet>

'it' is the iterator that 'remove_if' returns, the third argument is a lambda function that is executed on every element of the container. Because the container contains Bullet::Ptr, the lambda function needs to get that type(or a reference to that type) passed as an argument.

 auto it = std::remove_if(m_bullets.begin(), m_bullets.end(), [](Bullet::Ptr bullet){
    // dead bullets need to be removed from the container
    if (!bullet->isAlive()) {
        // lambda function returns true, thus this element is 'removed'
        return true;
    }
    else{
        // in the other case, that the bullet is still alive and we can do
        // stuff with it, like rendering and what not.
        bullet->render(); // while checking, we do render work at the same time
        // then we could either do another check or directly say that we don't
        // want the bullet to be removed.
        return false;
    }
});
// The interesting part is, that all of those objects were not really
// completely removed, as the space of the deleted objects does still 
// exist and needs to be removed if you do not want to manually fill it later 
// on with any other objects.
// erase dead bullets
m_bullets.erase(it, m_bullets.end());

'remove_if' removes the container where the lambda function returned true and shifts that content to the beginning of the container. The 'it' points to an undefined object that can be considered garbage. Objects from 'it' to m_bullets.end() can be erased, as they occupy memory, but contain garbage, thus the 'erase' method is called on that range.

What is the maximum possible length of a .NET string?

Since the Length property of System.String is an Int32, I would guess that that the maximum length would be 2,147,483,647 chars (max Int32 size). If it allowed longer you couldn't check the Length since that would fail.

Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

Just create the database using createdb CLI tool:

PGHOST="my.database.domain.com"
PGUSER="postgres"
PGDB="mydb"
createdb -h $PGHOST -p $PGPORT -U $PGUSER $PGDB

If the database exists, it will return an error:

createdb: database creation failed: ERROR:  database "mydb" already exists

Is it still valid to use IE=edge,chrome=1?

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> serves two purposes.

  1. IE=edge: specifies that IE should run in the highest mode available to that version of IE as opposed to a compatability mode; IE8 can support up to IE8 modes, IE9 can support up to IE9 modes, and so on.
  2. chrome=1: specifies that Google Chrome frame should start if the user has it installed

The IE=edge flag is still relevant for IE versions 10 and below. IE11 sets this mode as the default.

As for the chrome flag, you can leave it if your users still use Chrome Frame. Despite support and updates for Chrome Frame ending, one can still install and use the final release. If you remove the flag, Chrome Frame will not be activated when installed. For other users, chrome=1 will do nothing more than consume a few bytes of bandwidth.

I recommend you analyze your audience and see if their browsers prohibit any needed features and then decide. Perhaps it might be better to encourage them to use a more modern, evergreen browser.

Note, the W3C validator will flag chrome=1 as an error:

Error: A meta element with an http-equiv attribute whose value is
X-UA-Compatible must have a content attribute with the value IE=edge.

How do I output the results of a HiveQL query to CSV?

I was looking for a similar solution, but the ones mentioned here would not work. My data had all variations of whitespace (space, newline, tab) chars and commas.

To make the column data tsv safe, I replaced all \t chars in the column data with a space, and executed python code on the commandline to generate a csv file, as shown below:

hive -e 'tab_replaced_hql_query' |  python -c 'exec("import sys;import csv;reader = csv.reader(sys.stdin, dialect=csv.excel_tab);writer = csv.writer(sys.stdout, dialect=csv.excel)\nfor row in reader: writer.writerow(row)")'

This created a perfectly valid csv. Hope this helps those who come looking for this solution.

Select current date by default in ASP.Net Calendar control

If you are already doing databinding:

<asp:Calendar ID="Calendar1" runat="server"  SelectedDate="<%# DateTime.Today %>" />

Will do it. This does require that somewhere you are doing a Page.DataBind() call (or a databind call on a parent control). If you are not doing that and you absolutely do not want any codebehind on the page, then you'll have to create a usercontrol that contains a calendar control and sets its selecteddate.

How to return a string from a C++ function?

string str1, str2, str3;

cout << "These are the strings: " << endl;
cout << "str1: \"the dog jumped over the fence\"" << endl;
cout << "str2: \"the\"" << endl;
cout << "str3: \"that\"" << endl << endl;

From this, I see that you have not initialized str1, str2, or str3 to contain the values that you are printing. I might suggest doing so first:

string str1 = "the dog jumped over the fence", 
       str2 = "the",
       str3 = "that";

cout << "These are the strings: " << endl;
cout << "str1: \"" << str1 << "\"" << endl;
cout << "str2: \"" << str2 << "\"" << endl;
cout << "str3: \"" << str3 << "\"" << endl << endl;

Which data structures and algorithms book should I buy?

Introduction to Algorithms by Cormen et. al. is a standard introductory algorithms book, and is used by many universities, including my own. It has pretty good coverage and is very approachable.

And anything by Robert Sedgewick is good too.

In MS DOS copying several files to one file

filenames must sort correctly to combine correctly!

file1.bin file2.bin ... file10.bin wont work properly

file01.bin file02.bin ... file10.bin will work properly

c:>for %i in (file*.bin) do type %i >> onebinary.bin

Works for ascii or binary files.

How to set xlim and ylim for a subplot in matplotlib

You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.* function are thin wrappers that basically do gca().*.

plt.subplot returns an axes object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.

import matplotlib.pyplot as plt

ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])


ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])

and so on for as many axes as you want.

or better, wrap it all up in a loop:

import matplotlib.pyplot as plt

DATA_x = ([1, 2],
          [2, 3],
          [3, 4])

DATA_y = DATA_x[::-1]

XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3

for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
    ax = plt.subplot(1, 3, j + 1)
    ax.scatter(x, y)
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

How can you use php in a javascript function

you use script in php..

<?php

        $num = 1;
        echo $num;

    echo '<input type="button"
           name="lol" 
           value="Click to increment"
           onclick="Inc()" />
    <br>
    <script>
        function Inc()
        {';
            $num = 2;
            echo $num;

        echo '}
    </script>';
?>

how to change namespace of entire project?

In asp.net is more to do, to get completely running under another namespace.

  • Copy your source folder and rename it to your new project name.
  • Open it and Replace all by Ctrl + H and be sure to include all Replace everything
  • Press F2 on your Projectname and rename it to your new project name
  • go to your project properties and adjust it, coz everything has gone and you need to make a new Debug Profile Profile to Create
  • All dependencies have now an exclamation mark - restart visual studio
  • Clean your solution and Run it and it should work :)

How do you check if a string is not equal to an object or other string value in java?

you'll want to use && to see that it is not equal to "AM" AND not equal to "PM"

if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) {
    System.out.println("Sorry, incorrect input.");
    System.exit(1);
}

to be clear you can also do

if(!(TimeOfDayStringQ.equals("AM") || TimeOfDayStringQ.equals("PM"))){
    System.out.println("Sorry, incorrect input.");
    System.exit(1);
}

to have the not (one or the other) phrase in the code (remember the (silent) brackets)

Create a text file for download on-the-fly

<?php

    header('Content-type: text/plain');
    header('Content-Disposition: attachment;
            filename="<name for the created file>"');
    /*
    assign file content to a PHP Variable $content
    */
    echo $content;
?>

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

Something a bit more functional (easy to use anywhere):

function strip_carriage_returns($string)
{
    return str_replace(array("\n\r", "\n", "\r"), '', $string);
}

Using PHP_EOL as the search replacement parameter is also a good idea! Kudos.

Apache: Restrict access to specific source IP inside virtual host

In Apache 2.4, the authorization configuration syntax has changed, and the Order, Deny or Allow directives should no longer be used.

The new way to do this would be:

<VirtualHost *:8080>
    <Location />
        Require ip 192.168.1.0
    </Location>
    ...
</VirtualHost>

Further examples using the new syntax can be found in the Apache documentation: Upgrading to 2.4 from 2.2

Can't use System.Windows.Forms

may be necesssary, unreference system.windows.forms and reference again.

jquery: change the URL address without redirecting?

NOTE: history.pushState() is now supported - see other answers.

You cannot change the whole url without redirecting, what you can do instead is change the hash.

The hash is the part of the url that goes after the # symbol. That was initially intended to direct you (locally) to sections of your HTML document, but you can read and modify it through javascript to use it somewhat like a global variable.


If applied well, this technique is useful in two ways:

  1. the browser history will remember each different step you took (since the url+hash changed)
  2. you can have an address which links not only to a particular html document, but also gives your javascript a clue about what to do. That means you end up pointing to a state inside your web app.

To change the hash you can do:

document.location.hash = "show_picture";

To watch for hash changes you have to do something like:

window.onhashchange = function(){
    var what_to_do = document.location.hash;    
    if (what_to_do=="#show_picture")
        show_picture();
}

Of course the hash is just a string, so you can do pretty much what you like with it. For example you can put a whole object there if you use JSON to stringify it.

There are very good JQuery libraries to do advanced things with that.

Bypass popup blocker on window.open when JQuery event.preventDefault() is set

I am using this method to avoid the popup blocker in my React code. it will work in all other javascript codes also.

When you are making an async call on click event, just open a blank window first and then write the URL in that later when an async call will complete.

const popupWindow = window.open("", "_blank");
popupWindow.document.write("<div>Loading, Plesae wait...</div>")

on async call's success, write the following

popupWindow.document.write(resonse.url)

How to Run a jQuery or JavaScript Before Page Start to Load

Don't use $(document).ready() just put the script directly in the head section of the page. Pages are processed top to bottom so things at the top are processed first.

Python [Errno 98] Address already in use

Yes, it is intended. Here you can read detailed explanation. It is possible to override this behavior by setting SO_REUSEADDR option on a socket. For example:

sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

Checking if jquery is loaded using Javascript

As per this link:

if (typeof jQuery == 'undefined') {
    // jQuery IS NOT loaded, do stuff here.
}


there are a few more in comments of the link as well like,

if (typeof jQuery == 'function') {...}

//or

if (typeof $== 'function') {...}

// or

if (jQuery) {
    alert("jquery is loaded");
} else {
    alert("Not loaded");
}


Hope this covers most of the good ways to get this thing done!!

SQL to search objects, including stored procedures, in Oracle

i'm not sure if i understand you, but to query the source code of your triggers, procedures, package and functions you can try with the "user_source" table.

select * from user_source

How to remove trailing whitespaces with sed?

At least on Mountain Lion, Viktor's answer will also remove the character 't' when it is at the end of a line. The following fixes that issue:

sed -i '' -e's/[[:space:]]*$//' "$1"

What is PECS (Producer Extends Consumer Super)?

The principles behind this in computer science is called

  • Covariance: ? extends MyClass,
  • Contravariance: ? super MyClass and
  • Invariance/non-variance: MyClass

The picture below should explain the concept. Picture courtesy: Andrey Tyukin

Covariance vs Contravariance

How to parse JSON to receive a Date object in JavaScript?

The answer to this question is, use nuget to obtain JSON.NET then use this inside your JsonResult method:

JsonConvert.SerializeObject(/* JSON OBJECT TO SEND TO VIEW */);

inside your view simple do this in javascript:

JSON.parse(/* Converted JSON object */)

If it is an ajax call:

var request = $.ajax({ url: "@Url.Action("SomeAjaxAction", "SomeController")", dataType: "json"});
request.done(function (data, result) { var safe = JSON.parse(data); var date = new Date(safe.date); });

Once JSON.parse has been called, you can put the JSON date into a new Date instance because JsonConvert creates a proper ISO time instance

How do I revert an SVN commit?

I tried the above, (svn merge) and you're right, it does jack. However

svn update -r <revision> <target> [-R]

seems to work, but isn't permanent (my svn is simply showing an old revision). So I had to

mv <target> <target backup>
svn update <target>
mv <target backup> <target>
svn commit -m "Reverted commit on <target>" <target>

In my particular case my target is interfaces/AngelInterface.php. I made changes to the file, committed them, updated the build computer ran the phpdoc compiler and found my changes were a waste of time. svn log interfaces/AngelInterface.php shows my change as r22060 and the previous commit on that file was r22059. So I can svn update -r 22059 interfaces/AngelInterface.php and I end up with code as it was in -r22059 again. Then :-

mv interfaces/AngelInterface.php interfaces/AngelInterface.php~
svn update interfaces/AngelInterface.php
mv interfaces/AngelInterface.php~ interfaces/AngelInterface.php
svn commit -m "reverted -r22060" interfaces/AngelInterface.php

Alternatively I could do the same thing on a directory, by specifying . -R in place of interfaces/AngelInterface.php in all the above.

How to open a file / browse dialog using javascript?

you can't use input.click() directly, but you can call this in other element click event.

html

<input type="file">
<button>Select file</button>

js

var botton = document.querySelector('button');
var input = document.querySelector('input');
botton.addEventListener('click', function (e) {
    input.click();
});

this tell you Using hidden file input elements using the click() method

How do I use cx_freeze?

  • Add import sys as the new topline
  • You misspelled "executables" on the last line.
  • Remove script = on last line.

The code should now look like:

import sys
from cx_Freeze import setup, Executable

setup(
    name = "On Dijkstra's Algorithm",
    version = "3.1",
    description = "A Dijkstra's Algorithm help tool.",
    executables = [Executable("Main.py", base = "Win32GUI")])

Use the command prompt (cmd) to run python setup.py build. (Run this command from the folder containing setup.py.) Notice the build parameter we added at the end of the script call.