Programs & Examples On #Glr

GLR parser ("Generalized Left-to-right Rightmost derivation parser") is an extension of an LR parser algorithm to handle nondeterministic and ambiguous grammars.

Android Studio - Emulator - eglSurfaceAttrib not implemented

I've found the same thing, but only on emulators that have the Use Host GPU setting ticked. Try turning that off, you'll no longer see those warnings (and the emulator will run horribly, horribly slowly..)

In my experience those warnings are harmless. Notice that the "error" is EGL_SUCCESS, which would seem to indicate no error at all!

Android Emulator Error Message: "PANIC: Missing emulator engine program for 'x86' CPUS."

First, check the path you get with which emulator and if you get /usr/local/share/android-sdk/tools/emulator then remove or rename that emulator (it's an old one) and instead use /usr/local/share/android-sdk/emulator/emulator which is the new path.

If you're using Homebrew and installed with brew cask install android-sdk android-studio then you need to:

  1. Verify your .bashrc or .zshrc that you have the correct paths set:
# Remove $HOME/Library/Android paths
# The new way is to use ANDROID_SDK_ROOT
export ANDROID_SDK_ROOT="/usr/local/share/android-sdk"
# For good measure, add old paths to be backwards compatible with any scripts or 
whatnot. And to hopefully decrease confusion:
export ANDROID_HOME=$ANDROID_SDK_ROOT
export ANDROID_NDK_HOME=$ANDROID_SDK_ROOT/ndk-bundle
  1. Then restart your terminal shell, and check your paths are as you expect them:

    set | grep ANDROID

  2. Finally, with correct paths set, you typically need to install the ndk and some tools:

    sdkmanager "ndk-bundle" "cmake;3.10.2.4988404" "lldb;3.1"

    and check the list for other pieces like this sdkmanager --list

I also closed Android Studio, removed the old Android/Sdk folder under my $HOME folder, and restarted Studio, and when it asked where my Sdk had gone, I pasted the Sdk path: /usr/local/share/android-sdk

Saving binary data as file using JavaScript from a browser

Try

_x000D_
_x000D_
let bytes = [65,108,105,99,101,39,115,32,65,100,118,101,110,116,117,114,101];_x000D_
_x000D_
let base64data = btoa(String.fromCharCode.apply(null, bytes));_x000D_
_x000D_
let a = document.createElement('a');_x000D_
a.href = 'data:;base64,' + base64data;_x000D_
a.download = 'binFile.txt'; _x000D_
a.click();
_x000D_
_x000D_
_x000D_

I convert here binary data to base64 (for bigger data conversion use this) - during downloading browser decode it automatically and save raw data in file. 2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop working (probably due to sandbox security restrictions) - but JSFiddle version works - here

Recommended way to save uploaded files in a servlet application

I post my final way of doing it based on the accepted answer:

@SuppressWarnings("serial")
@WebServlet("/")
@MultipartConfig
public final class DataCollectionServlet extends Controller {

    private static final String UPLOAD_LOCATION_PROPERTY_KEY="upload.location";
    private String uploadsDirName;

    @Override
    public void init() throws ServletException {
        super.init();
        uploadsDirName = property(UPLOAD_LOCATION_PROPERTY_KEY);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // ...
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Collection<Part> parts = req.getParts();
        for (Part part : parts) {
            File save = new File(uploadsDirName, getFilename(part) + "_"
                + System.currentTimeMillis());
            final String absolutePath = save.getAbsolutePath();
            log.debug(absolutePath);
            part.write(absolutePath);
            sc.getRequestDispatcher(DATA_COLLECTION_JSP).forward(req, resp);
        }
    }

    // helpers
    private static String getFilename(Part part) {
        // courtesy of BalusC : http://stackoverflow.com/a/2424824/281545
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim()
                        .replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1)
                        .substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }
}

where :

@SuppressWarnings("serial")
class Controller extends HttpServlet {

    static final String DATA_COLLECTION_JSP="/WEB-INF/jsp/data_collection.jsp";
    static ServletContext sc;
    Logger log;
    // private
    // "/WEB-INF/app.properties" also works...
    private static final String PROPERTIES_PATH = "WEB-INF/app.properties";
    private Properties properties;

    @Override
    public void init() throws ServletException {
        super.init();
        // synchronize !
        if (sc == null) sc = getServletContext();
        log = LoggerFactory.getLogger(this.getClass());
        try {
            loadProperties();
        } catch (IOException e) {
            throw new RuntimeException("Can't load properties file", e);
        }
    }

    private void loadProperties() throws IOException {
        try(InputStream is= sc.getResourceAsStream(PROPERTIES_PATH)) {
                if (is == null)
                    throw new RuntimeException("Can't locate properties file");
                properties = new Properties();
                properties.load(is);
        }
    }

    String property(final String key) {
        return properties.getProperty(key);
    }
}

and the /WEB-INF/app.properties :

upload.location=C:/_/

HTH and if you find a bug let me know

How to move div vertically down using CSS

if div.title is a div then put this:

left: 0;
bottom: 0;

RSA Public Key format

Starting from the decoded base64 data of an OpenSSL rsa-ssh Key, i've been able to guess a format:

  • 00 00 00 07: four byte length prefix (7 bytes)
  • 73 73 68 2d 72 73 61: "ssh-rsa"
  • 00 00 00 01: four byte length prefix (1 byte)
  • 25: RSA Exponent (e): 25
  • 00 00 01 00: four byte length prefix (256 bytes)
  • RSA Modulus (n):

    7f 9c 09 8e 8d 39 9e cc d5 03 29 8b c4 78 84 5f
    d9 89 f0 33 df ee 50 6d 5d d0 16 2c 73 cf ed 46 
    dc 7e 44 68 bb 37 69 54 6e 9e f6 f0 c5 c6 c1 d9 
    cb f6 87 78 70 8b 73 93 2f f3 55 d2 d9 13 67 32 
    70 e6 b5 f3 10 4a f5 c3 96 99 c2 92 d0 0f 05 60 
    1c 44 41 62 7f ab d6 15 52 06 5b 14 a7 d8 19 a1 
    90 c6 c1 11 f8 0d 30 fd f5 fc 00 bb a4 ef c9 2d 
    3f 7d 4a eb d2 dc 42 0c 48 b2 5e eb 37 3c 6c a0 
    e4 0a 27 f0 88 c4 e1 8c 33 17 33 61 38 84 a0 bb 
    d0 85 aa 45 40 cb 37 14 bf 7a 76 27 4a af f4 1b 
    ad f0 75 59 3e ac df cd fc 48 46 97 7e 06 6f 2d 
    e7 f5 60 1d b1 99 f8 5b 4f d3 97 14 4d c5 5e f8 
    76 50 f0 5f 37 e7 df 13 b8 a2 6b 24 1f ff 65 d1 
    fb c8 f8 37 86 d6 df 40 e2 3e d3 90 2c 65 2b 1f 
    5c b9 5f fa e9 35 93 65 59 6d be 8c 62 31 a9 9b 
    60 5a 0e e5 4f 2d e6 5f 2e 71 f3 7e 92 8f fe 8b
    

The closest validation of my theory i can find it from RFC 4253:

The "ssh-rsa" key format has the following specific encoding:

  string    "ssh-rsa"
  mpint     e
  mpint     n

Here the 'e' and 'n' parameters form the signature key blob.

But it doesn't explain the length prefixes.


Taking the random RSA PUBLIC KEY i found (in the question), and decoding the base64 into hex:

30 82 01 0a 02 82 01 01 00 fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68 
e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e 
11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d 
dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80 
fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94 
23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0 
9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3 
4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd 
41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e 
97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f 
fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a 
63 02 03 01 00 01

From RFC3447 - Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1:

A.1.1 RSA public key syntax

An RSA public key should be represented with the ASN.1 type RSAPublicKey:

  RSAPublicKey ::= SEQUENCE {
     modulus           INTEGER,  -- n
     publicExponent    INTEGER   -- e
  }

The fields of type RSAPublicKey have the following meanings:

  • modulus is the RSA modulus n.
  • publicExponent is the RSA public exponent e.

Using Microsoft's excellent (and the only real) ASN.1 documentation:

30 82 01 0a       ;SEQUENCE (0x010A bytes: 266 bytes)
|  02 82 01 01    ;INTEGER  (0x0101 bytes: 257 bytes)
|  |  00          ;leading zero because high-bit, but number is positive
|  |  fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68 
|  |  e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e 
|  |  11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d 
|  |  dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80 
|  |  fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94 
|  |  23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0 
|  |  9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3 
|  |  4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd 
|  |  41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e 
|  |  97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f 
|  |  fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a 
|  |  63 
|  02 03          ;INTEGER (3 bytes)
|     01 00 01

giving the public key modulus and exponent:

  • modulus = 0xfb1199ff0733f6e805a4fd3b36ca68...837a63
  • exponent = 65,537

Update: My expanded form of this answer in another question

Using textures in THREE.js

In version r75 of three.js, you should use:

var loader = new THREE.TextureLoader();
loader.load('texture.png', function ( texture ) {
  var geometry = new THREE.SphereGeometry(1000, 20, 20);
  var material = new THREE.MeshBasicMaterial({map: texture, overdraw: 0.5});
  var mesh = new THREE.Mesh(geometry, material);
  scene.add(mesh);
});

IE9 JavaScript error: SCRIPT5007: Unable to get value of the property 'ui': object is null or undefined

I have written code that sniffs IE4 or greater and is currently functioning perfectly in sites for my company's clients, as well as my own personal sites.

Include the following enumerated constant and function variables into a javascript include file on your page...

//methods
var BrowserTypes = {
    Unknown: 0,
    FireFox: 1,
    Chrome: 2,
    Safari: 3,
    IE: 4,
    IE7: 5,
    IE8: 6,
    IE9: 7,
    IE10: 8,
    IE11: 8,
    IE12: 8
};

var Browser = function () {
    try {
        //declares
        var type;
        var version;
        var sVersion;

        //process
        switch (navigator.appName.toLowerCase()) {
            case "microsoft internet explorer":
                type = BrowserTypes.IE;
                sVersion = navigator.appVersion.substring(navigator.appVersion.indexOf('MSIE') + 5, navigator.appVersion.length);
                version = parseFloat(sVersion.split(";")[0]);
                switch (parseInt(version)) {
                    case 7:
                        type = BrowserTypes.IE7;
                        break;
                    case 8:
                        type = BrowserTypes.IE8;
                        break;
                    case 9:
                        type = BrowserTypes.IE9;
                        break;
                    case 10:
                        type = BrowserTypes.IE10;
                        break;
                    case 11:
                        type = BrowserTypes.IE11;
                        break;
                    case 12:
                        type = BrowserTypes.IE12;
                        break;
                }
                break;
            case "netscape":
                if (navigator.userAgent.toLowerCase().indexOf("chrome") > -1) { type = BrowserTypes.Chrome; }
                else { if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) { type = BrowserTypes.FireFox } };
                break;
            default:
                type = BrowserTypes.Unknown;
                break;
        }

        //returns
        return type;
    } catch (ex) {
    }
};

Then all you have to do is use any conditional functionality such as...

ie. value = (Browser() >= BrowserTypes.IE) ? node.text : node.textContent;

or WindowWidth = (((Browser() >= BrowserTypes.IE9) || (Browser() < BrowserTypes.IE)) ? window.innerWidth : document.documentElement.clientWidth);

or sJSON = (Browser() >= BrowserTypes.IE) ? xmlElement.text : xmlElement.textContent;

Get the idea? Hope this helps.

Oh, you might want to keep it in mind to QA the Browser() function after IE10 is released, just to verify they didn't change the rules.

Can't create handler inside thread which has not called Looper.prepare()

All the answers above are correct, but I think this is the easiest example possible:

public class ExampleActivity extends Activity {
    private Handler handler;
    private ProgressBar progress;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        progress = (ProgressBar) findViewById(R.id.progressBar1);
        handler = new Handler();
    }

    public void clickAButton(View view) {
        // Do something that takes a while
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                handler.post(new Runnable() { // This thread runs in the UI
                    @Override
                    public void run() {
                        progress.setProgress("anything"); // Update the UI
                    }
                });
            }
        };
        new Thread(runnable).start();
    }
}

What this does is update a progress bar in the UI thread from a completely different thread passed through the post() method of the handler declared in the activity.

Hope it helps!

Python base64 data decode

i used chardet to detect possible encoding of this data ( if its text ), but get {'confidence': 0.0, 'encoding': None}. Then i tried to use pickle.load and get nothing again. I tried to save this as file , test many different formats and failed here too. Maybe you tell us what type have this 16512 bytes of mysterious data?

Delete data with foreign key in SQL Server table

You can disable and re-enable the foreign key constraints before and after deleting:

alter table MyOtherTable nocheck constraint all
delete from MyTable
alter table MyOtherTable check constraint all

How do I detect if software keyboard is visible on Android Device or not?

There is a direct method to find this out. And, it does not require the layout changes.
So it works in immersive fullscreen mode, too.
But, unfortunately, it does not work on all devices. So you have to test it with your device(s).

The trick is that you try to hide or show the soft keyboard and capture the result of that try.
If it works correct then the keyboard is not really shown or hidden. We just ask for the state.

To stay up-to-date, you simply repeat this operation, e.g. every 200 milliseconds, using a Handler.

The implementation below does just a single check.
If you do multiple checks, then you should enable all the (_keyboardVisible) tests.

public interface OnKeyboardShowHide
{
    void    onShowKeyboard( Object param );
    void    onHideKeyboard( Object param );
}

private static Handler      _keyboardHandler    = new Handler();
private boolean             _keyboardVisible    = false;
private OnKeyboardShowHide  _keyboardCallback;
private Object              _keyboardCallbackParam;

public void start( OnKeyboardShowHide callback, Object callbackParam )
{
    _keyboardCallback      = callback;
    _keyboardCallbackParam = callbackParam;
    //
    View view = getCurrentFocus();
    if (view != null)
    {
        InputMethodManager imm = (InputMethodManager) getSystemService( Activity.INPUT_METHOD_SERVICE );
        imm.hideSoftInputFromWindow( view.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY, _keyboardResultReceiver );
        imm.showSoftInput( view, InputMethodManager.SHOW_IMPLICIT, _keyboardResultReceiver );
    }
    else // if (_keyboardVisible)
    {
        _keyboardVisible = false;
        _keyboardCallback.onHideKeyboard( _keyboardCallbackParam );
    }
}

private ResultReceiver      _keyboardResultReceiver = new ResultReceiver( _keyboardHandler )
{
    @Override
    protected void onReceiveResult( int resultCode, Bundle resultData )
    {
        switch (resultCode)
        {
            case InputMethodManager.RESULT_SHOWN :
            case InputMethodManager.RESULT_UNCHANGED_SHOWN :
                // if (!_keyboardVisible)
                {
                    _keyboardVisible = true;
                    _keyboardCallback.onShowKeyboard( _keyboardCallbackParam );
                }
                break;
            case InputMethodManager.RESULT_HIDDEN :
            case InputMethodManager.RESULT_UNCHANGED_HIDDEN :
                // if (_keyboardVisible)
                {
                    _keyboardVisible = false;
                    _keyboardCallback.onHideKeyboard( _keyboardCallbackParam );
                }
                break;
        }
    }
};

Python - Count elements in list

len()

>>> someList=[]
>>> print len(someList)
0

Cannot install packages inside docker Ubuntu image

I found that mounting a local volume over /tmp can cause permission issues when the "apt-get update" runs, which prevents the package cache from being populated. Hopefully, this isn't something most people do, but it's something else to look for if you see this issue.

Is there a way to collapse all code blocks in Eclipse?

In addition to the hotkey, if you right click in the gutter where you see the +/-, there is a context menu item 'Folding.' Opening the submenu associated with this, you can see a 'Collapse All' item. this will also do what you wish.

replace anchor text with jquery

Try this, in case of id

$("#YourId").text('Your text');

OR this, in case of class

$(".YourClassName").text('Your text');

How to run a Maven project from Eclipse?

Your Maven project doesn't seem to be configured as a Eclipse Java project, that is the Java nature is missing (the little 'J' in the project icon).

To enable this, the <packaging> element in your pom.xml should be jar (or similar).

Then, right-click the project and select Maven > Update Project Configuration

For this to work, you need to have m2eclipse installed. But since you had the _ New ... > New Maven Project_ wizard, I assume you have m2eclipse installed.

Difference between abstraction and encapsulation?

Most answers here focus on OOP but encapsulation begins much earlier:

  • Every function is an encapsulation; in pseudocode:

    point x = { 1, 4 }
    point y = { 23, 42 }
    
    numeric d = distance(x, y)
    

    Here, distance encapsulates the calculation of the (Euclidean) distance between two points in a plane: it hides implementation details. This is encapsulation, pure and simple.

  • Abstraction is the process of generalisation: taking a concrete implementation and making it applicable to different, albeit somewhat related, types of data. The classical example of abstraction is C’s qsort function to sort data:

    The thing about qsort is that it doesn't care about the data it sorts — in fact, it doesn’t know what data it sorts. Rather, its input type is a typeless pointer (void*) which is just C’s way of saying “I don't care about the type of data” (this is also called type erasure). The important point is that the implementation of qsort always stays the same, regardless of data type. The only thing that has to change is the compare function, which differs from data type to data type. qsort therefore expects the user to provide said compare function as a function argument.

Encapsulation and abstraction go hand in hand so much so that you could make the point that they are truly inseparable. For practical purposes, this is probably true; that said, here’s an encapsulation that’s not much of an abstraction:

class point {
    numeric x
    numeric y
}

We encapsulate the point’s coordinate, but we don’t materially abstract them away, beyond grouping them logically.

And here’s an example of abstraction that’s not encapsulation:

T pi<T> = 3.1415926535

This is a generic variable pi with a given value (p), and the declaration doesn’t care about the exact type of the variable. Admittedly, I’d be hard-pressed to find something like this in real code: abstraction virtually always uses encapsulation. However, the above does actually exist in C++(14), via variable templates (= generic templates for variables); with a slightly more complex syntax, e.g.:

template <typename T> constexpr T pi = T{3.1415926535};

How to suppress warnings globally in an R Script

You could use

options(warn=-1)

But note that turning off warning messages globally might not be a good idea.

To turn warnings back on, use

options(warn=0)

(or whatever your default is for warn, see this answer)

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

The return value def __unicode __ should be similar to the return value of the related models (tables) for correct viewing of "some_field" in django admin panel. You can also use:

def __str__(self):
    return self.some_field

IIS error, Unable to start debugging on the webserver

Check your web config, if there are problems, you may get this error. I had a HTTP to HTTPS redirect in the web config but the application was set to launch as http.

To fix (Local IIS):

  1. Configure a https binding for your application in IIS.
  2. Right click the web project then Properties > Web. Under Servers, set the URL to your https URL.

ExecutorService that interrupts tasks after a timeout

What about this alternative idea :

  • two have two executors :
    • one for :
      • submitting the task, without caring about the timeout of the task
      • adding the Future resulted and the time when it should end to an internal structure
    • one for executing an internal job which is checking the internal structure if some tasks are timeout and if they have to be cancelled.

Small sample is here :

public class AlternativeExecutorService 
{

private final CopyOnWriteArrayList<ListenableFutureTask> futureQueue       = new CopyOnWriteArrayList();
private final ScheduledThreadPoolExecutor                scheduledExecutor = new ScheduledThreadPoolExecutor(1); // used for internal cleaning job
private final ListeningExecutorService                   threadExecutor    = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(5)); // used for
private ScheduledFuture scheduledFuture;
private static final long INTERNAL_JOB_CLEANUP_FREQUENCY = 1000L;

public AlternativeExecutorService()
{
    scheduledFuture = scheduledExecutor.scheduleAtFixedRate(new TimeoutManagerJob(), 0, INTERNAL_JOB_CLEANUP_FREQUENCY, TimeUnit.MILLISECONDS);
}

public void pushTask(OwnTask task)
{
    ListenableFuture<Void> future = threadExecutor.submit(task);  // -> create your Callable
    futureQueue.add(new ListenableFutureTask(future, task, getCurrentMillisecondsTime())); // -> store the time when the task should end
}

public void shutdownInternalScheduledExecutor()
{
    scheduledFuture.cancel(true);
    scheduledExecutor.shutdownNow();
}

long getCurrentMillisecondsTime()
{
    return Calendar.getInstance().get(Calendar.MILLISECOND);
}

class ListenableFutureTask
{
    private final ListenableFuture<Void> future;
    private final OwnTask                task;
    private final long                   milliSecEndTime;

    private ListenableFutureTask(ListenableFuture<Void> future, OwnTask task, long milliSecStartTime)
    {
        this.future = future;
        this.task = task;
        this.milliSecEndTime = milliSecStartTime + task.getTimeUnit().convert(task.getTimeoutDuration(), TimeUnit.MILLISECONDS);
    }

    ListenableFuture<Void> getFuture()
    {
        return future;
    }

    OwnTask getTask()
    {
        return task;
    }

    long getMilliSecEndTime()
    {
        return milliSecEndTime;
    }
}

class TimeoutManagerJob implements Runnable
{
    CopyOnWriteArrayList<ListenableFutureTask> getCopyOnWriteArrayList()
    {
        return futureQueue;
    }

    @Override
    public void run()
    {
        long currentMileSecValue = getCurrentMillisecondsTime();
        for (ListenableFutureTask futureTask : futureQueue)
        {
            consumeFuture(futureTask, currentMileSecValue);
        }
    }

    private void consumeFuture(ListenableFutureTask futureTask, long currentMileSecValue)
    {
        ListenableFuture<Void> future = futureTask.getFuture();
        boolean isTimeout = futureTask.getMilliSecEndTime() >= currentMileSecValue;
        if (isTimeout)
        {
            if (!future.isDone())
            {
                future.cancel(true);
            }
            futureQueue.remove(futureTask);
        }
    }
}

class OwnTask implements Callable<Void>
{
    private long     timeoutDuration;
    private TimeUnit timeUnit;

    OwnTask(long timeoutDuration, TimeUnit timeUnit)
    {
        this.timeoutDuration = timeoutDuration;
        this.timeUnit = timeUnit;
    }

    @Override
    public Void call() throws Exception
    {
        // do logic
        return null;
    }

    public long getTimeoutDuration()
    {
        return timeoutDuration;
    }

    public TimeUnit getTimeUnit()
    {
        return timeUnit;
    }
}
}

Convert .class to .java

Invoking javap to read the bytecode

The javap command takes class-names without the .class extension. Try

javap -c ClassName

Converting .class files back to .java files

javap will however not give you the implementations of the methods in java-syntax. It will at most give it to you in JVM bytecode format.

To actually decompile (i.e., do the reverse of javac) you will have to use proper decompiler. See for instance the following related question:

INNER JOIN same table

I think the problem is in your JOIN condition.

SELECT user.user_fname,
       user.user_lname,
       parent.user_fname,
       parent.user_lname
FROM users AS user
JOIN users AS parent 
  ON parent.user_id = user.user_parent_id
WHERE user.user_id = $_GET[id]

Edit: You should probably use LEFT JOIN if there are users with no parents.

ALTER table - adding AUTOINCREMENT in MySQL

ALTER TABLE `ALLITEMS`
    CHANGE COLUMN `itemid` `itemid` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT;

Which equals operator (== vs ===) should be used in JavaScript comparisons?

Why == is so unpredictable?

What do you get when you compare an empty string "" with the number zero 0?

true

Yep, that's right according to == an empty string and the number zero are the same time.

And it doesn't end there, here's another one:

'0' == false // true

Things get really weird with arrays.

[1] == true // true
[] == false // true
[[]] == false // true
[0] == false // true

Then weirder with strings

[1,2,3] == '1,2,3' // true - REALLY?!
'\r\n\t' == 0 // true - Come on!

It get's worse:

When is equal not equal?

let A = ''  // empty string
let B = 0   // zero
let C = '0' // zero string

A == B // true - ok... 
B == C // true - so far so good...
A == C // **FALSE** - Plot twist!

Let me say that again:

(A == B) && (B == C) // true
(A == C) // **FALSE**

And this is just the crazy stuff you get with primitives.

It's a whole new level of crazy when you use == with objects.

At this point your probably wondering...

Why does this happen?

Well it's because unlike "triple equals" (===) which just checks if two values are the same.

== does a whole bunch of other stuff.

It has special handling for functions, special handling for nulls, undefined, strings, you name it.

It get's pretty wacky.

In fact, if you tried to write a function that does what == does it would look something like this:

function isEqual(x, y) { // if `==` were a function
    if(typeof y === typeof x) return y === x;
    // treat null and undefined the same
    var xIsNothing = (y === undefined) || (y === null);
    var yIsNothing = (x === undefined) || (x === null);

    if(xIsNothing || yIsNothing) return (xIsNothing && yIsNothing);

    if(typeof y === "function" || typeof x === "function") {
        // if either value is a string 
        // convert the function into a string and compare
        if(typeof x === "string") {
            return x === y.toString();
        } else if(typeof y === "string") {
            return x.toString() === y;
        } 
        return false;
    }

    if(typeof x === "object") x = toPrimitive(x);
    if(typeof y === "object") y = toPrimitive(y);
    if(typeof y === typeof x) return y === x;

    // convert x and y into numbers if they are not already use the "+" trick
    if(typeof x !== "number") x = +x;
    if(typeof y !== "number") y = +y;
    // actually the real `==` is even more complicated than this, especially in ES6
    return x === y;
}

function toPrimitive(obj) {
    var value = obj.valueOf();
    if(obj !== value) return value;
    return obj.toString();
}

So what does this mean?

It means == is complicated.

Because it's complicated it's hard to know what's going to happen when you use it.

Which means you could end up with bugs.

So the moral of the story is...

Make your life less complicated.

Use === instead of ==.

The End.

How to set a default Value of a UIPickerView

You have to send - (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated to the picker view before it appears. The documentation states that the method selectedRowInComp... will give -1, thus it is possible that the picker view is in a state with no selected row. It turns out to be in that state when created.

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

IOException: read failed, socket might closed - Bluetooth on Android 4.3

Well, I have actually found the problem.

The most people who try to make a connection using socket.Connect(); get an exception called Java.IO.IOException: read failed, socket might closed, read ret: -1.

In some cases it also depends on your Bluetooth device, because there are two different types of Bluetooth, namely BLE (low energy) and Classic.

If you want to check the type of your Bluetooth device is, here's the code:

        String checkType;
        var listDevices = BluetoothAdapter.BondedDevices;
        if (listDevices.Count > 0)
        {
            foreach (var btDevice in listDevices)
            {
                if(btDevice.Name == "MOCUTE-032_B52-CA7E")
                {
                    checkType = btDevice.Type.ToString();
                    Console.WriteLine(checkType);
                }
            }
        }

I've been trying for days to solve the problem, but since today I have found the problem. The solution from @matthes has unfortunately still a few issues as he said already, but here's my solution.

At the moment I work in Xamarin Android, but this should also work for other platforms.

SOLUTION

If there is more than one paired device, then you should remove the other paired devices. So keep only the one that you want to connect (see the right image).

enter image description here enter image description here

In the left image you see that I have two paired devices, namely "MOCUTE-032_B52-CA7E" and "Blue Easy". That's the issue, but I have no idea why that problem occurs. Maybe the Bluetooth protocol is trying to get some information from another Bluetooth device.

However, the socket.Connect(); works great right now, without any problems. So I just wanted to share this, because that error is really annoying.

Good luck!

Dynamic tabs with user-click chosen components

update

Angular 5 StackBlitz example

update

ngComponentOutlet was added to 4.0.0-beta.3

update

There is a NgComponentOutlet work in progress that does something similar https://github.com/angular/angular/pull/11235

RC.7

Plunker example RC.7

// Helper component to add dynamic components
@Component({
  selector: 'dcl-wrapper',
  template: `<div #target></div>`
})
export class DclWrapper {
  @ViewChild('target', {read: ViewContainerRef}) target: ViewContainerRef;
  @Input() type: Type<Component>;
  cmpRef: ComponentRef<Component>;
  private isViewInitialized:boolean = false;

  constructor(private componentFactoryResolver: ComponentFactoryResolver, private compiler: Compiler) {}

  updateComponent() {
    if(!this.isViewInitialized) {
      return;
    }
    if(this.cmpRef) {
      // when the `type` input changes we destroy a previously 
      // created component before creating the new one
      this.cmpRef.destroy();
    }

    let factory = this.componentFactoryResolver.resolveComponentFactory(this.type);
    this.cmpRef = this.target.createComponent(factory)
    // to access the created instance use
    // this.compRef.instance.someProperty = 'someValue';
    // this.compRef.instance.someOutput.subscribe(val => doSomething());
  }

  ngOnChanges() {
    this.updateComponent();
  }

  ngAfterViewInit() {
    this.isViewInitialized = true;
    this.updateComponent();  
  }

  ngOnDestroy() {
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }    
  }
}

Usage example

// Use dcl-wrapper component
@Component({
  selector: 'my-tabs',
  template: `
  <h2>Tabs</h2>
  <div *ngFor="let tab of tabs">
    <dcl-wrapper [type]="tab"></dcl-wrapper>
  </div>
`
})
export class Tabs {
  @Input() tabs;
}
@Component({
  selector: 'my-app',
  template: `
  <h2>Hello {{name}}</h2>
  <my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
  // The list of components to create tabs from
  types = [C3, C1, C2, C3, C3, C1, C1];
}
@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, DclWrapper, Tabs, C1, C2, C3],
  entryComponents: [C1, C2, C3],
  bootstrap: [ App ]
})
export class AppModule {}

See also angular.io DYNAMIC COMPONENT LOADER

older versions xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

This changed again in Angular2 RC.5

I will update the example below but it's the last day before vacation.

This Plunker example demonstrates how to dynamically create components in RC.5

Update - use ViewContainerRef.createComponent()

Because DynamicComponentLoader is deprecated, the approach needs to be update again.

@Component({
  selector: 'dcl-wrapper',
  template: `<div #target></div>`
})
export class DclWrapper {
  @ViewChild('target', {read: ViewContainerRef}) target;
  @Input() type;
  cmpRef:ComponentRef;
  private isViewInitialized:boolean = false;

  constructor(private resolver: ComponentResolver) {}

  updateComponent() {
    if(!this.isViewInitialized) {
      return;
    }
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }
   this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {
      this.cmpRef = this.target.createComponent(factory)
      // to access the created instance use
      // this.compRef.instance.someProperty = 'someValue';
      // this.compRef.instance.someOutput.subscribe(val => doSomething());
    });
  }

  ngOnChanges() {
    this.updateComponent();
  }

  ngAfterViewInit() {
    this.isViewInitialized = true;
    this.updateComponent();  
  }

  ngOnDestroy() {
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }    
  }
}

Plunker example RC.4
Plunker example beta.17

Update - use loadNextToLocation

export class DclWrapper {
  @ViewChild('target', {read: ViewContainerRef}) target;
  @Input() type;
  cmpRef:ComponentRef;
  private isViewInitialized:boolean = false;

  constructor(private dcl:DynamicComponentLoader) {}

  updateComponent() {
    // should be executed every time `type` changes but not before `ngAfterViewInit()` was called 
    // to have `target` initialized
    if(!this.isViewInitialized) {
      return;
    }
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }
    this.dcl.loadNextToLocation(this.type, this.target).then((cmpRef) => {
      this.cmpRef = cmpRef;
    });
  }

  ngOnChanges() {
    this.updateComponent();
  }

  ngAfterViewInit() {
    this.isViewInitialized = true;
    this.updateComponent();  
  }

  ngOnDestroy() {
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }    
  }
}

Plunker example beta.17

original

Not entirely sure from your question what your requirements are but I think this should do what you want.

The Tabs component gets an array of types passed and it creates "tabs" for each item in the array.

@Component({
  selector: 'dcl-wrapper',
  template: `<div #target></div>`
})
export class DclWrapper {
  constructor(private elRef:ElementRef, private dcl:DynamicComponentLoader) {}
  @Input() type;

  ngOnChanges() {
    if(this.cmpRef) {
      this.cmpRef.dispose();
    }
    this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
      this.cmpRef = cmpRef;
    });
  }
}

@Component({
  selector: 'c1',
  template: `<h2>c1</h2>`

})
export class C1 {
}

@Component({
  selector: 'c2',
  template: `<h2>c2</h2>`

})
export class C2 {
}

@Component({
  selector: 'c3',
  template: `<h2>c3</h2>`

})
export class C3 {
}

@Component({
  selector: 'my-tabs',
  directives: [DclWrapper],
  template: `
  <h2>Tabs</h2>
  <div *ngFor="let tab of tabs">
    <dcl-wrapper [type]="tab"></dcl-wrapper>
  </div>
`
})
export class Tabs {
  @Input() tabs;
}


@Component({
  selector: 'my-app',
  directives: [Tabs]
  template: `
  <h2>Hello {{name}}</h2>
  <my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
  types = [C3, C1, C2, C3, C3, C1, C1];
}

Plunker example beta.15 (not based on your Plunker)

There is also a way to pass data along that can be passed to the dynamically created component like (someData would need to be passed like type)

    this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
  cmpRef.instance.someProperty = someData;
  this.cmpRef = cmpRef;
});

There is also some support to use dependency injection with shared services.

For more details see https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html

Creating a segue programmatically

You have to link your code to the UIStoryboard that you're using. Make sure you go into YourViewController in your UIStoryboard, click on the border around it, and then set its identifier field to a NSString that you call in your code.

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" 
                                                     bundle:nil];
YourViewController *yourViewController = 
 (YourViewController *)
  [storyboard instantiateViewControllerWithIdentifier:@"yourViewControllerID"];
[self.navigationController pushViewController:yourViewController animated:YES];

Get the value of input text when enter key pressed

Try this:

<input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>  
<input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>

JS Code

function search(ele) {
    if(event.key === 'Enter') {
        alert(ele.value);        
    }
}

DEMO Link

Java: How to insert CLOB into oracle database

I had similar issue. Changed one of my table column from varchar2 to CLOB. I didn't needed to change any java code. I kept it as setString(..) only so no need to change set method as setClob() etch if you are using following versions ATLEAST of Oracle and jdbc driver.

I tried in In Oracle 11g and driver ojdbc6-11.2.0.4.jar

How to kill all processes with a given partial name?

This is the way:

kill -9 $(pgrep -d' ' -f chrome)

Execute SQL script from command line

Take a look at the sqlcmd utility. It allows you to execute SQL from the command line.

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

It's all in there in the documentation, but the syntax should look something like this:

sqlcmd -U myLogin -P myPassword -S MyServerName -d MyDatabaseName 
    -Q "DROP TABLE MyTable"

What is the --save option for npm install?

The easier (and more awesome) way to add dependencies to your package.json is to do so from the command line, flagging the npm install command with either --save or --save-dev, depending on how you'd like to use that dependency.

Static constant string (class member)

To use that in-class initialization syntax, the constant must be a static const of integral or enumeration type initialized by a constant expression.

This is the restriction. Hence, in this case you need to define variable outside the class. refer answwer from @AndreyT

Drop a temporary table if it exists

Check for the existence by retrieving its object_id:

if object_id('tempdb..##clients_keyword') is not null
    drop table ##clients_keyword

JavaScript + Unicode regexes

Situation for ES 6

The upcoming ECMAScript language specification, edition 6, includes Unicode-aware regular expressions. Support must be enabled with the u modifier on the regex. See Unicode-aware regular expressions in ES6.

Until ES 6 is finished and widely adopted among browser vendors you're still on your own, though. Update: There is now a transpiler named regexpu that translates ES6 Unicode regular expressions into equivalent ES5. It can be used as part of your build process. Try it out online.

Situation for ES 5 and below

Even though JavaScript operates on Unicode strings, it does not implement Unicode-aware character classes and has no concept of POSIX character classes or Unicode blocks/sub-ranges.

Alternative for <blink>

Please try this one and I guarantee that it will work

  <script type="text/javascript">
  function blink() {
  var blinks = document.getElementsByTagName('blink');
  for (var i = blinks.length - 1; i >= 0; i--) {
  var s = blinks[i];
  s.style.visibility = (s.style.visibility === 'visible') ? 'hidden' : 'visible';
}
window.setTimeout(blink, 1000);
}
if (document.addEventListener) document.addEventListener("DOMContentLoaded", blink, false);
else if (window.addEventListener) window.addEventListener("load", blink, false);
else if (window.attachEvent) window.attachEvent("onload", blink);
else window.onload = blink;

Then put this below:

<blink><center> Your text here </blink></div>

How to add url parameters to Django template url tag?

First you need to prepare your url to accept the param in the regex: (urls.py)

url(r'^panel/person/(?P<person_id>[0-9]+)$', 'apps.panel.views.person_form', name='panel_person_form'),

So you use this in your template:

{% url 'panel_person_form' person_id=item.id %}

If you have more than one param, you can change your regex and modify the template using the following:

{% url 'panel_person_form' person_id=item.id group_id=3 %}

cin and getline skipping input

Here, the '\n' left by cin, is creating issues.

do {
    system("cls");
    manageCustomerMenu();
    cin >> choice;               #This cin is leaving a trailing \n
    system("cls");

    switch (choice) {
        case '1':
            createNewCustomer();
            break;

This \n is being consumed by next getline in createNewCustomer(). You should use getline instead -

do {
    system("cls");
    manageCustomerMenu();
    getline(cin, choice)               
    system("cls");

    switch (choice) {
        case '1':
            createNewCustomer();
            break;

I think this would resolve the issue.

What is the best Java email address validation method?

This is the best method:

public static boolean isValidEmail(String enteredEmail){
        String EMAIL_REGIX = "^[\\\\w!#$%&’*+/=?`{|}~^-]+(?:\\\\.[\\\\w!#$%&’*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\\\.)+[a-zA-Z]{2,6}$";
        Pattern pattern = Pattern.compile(EMAIL_REGIX);
        Matcher matcher = pattern.matcher(enteredEmail);
        return ((!enteredEmail.isEmpty()) && (enteredEmail!=null) && (matcher.matches()));
    }

Sources:- http://howtodoinjava.com/2014/11/11/java-regex-validate-email-address/

http://www.rfc-editor.org/rfc/rfc5322.txt

How to replace a string in an existing file in Perl?

$_='~s/blue/red/g';

Uh, what??

Just

s/blue/red/g;

or, if you insist on using a variable (which is not necessary when using $_, but I just want to show the right syntax):

$_ =~ s/blue/red/g;

How to get all elements which name starts with some string?

HTML DOM querySelectorAll() method seems apt here.

W3School Link given here

Syntax (As given in W3School)

document.querySelectorAll(CSS selectors)

So the answer.

document.querySelectorAll("[name^=q1_]")

Fiddle

Edit:

Considering FLX's suggestion adding link to MDN here

How to know the version of pip itself

check two things

pip2 --version   

and

pip3 --version

because the default pip may be anyone of this so it is always better to check both.

Java synchronized block vs. Collections.synchronizedMap

That looks correct to me. If I were to change anything, I would stop using the Collections.synchronizedMap() and synchronize everything the same way, just to make it clearer.

Also, I'd replace

  if (synchronizedMap.containsKey(key)) {
    synchronizedMap.get(key).add(value);
  }
  else {
    List<String> valuesList = new ArrayList<String>();
    valuesList.add(value);
    synchronizedMap.put(key, valuesList);
  }

with

List<String> valuesList = synchronziedMap.get(key);
if (valuesList == null)
{
  valuesList = new ArrayList<String>();
  synchronziedMap.put(key, valuesList);
}
valuesList.add(value);

How do I create a HTTP Client Request with a cookie?

This answer is deprecated, please see @ankitjaininfo's answer below for a more modern solution


Here's how I think you make a POST request with data and a cookie using just the node http library. This example is posting JSON, set your content-type and content-length accordingly if you post different data.

// NB:- node's http client API has changed since this was written
// this code is for 0.4.x
// for 0.6.5+ see http://nodejs.org/docs/v0.6.5/api/http.html#http.request

var http = require('http');

var data = JSON.stringify({ 'important': 'data' });
var cookie = 'something=anything'

var client = http.createClient(80, 'www.example.com');

var headers = {
    'Host': 'www.example.com',
    'Cookie': cookie,
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(data,'utf8')
};

var request = client.request('POST', '/', headers);

// listening to the response is optional, I suppose
request.on('response', function(response) {
  response.on('data', function(chunk) {
    // do what you do
  });
  response.on('end', function() {
    // do what you do
  });
});
// you'd also want to listen for errors in production

request.write(data);

request.end();

What you send in the Cookie value should really depend on what you received from the server. Wikipedia's write-up of this stuff is pretty good: http://en.wikipedia.org/wiki/HTTP_cookie#Cookie_attributes

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

Go to windows -> Preferences -> Java -> Installed JREs

may be jre is already added enter image description here

click on Add -> Standard VM -> Next -> Directory

and browse for the JDK in my case path was C:\Program Files\Java\jdk1.8.0_111

then Click on finish.

you will see window like thisenter image description here

select JDK -> Apply -> Ok

And You are done.

How to get json key and value in javascript?

For getting key

var a = {"a":"1","b":"2"};
var keys = []
for(var k in a){
  keys.push(k)
}

For getting value.

var a = {"a":"1","b":"2"};
var values = []
for(var k in a){
  values.push(a[k]);
}

Convert DataFrame column type from string to datetime, dd/mm/yyyy format

The easiest way is to use to_datetime:

df['col'] = pd.to_datetime(df['col'])

It also offers a dayfirst argument for European times (but beware this isn't strict).

Here it is in action:

In [11]: pd.to_datetime(pd.Series(['05/23/2005']))
Out[11]:
0   2005-05-23 00:00:00
dtype: datetime64[ns]

You can pass a specific format:

In [12]: pd.to_datetime(pd.Series(['05/23/2005']), format="%m/%d/%Y")
Out[12]:
0   2005-05-23
dtype: datetime64[ns]

HTML CSS Button Positioning

try changing that line-height change to a margin-top or padding-top change instead

#btnhome:active{
margin-top : 25px;
}

Edit: You could also try adding a span inside the button

<div id="header">           
    <button id="btnhome"><span>Home</span></button>          
    <button id="btnabout">About</button>
    <button id="btncontact">Contact</button>
    <button id="btnsup">Help Us</button>           
</div>

Then style that

#btnhome span:active { padding-top:25px;}

Spring RestTemplate GET with parameters

To easily manipulate URLs / path / params / etc., you can use Spring's UriComponentsBuilder class. It's cleaner than manually concatenating strings and it takes care of the URL encoding for you:

HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
        .queryParam("msisdn", msisdn)
        .queryParam("email", email)
        .queryParam("clientVersion", clientVersion)
        .queryParam("clientType", clientType)
        .queryParam("issuerName", issuerName)
        .queryParam("applicationName", applicationName);

HttpEntity<?> entity = new HttpEntity<>(headers);

HttpEntity<String> response = restTemplate.exchange(
        builder.toUriString(), 
        HttpMethod.GET, 
        entity, 
        String.class);

Android Debug Bridge (adb) device - no permissions

The answer is weaved amongst the various posts here, I'll so my best, but it looks like a really simple and obvious reason.

1) is that there usually is a "user" variable in the udev rule some thing like USER="your_user" probably right after the GROUP="plugdev"

2) You need to use the correct SYSFS{idVendor}==”####" and SYSFS{idProduct}=="####" values for your device/s. If you have devices from more than one manufacture, say like one from Samsung and one from HTC, then you need to have an entry(rule) for each vendor, not an entry for each device but for each different vendor you will use, so you need an entry for HTC and Samsung. It looks like you have your entry for Samsung now you need another. Remember the USER="your_user". Use 'lsusb' like Robert Seimer suggests to find the idVendor and idProduct, they are usually some numbers and letters in this format X#X#:#X#X I think the first one is the idVendor and the second idProduct but your going to need to do this for each brand of phone/tablet you have.

3) I havent figured out how 51-adb.rules and 99-adb.rules are different or why.

4) maybe try adding "plugdev" group to your user with "usermod -a -G plugdev your_user", Try that at your own risk, though I don't thinks it anyriskier than launching a gui as root but I believe if necessary you should at least use "gksudo eclipse" instead.

I hope that helped clearify some things, the udev rules syntax is a bit of a mystery to me aswell, but from what I hear it can be different for different systems so try some things out, one ate a time, and note what change works.

Magento How to debug blank white screen

Whenever this happens the first thing I check is the PHP memory limit.

Magento overrides the normal error handler with it's own, but when the error is "Out of memory" that custom handler cannot run, so nothing is seen.

Add new column in Pandas DataFrame Python

The easiest way that I found for adding a column to a DataFrame was to use the "add" function. Here's a snippet of code, also with the output to a CSV file. Note that including the "columns" argument allows you to set the name of the column (which happens to be the same as the name of the np.array that I used as the source of the data).

#  now to create a PANDAS data frame
df = pd.DataFrame(data = FF_maxRSSBasal, columns=['FF_maxRSSBasal'])
# from here on, we use the trick of creating a new dataframe and then "add"ing it
df2 = pd.DataFrame(data = FF_maxRSSPrism, columns=['FF_maxRSSPrism'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = FF_maxRSSPyramidal, columns=['FF_maxRSSPyramidal'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_strainE22, columns=['deltaFF_strainE22'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = scaled, columns=['scaled'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_orientation, columns=['deltaFF_orientation'])
df = df.add( df2, fill_value=0 )
#print(df)
df.to_csv('FF_data_frame.csv')

How to debug a referenced dll (having pdb)

When you want to set a breakpoint in source code of a referenced dll, first make sure that you have a pdb file available for it. Then you can just open the related source code file and set a breakpoint over there. The source file does not need to be part of your solution. As explained in How can I set a breakpoint in referenced code in Visual Studio?

You can review your breakpoints through the breakpoints window, available via Debug -> Windows -> Breakpoints.

This approach has the benefit that you are not required to add an existing project to your solution just for debugging purposes as leaving it out has saved me a lot of build time. Evidently, building a solution with only one project in it is much faster than building a solution with lots of them.

nodemon command is not recognized in terminal for node js server

I was facing the same issue. I had installed nodemon as a dev-dependency and when I tried to start the server it gave the message that

nodemon is not recognized as internal or external command, operable program or batch file

Then I installed it globally and tried to start the server and it worked!

npm install -g nodemon

How do I create a readable diff of two spreadsheets using git diff?

Do you use TortoiseSVN for doing your commits and updates in subversion? It has a diff tool, however comparing Excel files is still not really user friendly. In my environment (Win XP, Office 2007), it opens up two excel files for side by side comparison.

Right click document > Tortoise SVN > Show Log > select revision > right click for "Compare with working copy".

Pretty git branch graphs

Although sometimes I use gitg, always come back to command line:

[alias]
    #quick look at all repo
    loggsa = log --color --date-order --graph --oneline --decorate --simplify-by-decoration --all
    #quick look at active branch (or refs pointed)
    loggs  = log --color --date-order --graph --oneline --decorate --simplify-by-decoration
    #extend look at all repo
    logga  = log --color --date-order --graph --oneline --decorate --all
    #extend look at active branch
    logg   = log --color --date-order --graph --oneline --decorate
    #Look with date
    logda  = log --color --date-order --date=local --graph --format=\"%C(auto)%h%Creset %C(blue bold)%ad%Creset %C(auto)%d%Creset %s\" --all
    logd   = log --color --date-order --date=local --graph --format=\"%C(auto)%h%Creset %C(blue bold)%ad%Creset %C(auto)%d%Creset %s\"        
    #Look with relative date
    logdra = log --color --date-order --graph --format=\"%C(auto)%h%Creset %C(blue bold)%ar%Creset %C(auto)%d%Creset %s\" --all
    logdr = log --color --date-order --graph --format=\"%C(auto)%h%Creset %C(blue bold)%ar%Creset %C(auto)%d%Creset %s\"  

    loga   = log --graph --color --decorate --all

    # For repos without subject body commits (vim repo, git-svn clones)
    logt  = log --graph --color --format=\"%C(auto)%h %d %<|(100,trunc) %s\"
    logta  = log --graph --color --format=\"%C(auto)%h %d %<|(100,trunc) %s\" --all        
    logtsa = log --graph --color --format=\"%C(auto)%h %d %<|(100,trunc) %s\" --all --simplify-by-decoration 

As you can see is almost a keystroke saving aliases, based on:

  • --color: clear look
  • --graph: visualize parents
  • --date-order: most understandable look at repo
  • --decorate: who is who
  • --oneline: Many times all you need to know about a commit
  • --simplify-by-decoration: basic for a first look (just tags, relevant merges, branches)
  • --all: saving keystrokes with all alias with and without this option
  • --date=relative (%ar): Understand activity in repo (sometimes a branch is few commits near master but months ago from him)

See in recent version of git (1.8.5 and above) you can benefit from %C(auto) in decorate placeholder %d

From here all you need is a good understand of gitrevisions to filter whatever you need (something like master..develop, where --simplify-merges could help with long term branches)

The power behind command line is the quickly config based on your needs (understand a repo isn't a unique key log configuration, so adding --numstat, or --raw, or --name-status is sometimes needed. Here git log and aliases are fast, powerful and (with time) the prettiest graph you can achieved. Even more, with output showed by default through a pager (say less) you can always search quickly inside results. Not convinced? You can always parse the result with projects like gitgraph

How to upload files on server folder using jsp

public class FileUploadExample extends HttpServlet {
     protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);

            if (isMultipart) {
                // Create a factory for disk-based file items
                FileItemFactory factory = new DiskFileItemFactory();

                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);

                try {
                    // Parse the request
                    List items = upload.parseRequest(request);
                    Iterator iterator = items.iterator();
                    while (iterator.hasNext()) {
                        FileItem item = (FileItem) iterator.next();
                        if (!item.isFormField()) {
                            String fileName = item.getName();    
                            String root = getServletContext().getRealPath("/");
                            File path = new File(root + "/uploads");
                            if (!path.exists()) {
                                boolean status = path.mkdirs();
                            }

                            File uploadedFile = new File(path + "/" + fileName);
                            System.out.println(uploadedFile.getAbsolutePath());
                            item.write(uploadedFile);
                        }
                    }
                } catch (FileUploadException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

}

Remove ':hover' CSS behavior from element

add a new .css class:

#test.nohover:hover { border: 0 }

and

<div id="test" class="nohover">blah</div>

The more "specific" css rule wins, so this border:0 version will override the generic one specified elsewhere.

Visual Studio Code Automatic Imports

If you are using angular, check that the tsconfig.json does not contain errors. (in the problems terminal)

For some reason I doubled these lines, and it didn't work for me

{
  "module": "esnext",
  "moduleResolution": "node",
}

PHP Warning: Invalid argument supplied for foreach()

You should check that what you are passing to foreach is an array by using the is_array function

If you are not sure it's going to be an array you can always check using the following PHP example code:

if (is_array($variable)) {

  foreach ($variable as $item) {
   //do something
  }
}

Excel formula to display ONLY month and year?

There are a number of ways to go about this. One way would be to enter the date 8/1/2013 manually in the first cell (say A1 for example's sake) and then in B1 type the following formula (and then drag it across):

=DATE(YEAR(A1),MONTH(A1)+1,1)

Since you only want to see month and year, you can format accordingly using the different custom date formats available.

The format you're looking for is YY-Mmm.

Laravel stylesheets and javascript don't load for non-base routes

i suggest you put it on route filter before on {project}/application/routes.php

Route::filter('before', function()
{
    // Do stuff before every request to your application...    
    Asset::add('jquery', 'js/jquery-2.0.0.min.js');
    Asset::add('style', 'template/style.css');
    Asset::add('style2', 'css/style.css');

});

and using blade template engine

{{ Asset::styles() }}
{{ Asset::scripts(); }}

or more on laravel managing assets docs

Why does an image captured using camera intent gets rotated on some devices on Android?

Jason Robinson's answer and Sami Eltamawy answer are excelent.

Just an improvement to complete the aproach, you should use compat ExifInterface.

com.android.support:exifinterface:${lastLibVersion}

You will be able to instantiate the ExifInterface(pior API <24) with InputStream (from ContentResolver) instead of uri paths avoiding "File not found exceptions"

https://android-developers.googleblog.com/2016/12/introducing-the-exifinterface-support-library.html

How can I get a list of Git branches, ordered by most recent commit?

List of Git branch names, ordered by most recent commit…

Expanding on Jakub’s answer and Joe’s tip, the following will strip out the "refs/heads/" so the output only displays the branch names:


Command:

git for-each-ref --count=30 --sort=-committerdate refs/heads/ --format='%(refname:short)'

Result:

Recent Git branches

How to auto generate migrations with Sequelize CLI from Sequelize models?

If you don't want to recreate your model from scratch, you can manually generate a migration file using the following CLI command:

sequelize migration:generate --name [name_of_your_migration]

This will generate a blank skeleton migration file. While it doesn't copy your model structure over to the file, I do find it easier and cleaner than regenerating everything. Note: make sure to run the command from the containing directory of your migrations directory; otherwise the CLI will generate a new migration dir for you

require(vendor/autoload.php): failed to open stream

I was able to resolve by removing composer and reinstalling the proper way. Here is what I did:

I was then able to get composer install to work again. Found my answer at the bottom of this issue: https://github.com/composer/composer/issues/5510

Is it possible that one domain name has multiple corresponding IP addresses?

You can do it. That is what big guys do as well.

First query:

» host google.com 
google.com has address 74.125.232.230
google.com has address 74.125.232.231
google.com has address 74.125.232.232
google.com has address 74.125.232.233
google.com has address 74.125.232.238
google.com has address 74.125.232.224
google.com has address 74.125.232.225
google.com has address 74.125.232.226
google.com has address 74.125.232.227
google.com has address 74.125.232.228
google.com has address 74.125.232.229

Next query:

» host google.com
google.com has address 74.125.232.224
google.com has address 74.125.232.225
google.com has address 74.125.232.226
google.com has address 74.125.232.227
google.com has address 74.125.232.228
google.com has address 74.125.232.229
google.com has address 74.125.232.230
google.com has address 74.125.232.231
google.com has address 74.125.232.232
google.com has address 74.125.232.233
google.com has address 74.125.232.238

As you see, the list of IPs rotated around, but the relative order between two IPs stayed the same.

Update: I see several comments bragging about how DNS round-robin is not convenient for fail-over, so here is the summary: DNS is not for fail-over. So it is obviously not good for fail-over. It was never designed to be a solution for fail-over.

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

I regularly use IntelliJ, PHPStorm and WebStorm. Would love to only use IntelliJ. As pointed out by the vendor the "Open Directory" functionality not being in IntelliJ is painful.

Now for the rub part; I have tried using IntelliJ as my single IDE and have found performance to be terrible compared to the lighter weight versions. Intellisense is almost useless in IntelliJ compared to WebStorm.

"NoClassDefFoundError: Could not initialize class" error

Realised that I was using OpenJDK when I saw this error. Fixed it once I installed the Oracle JDK instead.

How to access the services from RESTful API in my angularjs page?

For instance your json looks like this : {"id":1,"content":"Hello, World!"}

You can access this thru angularjs like so:

angular.module('app', [])
    .controller('myApp', function($scope, $http) {
        $http.get('http://yourapp/api').
            then(function(response) {
                $scope.datafromapi = response.data;
            });
    });

Then on your html you would do it like this:

<!doctype html>
<html ng-app="myApp">
    <head>
        <title>Hello AngularJS</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
        <script src="hello.js"></script>
    </head>

    <body>
        <div ng-controller="myApp">
            <p>The ID is {{datafromapi.id}}</p>
            <p>The content is {{datafromapi.content}}</p>
        </div>
    </body>
</html>

This calls the CDN for angularjs in case you don't want to download them.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="hello.js"></script>

Hope this helps.

Check if my SSL Certificate is SHA1 or SHA2

openssl s_client -connect api.cscglobal.com:443 < /dev/null 2>/dev/null  | openssl x509 -text -in /dev/stdin | grep "Signature Algorithm" | cut -d ":" -f2 | uniq | sed '/^$/d' | sed -e 's/^[ \t]*//'

How to change the Content of a <textarea> with JavaScript

Like this:

document.getElementById('myTextarea').value = '';

or like this in jQuery:

$('#myTextarea').val('');

Where you have

<textarea id="myTextarea" name="something">This text gets removed</textarea>

For all the downvoters and non-believers:

fast way to copy formatting in excel

Does:

Set Sheets("Output").Range("$A$1:$A$500") =  Sheets(sheet_).Range("$A$1:$A$500")

...work? (I don't have Excel in front of me, so can't test.)

How do I get countifs to select all non-blank cells in Excel?

If you are using multiple criteria, and want to count the number of non-blank cells in a particular column, you probably want to look at DCOUNTA.

e.g

  A   B   C   D  E   F   G
1 Dog Cat Cow    Dog Cat
2 x   1          x   1
3 x   2 
4 x   1   nb     Result:
5 x   2   nb     1

Formula in E5: =DCOUNTA(A1:C5,"Cow",E1:F2)

Can media queries resize based on a div element instead of the screen?

This is currently not possible with CSS alone as @BoltClock wrote in the accepted answer, but you can work around that by using JavaScript.

I created a container query (aka element query) prolyfill to solve this kind of issue. It works a bit different than other scripts, so you don’t have to edit the HTML code of your elements. All you have to do is include the script and use it in your CSS like so:

.element:container(width > 99px) {
    /* If its container is at least 100px wide */
}

https://github.com/ausi/cq-prolyfill

PHP to write Tab Characters inside a file?

The tab character is \t. Notice the use of " instead of '.

$chunk = "abc\tdef\tghi";

PHP Strings - Double quoted

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

...

\t horizontal tab (HT or 0x09 (9) in ASCII)


Also, let me recommend the fputcsv() function which is for the purpose of writing CSV files.

How do I trigger a macro to run after a new mail is received in Outlook?

This code will add an event listener to the default local Inbox, then take some action on incoming emails. You need to add that action in the code below.

Private WithEvents Items As Outlook.Items 
Private Sub Application_Startup() 
  Dim olApp As Outlook.Application 
  Dim objNS As Outlook.NameSpace 
  Set olApp = Outlook.Application 
  Set objNS = olApp.GetNamespace("MAPI") 
  ' default local Inbox
  Set Items = objNS.GetDefaultFolder(olFolderInbox).Items 
End Sub
Private Sub Items_ItemAdd(ByVal item As Object) 

  On Error Goto ErrorHandler 
  Dim Msg As Outlook.MailItem 
  If TypeName(item) = "MailItem" Then
    Set Msg = item 
    ' ******************
    ' do something here
    ' ******************
  End If
ProgramExit: 
  Exit Sub
ErrorHandler: 
  MsgBox Err.Number & " - " & Err.Description 
  Resume ProgramExit 
End Sub

After pasting the code in ThisOutlookSession module, you must restart Outlook.

Registry key Error: Java version has value '1.8', but '1.7' is required

After trying more than hundred of tricks, finally got success.

I removed all java.exe, javaw.exe and javaws.exe from my

  1. Windows\System32 and

  2. Windows\SysWOW64 folder. [Try step 2 if you have x64 system (Win 7 64 bits)]

More elegant "ps aux | grep -v grep"

You could use preg_split instead of explode and split on [ ]+ (one or more spaces). But I think in this case you could go with preg_match_all and capturing:

preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];

The pattern matches a space, php, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php as part of a user name but really only as a command.

An alternative to capturing is the "keep" feature of PCRE. If you use \K in the pattern, everything before it is discarded in the match:

preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];

I would use preg_match(). I do something similar for many of my system management scripts. Here is an example:

$test = "user     12052  0.2  0.1 137184 13056 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user     12054  0.2  0.1 137184 13064 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user     12055  0.6  0.1 137844 14220 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user     12057  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user     12058  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user     12059  0.3  0.1 135112 13000 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root     12068  0.0  0.0 106088  1164 pts/1    S+   10:00   0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root     12070  0.0  0.0 103240   828 pts/1    R+   10:00   0:00 grep utilities";

$lines = explode("\n", $test);

foreach($lines as $line){
        if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
                print_r($matches);
        }

}

The above prints:

Array
(
    [0] => .php cust1 cron
    [1] => cust1
)
Array
(
    [0] => .php cust3 cron
    [1] => cust3
)
Array
(
    [0] => .php cust4 cron
    [1] => cust4
)
Array
(
    [0] => .php cust89 cron
    [1] => cust89
)
Array
(
    [0] => .php cust435 cron
    [1] => cust435
)
Array
(
    [0] => .php cust16 cron
    [1] => cust16
)

You can set $test to equal the output from exec. the values you are looking for would be in the if statement under the foreach. $matches[1] will have the custx value.

How do I localize the jQuery UI Datepicker?

I solved it by adding the property data-date-language="it":

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#TxtDaDataDoc_Val').datepicker();_x000D_
});
_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">_x000D_
<link rel="stylesheet" href="/resources/demos/style.css">_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
_x000D_
<div class="form-group col-xs-2 col-sm-2 col-md-2">_x000D_
    <div class="input-group input-append date form-group" _x000D_
        id="TxtDaDataDoc" data-date-language="it">_x000D_
        <input type="text" class="form-control" name="date" _x000D_
               id="TxtDaDataDoc_Val" runat="server" />_x000D_
        <span class="input-group-addon add-on">_x000D_
            <span class="glyphicon glyphicon-calendar"></span>_x000D_
        </span>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

CodeIgniter - accessing $config variable in view

$this->config->item() works fine.

For example, if the config file contains $config['foo'] = 'bar'; then $this->config->item('foo') == 'bar'

Where to place the 'assets' folder in Android Studio?

In android studio you can specify where the source, res, assets folders are located. for each module/app in the build.gradle file you can add something like:

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.1"

    sourceSets {
        main {
            java.srcDirs = ['src']
            assets.srcDirs = ['assets']
            res.srcDirs = ['res']
            manifest.srcFile 'AndroidManifest.xml'
        }
    }
}

use current date as default value for a column

CREATE TABLE Orders(
    O_Id int NOT NULL,
    OrderNo int NOT NULL,
    P_Id int,
    OrderDate date DEFAULT GETDATE() // you can set default constraints while creating the table
)

How do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?

If you want to get the stdout AND know whether the command succeeded or not, just use returnStdout and wrap it in an exception handler:

scripted pipeline

try {
    // Fails with non-zero exit if dir1 does not exist
    def dir1 = sh(script:'ls -la dir1', returnStdout:true).trim()
} catch (Exception ex) {
    println("Unable to read dir1: ${ex}")
}

output:

[Pipeline] sh
[Test-Pipeline] Running shell script
+ ls -la dir1
ls: cannot access dir1: No such file or directory
[Pipeline] echo
unable to read dir1: hudson.AbortException: script returned exit code 2

Unfortunately hudson.AbortException is missing any useful method to obtain that exit status, so if the actual value is required you'd need to parse it out of the message (ugh!)

Contrary to the Javadoc https://javadoc.jenkins-ci.org/hudson/AbortException.html the build is not failed when this exception is caught. It fails when it's not caught!

Update: If you also want the STDERR output from the shell command, Jenkins unfortunately fails to properly support that common use-case. A 2017 ticket JENKINS-44930 is stuck in a state of opinionated ping-pong whilst making no progress towards a solution - please consider adding your upvote to it.

As to a solution now, there could be a couple of possible approaches:

a) Redirect STDERR to STDOUT 2>&1 - but it's then up to you to parse that out of the main output though, and you won't get the output if the command failed - because you're in the exception handler.

b) redirect STDERR to a temporary file (the name of which you prepare earlier) 2>filename (but remember to clean up the file afterwards) - ie. main code becomes:

def stderrfile = 'stderr.out'
try {
    def dir1 = sh(script:"ls -la dir1 2>${stderrfile}", returnStdout:true).trim()
} catch (Exception ex) {
    def errmsg = readFile(stderrfile)
    println("Unable to read dir1: ${ex} - ${errmsg}")
}

c) Go the other way, set returnStatus=true instead, dispense with the exception handler and always capture output to a file, ie:

def outfile = 'stdout.out'
def status = sh(script:"ls -la dir1 >${outfile} 2>&1", returnStatus:true)
def output = readFile(outfile).trim()
if (status == 0) {
    // output is directory listing from stdout
} else {
    // output is error message from stderr
}

Caveat: the above code is Unix/Linux-specific - Windows requires completely different shell commands.

Calculate date/time difference in java

difference-between-two-dates-in-java

Extracted the code from the link

public class TimeDiff {
    /**
     * (For testing purposes)
     *
     */
    public static void main(String[] args) {
        Date d1 = new Date();
        try { Thread.sleep(750); } catch(InterruptedException e) { /* ignore */ }      
        Date d0 = new Date(System.currentTimeMillis() - (1000*60*60*24*3)); // About 3 days ago
        long[] diff = TimeDiff.getTimeDifference(d0, d1);

        System.out.printf("Time difference is %d day(s), %d hour(s), %d minute(s), %d second(s) and %d millisecond(s)\n",
                diff[0], diff[1], diff[2], diff[3], diff[4]);
        System.out.printf("Just the number of days = %d\n",
                TimeDiff.getTimeDifference(d0, d1, TimeDiff.TimeField.DAY));
    }

    /**
     * Calculate the absolute difference between two Date without
     * regard for time offsets
     *
     * @param d1 Date one
     * @param d2 Date two
     * @param field The field we're interested in out of
     * day, hour, minute, second, millisecond
     *
     * @return The value of the required field
     */
    public static long getTimeDifference(Date d1, Date d2, TimeField field) {
        return TimeDiff.getTimeDifference(d1, d2)[field.ordinal()];
    }

    /**
     * Calculate the absolute difference between two Date without
     * regard for time offsets
     *
     * @param d1 Date one
     * @param d2 Date two
     * @return The fields day, hour, minute, second and millisecond
     */
    public static long[] getTimeDifference(Date d1, Date d2) {
        long[] result = new long[5];
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("UTC"));
        cal.setTime(d1);

        long t1 = cal.getTimeInMillis();
        cal.setTime(d2);

        long diff = Math.abs(cal.getTimeInMillis() - t1);
        final int ONE_DAY = 1000 * 60 * 60 * 24;
        final int ONE_HOUR = ONE_DAY / 24;
        final int ONE_MINUTE = ONE_HOUR / 60;
        final int ONE_SECOND = ONE_MINUTE / 60;

        long d = diff / ONE_DAY;
        diff %= ONE_DAY;

        long h = diff / ONE_HOUR;
        diff %= ONE_HOUR;

        long m = diff / ONE_MINUTE;
        diff %= ONE_MINUTE;

        long s = diff / ONE_SECOND;
        long ms = diff % ONE_SECOND;
        result[0] = d;
        result[1] = h;
        result[2] = m;
        result[3] = s;
        result[4] = ms;

        return result;
    }

    public static void printDiffs(long[] diffs) {
        System.out.printf("Days:         %3d\n", diffs[0]);
        System.out.printf("Hours:        %3d\n", diffs[1]);
        System.out.printf("Minutes:      %3d\n", diffs[2]);
        System.out.printf("Seconds:      %3d\n", diffs[3]);
        System.out.printf("Milliseconds: %3d\n", diffs[4]);
    }

    public static enum TimeField {DAY,
        HOUR,
        MINUTE,
        SECOND,
        MILLISECOND;
    }
}

How to call getClass() from a static method in Java?

Suppose there is a Utility class, then sample code would be -

    URL url = Utility.class.getClassLoader().getResource("customLocation/".concat("abc.txt"));

CustomLocation - if any folder structure within resources otherwise remove this string literal.

What is the equivalent of the C# 'var' keyword in Java?

This feature is now available in Java SE 10. The static, type-safe var has finally made it into the java world :)

source: https://www.oracle.com/corporate/pressrelease/Java-10-032018.html

Print to standard printer from Python?

Unfortunately, there is no standard way to print using Python on all platforms. So you'll need to write your own wrapper function to print.

You need to detect the OS your program is running on, then:

For Linux -

import subprocess
lpr =  subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE)
lpr.stdin.write(your_data_here)

For Windows: http://timgolden.me.uk/python/win32_how_do_i/print.html

More resources:

Print PDF document with python's win32print module?

How do I print to the OS's default printer in Python 3 (cross platform)?

How to convert interface{} to string?

To expand on what Peter said: Since you are looking to go from interface{} to string, type assertion will lead to headaches since you need to account for multiple incoming types. You'll have to assert each type possible and verify it is that type before using it.

Using fmt.Sprintf (https://golang.org/pkg/fmt/#Sprintf) automatically handles the interface conversion. Since you know your desired output type is always a string, Sprintf will handle whatever type is behind the interface without a bunch of extra code on your behalf.

gcc-arm-linux-gnueabi command not found

You have installed a toolchain which was compiled for i686 on a box which is running an x86_64 userland.

Use an i686 VM.

What is the total amount of public IPv4 addresses?

Public IP Addresses

https://github.com/stephenlb/geo-ip will generate a list of Valid IP Public Addresses including Localities.

'1.0.0.0/8' to '191.0.0.0/8' are the valid public IP Address range exclusive of the reserved Private IP Addresses as follows:

import iptools
## Private IP Addresses
private_ips = iptools.IpRangeList(
    '0.0.0.0/8',      '10.0.0.0/8',     '100.64.0.0/10', '127.0.0.0/8',
    '169.254.0.0/16', '172.16.0.0/12',  '192.0.0.0/24',  '192.0.2.0/24',
    '192.88.99.0/24', '192.168.0.0/16', '198.18.0.0/15', '198.51.100.0/24',
    '203.0.113.0/24', '224.0.0.0/4',    '240.0.0.0/4',   '255.255.255.255/32'
)

IP Generator

Generates a JSON dump of IP Addresses and associated Geo information. Note that the valid public IP Address range is from '1.0.0.0/8' to '191.0.0.0/8' excluding the reserved Private IP Address ranges shown lower down in this readme.

docker build -t geo-ip .
docker run -e IPRANGE='54.0.0.0/30' geo-ip               ## a few IPs
docker run -e IPRANGE='54.0.0.0/26' geo-ip               ## a few more IPs
docker run -e IPRANGE='54.0.0.0/16' geo-ip               ## a lot more IPs
docker run -e IPRANGE='0.0.0.0/0'   geo-ip               ## ALL IPs ( slooooowwwwww )
docker run -e IPRANGE='0.0.0.0/0'   geo-ip > geo-ip.json ## ALL IPs saved to JSON File
docker run geo-ip 

A little faster option for scanning all valid public addresses:

for i in $(seq 1 191); do \
    docker run -e IPRANGE="$i.0.0.0/8" geo-ip; \
    sleep 1; \ 
done

This prints less than 4,228,250,625 JSON lines to STDOUT. Here is an example of one of the lines:

{"city": "Palo Alto", "ip": "0.0.0.0", "longitude": -122.1274,
 "continent": "North America", "continent_code": "NA",
 "state": "California", "country": "United States", "latitude": 37.418,
 "iso_code": "US", "state_code": "CA", "aso": "PubNub",
 "asn": "11404", "zip_code": "94107"}

Private and Reserved IP Range

The dockerfile in the repo above will exclude non-usable IP addresses following the guide from the wikipedia article: https://en.wikipedia.org/wiki/Reserved_IP_addresses

MaxMind Geo IP

The dockerfile imports a free public Database provided by https://www.maxmind.com/en/home

How can I stop a running MySQL query?

Use mysqladmin to kill the runaway query:

Run the following commands:

mysqladmin -uusername -ppassword pr

Then note down the process id.

mysqladmin -uusername -ppassword kill pid

The runaway query should no longer be consuming resources.

How to use OUTPUT parameter in Stored Procedure

The SQL in your SP is wrong. You probably want

Select @code = RecItemCode from Receipt where RecTransaction = @id

In your statement, you are not setting @code, you are trying to use it for the value of RecItemCode. This would explain your NullReferenceException when you try to use the output parameter, because a value is never assigned to it and you're getting a default null.

The other issue is that your SQL statement if rewritten as

Select @code = RecItemCode, RecUsername from Receipt where RecTransaction = @id

It is mixing variable assignment and data retrieval. This highlights a couple of points. If you need the data that is driving @code in addition to other parts of the data, forget the output parameter and just select the data.

Select RecItemCode, RecUsername from Receipt where RecTransaction = @id

If you just need the code, use the first SQL statement I showed you. On the offhand chance you actually need the output and the data, use two different statements

Select @code = RecItemCode from Receipt where RecTransaction = @id
Select RecItemCode, RecUsername from Receipt where RecTransaction = @id

This should assign your value to the output parameter as well as return two columns of data in a row. However, this strikes me as terribly redundant.

If you write your SP as I have shown at the very top, simply invoke cmd.ExecuteNonQuery(); and then read the output parameter value.


Another issue with your SP and code. In your SP, you have declared @code as varchar. In your code, you specify the parameter type as Int. Either change your SP or your code to make the types consistent.


Also note: If all you are doing is returning a single value, there's another way to do it that does not involve output parameters at all. You could write

 Select RecItemCode from Receipt where RecTransaction = @id

And then use object obj = cmd.ExecuteScalar(); to get the result, no need for an output parameter in the SP or in your code.

Regular Expression to match every new line character (\n) inside a <content> tag

Actually... you can't use a simple regex here, at least not one. You probably need to worry about comments! Someone may write:

<!-- <content> blah </content> -->

You can take two approaches here:

  1. Strip all comments out first. Then use the regex approach.
  2. Do not use regular expressions and use a context sensitive parsing approach that can keep track of whether or not you are nested in a comment.

Be careful.

I am also not so sure you can match all new lines at once. @Quartz suggested this one:

<content>([^\n]*\n+)+</content>

This will match any content tags that have a newline character RIGHT BEFORE the closing tag... but I'm not sure what you mean by matching all newlines. Do you want to be able to access all the matched newline characters? If so, your best bet is to grab all content tags, and then search for all the newline chars that are nested in between. Something more like this:

<content>.*</content>

BUT THERE IS ONE CAVEAT: regexes are greedy, so this regex will match the first opening tag to the last closing one. Instead, you HAVE to suppress the regex so it is not greedy. In languages like python, you can do this with the "?" regex symbol.

I hope with this you can see some of the pitfalls and figure out how you want to proceed. You are probably better off using an XML parsing library, then iterating over all the content tags.

I know I may not be offering the best solution, but at least I hope you will see the difficulty in this and why other answers may not be right...

UPDATE 1:

Let me summarize a bit more and add some more detail to my response. I am going to use python's regex syntax because it is what I am more used to (forgive me ahead of time... you may need to escape some characters... comment on my post and I will correct it):

To strip out comments, use this regex: Notice the "?" suppresses the .* to make it non-greedy.

Similarly, to search for content tags, use: .*?

Also, You may be able to try this out, and access each newline character with the match objects groups():

<content>(.*?(\n))+.*?</content>

I know my escaping is off, but it captures the idea. This last example probably won't work, but I think it's your best bet at expressing what you want. My suggestion remains: either grab all the content tags and do it yourself, or use a parsing library.

UPDATE 2:

So here is python code that ought to work. I am still unsure what you mean by "find" all newlines. Do you want the entire lines? Or just to count how many newlines. To get the actual lines, try:

#!/usr/bin/python

import re

def FindContentNewlines(xml_text):
    # May want to compile these regexes elsewhere, but I do it here for brevity
    comments = re.compile(r"<!--.*?-->", re.DOTALL)
    content = re.compile(r"<content>(.*?)</content>", re.DOTALL)
    newlines = re.compile(r"^(.*?)$", re.MULTILINE|re.DOTALL)

    # strip comments: this actually may not be reliable for "nested comments"
    # How does xml handle <!--  <!-- --> -->. I am not sure. But that COULD
    # be trouble.
    xml_text = re.sub(comments, "", xml_text)

    result = []
    all_contents = re.findall(content, xml_text)
    for c in all_contents:
        result.extend(re.findall(newlines, c))

    return result

if __name__ == "__main__":
    example = """

<!-- This stuff
ought to be omitted
<content>
  omitted
</content>
-->

This stuff is good
<content>
<p>
  haha!
</p>
</content>

This is not found
"""
    print FindContentNewlines(example)

This program prints the result:

 ['', '<p>', '  haha!', '</p>', '']

The first and last empty strings come from the newline chars immediately preceeding the first <p> and the one coming right after the </p>. All in all this (for the most part) does the trick. Experiment with this code and refine it for your needs. Print out stuff in the middle so you can see what the regexes are matching and not matching.

Hope this helps :-).

PS - I didn't have much luck trying out my regex from my first update to capture all the newlines... let me know if you do.

Setup a Git server with msysgit on Windows

There is a nice open source Git stack called Git Blit. It is available for different platform and in different packages. You can also easily deploy it to your existing Tomcat or any other servlet container. Take a look at Setup git server on windows in few clicks tutorial for more details, it will take you around 10 minutes to get basic setup.

ios simulator: how to close an app

For iOS 7 & above:

  • shift+command+H twice to simulate the double tap of home button
  • swipe your app's screenshot upward to close it

You'll see screenshots representing the apps suspended on your device - those screenshots respond to touch events. Swiping is the gesture you'll make to "fling" the screenshot off of the screen. Note that on machines where your mouse is intended to represent your finger, you'll click and swipe as if it is your finger tapping and making the gesture.

How to fix Error: laravel.log could not be opened?

Delete "/var/www/laravel/app/storage/logs/laravel.log" and try again:

rm storage/logs/laravel.log

Where can I find the Tomcat 7 installation folder on Linux AMI in Elastic Beanstalk?

In my case on Ubuntu 16.04 server, and default tomcat installation it's under:

/var/lib/tomcat8

How do I iterate and modify Java Sets?

You can do what you want if you use an iterator object to go over the elements in your set. You can remove them on the go an it's ok. However removing them while in a for loop (either "standard", of the for each kind) will get you in trouble:

Set<Integer> set = new TreeSet<Integer>();
    set.add(1);
    set.add(2);
    set.add(3);

    //good way:
    Iterator<Integer> iterator = set.iterator();
    while(iterator.hasNext()) {
        Integer setElement = iterator.next();
        if(setElement==2) {
            iterator.remove();
        }
    }

    //bad way:
    for(Integer setElement:set) {
        if(setElement==2) {
            //might work or might throw exception, Java calls it indefined behaviour:
            set.remove(setElement);
        } 
    }

As per @mrgloom's comment, here are more details as to why the "bad" way described above is, well... bad :

Without getting into too much details about how Java implements this, at a high level, we can say that the "bad" way is bad because it is clearly stipulated as such in the Java docs:

https://docs.oracle.com/javase/8/docs/api/java/util/ConcurrentModificationException.html

stipulate, amongst others, that (emphasis mine):

"For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected" (...)

"Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception."

To go more into details: an object that can be used in a forEach loop needs to implement the "java.lang.Iterable" interface (javadoc here). This produces an Iterator (via the "Iterator" method found in this interface), which is instantiated on demand, and will contain internally a reference to the Iterable object from which it was created. However, when an Iterable object is used in a forEach loop, the instance of this iterator is hidden to the user (you cannot access it yourself in any way).

This, coupled with the fact that an Iterator is pretty stateful, i.e. in order to do its magic and have coherent responses for its "next" and "hasNext" methods it needs that the backing object is not changed by something else than the iterator itself while it's iterating, makes it so that it will throw an exception as soon as it detects that something changed in the backing object while it is iterating over it.

Java calls this "fail-fast" iteration: i.e. there are some actions, usually those that modify an Iterable instance (while an Iterator is iterating over it). The "fail" part of the "fail-fast" notion refers to the ability of an Iterator to detect when such "fail" actions happen. The "fast" part of the "fail-fast" (and, which in my opinion should be called "best-effort-fast"), will terminate the iteration via ConcurrentModificationException as soon as it can detect that a "fail" action has happen.

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

I have encountered this error code when enumerating names and calling worksheet.get_Range(name). It seems to occur when the name does NOT apply to a range, in my case it is the name of a macro.

modal View controllers - how to display and dismiss

I wanted this:

MapVC is a Map in full screen.

When I press a button, it opens PopupVC (not in full screen) above the map.

When I press a button in PopupVC, it returns to MapVC, and then I want to execute viewDidAppear.

I did this:

MapVC.m: in the button action, a segue programmatically, and set delegate

- (void) buttonMapAction{
   PopupVC *popvc = [self.storyboard instantiateViewControllerWithIdentifier:@"popup"];
   popvc.delegate = self;
   [self presentViewController:popvc animated:YES completion:nil];
}

- (void)dismissAndPresentMap {
  [self dismissViewControllerAnimated:NO completion:^{
    NSLog(@"dismissAndPresentMap");
    //When returns of the other view I call viewDidAppear but you can call to other functions
    [self viewDidAppear:YES];
  }];
}

PopupVC.h: before @interface, add the protocol

@protocol PopupVCProtocol <NSObject>
- (void)dismissAndPresentMap;
@end

after @interface, a new property

@property (nonatomic,weak) id <PopupVCProtocol> delegate;

PopupVC.m:

- (void) buttonPopupAction{
  //jump to dismissAndPresentMap on Map view
  [self.delegate dismissAndPresentMap];
}

Javascript - validation, numbers only

// I use this jquery it works perfect, just add class nosonly to any textbox that should be numbers only:

$(document).ready(function () {
       $(".nosonly").keydown(function (event) {
           // Allow only backspace and delete
           if (event.keyCode == 46 || event.keyCode == 8) {
               // let it happen, don't do anything
           }
           else {
               // Ensure that it is a number and stop the keypress
               if (event.keyCode < 48 || event.keyCode > 57) {
              alert("Only Numbers Allowed"),event.preventDefault();
               }
           }
       });
   });

Java: Rotating Images

This is how you can do it. This code assumes the existance of a buffered image called 'image' (like your comment says)

// The required drawing location
int drawLocationX = 300;
int drawLocationY = 300;

// Rotation information

double rotationRequired = Math.toRadians (45);
double locationX = image.getWidth() / 2;
double locationY = image.getHeight() / 2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);

// Drawing the rotated image at the required drawing locations
g2d.drawImage(op.filter(image, null), drawLocationX, drawLocationY, null);

Ruby Arrays: select(), collect(), and map()

When dealing with a hash {}, use both the key and value to the block inside the ||.

details.map {|key,item|"" == item}

=>[false, false, true, false, false]

What does it mean when a PostgreSQL process is "idle in transaction"?

As mentioned here: Re: BUG #4243: Idle in transaction it is probably best to check your pg_locks table to see what is being locked and that might give you a better clue where the problem lies.

Activate a virtualenv with a Python script

The top answer only works for Python 2.x

For Python 3.x, use this:

activate_this_file = "/path/to/virtualenv/bin/activate_this.py"

exec(compile(open(activate_this_file, "rb").read(), activate_this_file, 'exec'), dict(__file__=activate_this_file))

Reference: What is an alternative to execfile in Python 3?

How to sort the files according to the time stamp in unix?

File modification:

ls -t

Inode change:

ls -tc

File access:

ls -tu

"Newest" one at the bottom:

ls -tr

None of this is a creation time. Most Unix filesystems don't support creation timestamps.

How to navigate to to different directories in the terminal (mac)?

To check that the file you're trying to open actually exists, you can change directories in terminal using cd. To change to ~/Desktop/sass/css: cd ~/Desktop/sass/css. To see what files are in the directory: ls.

If you want information about either of those commands, use the man page: man cd or man ls, for example.

Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.

On Mac OS X, you can also use open to open a finder window: open . will open the current directory in finder. (open ~/Desktop/sass/css will open the ~/Desktop/sass/css).

How to remove outliers in boxplot in R?

See ?boxplot for all the help you need.

 outline: if ‘outline’ is not true, the outliers are not drawn (as
          points whereas S+ uses lines).

boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)

And for extending the range of the whiskers and suppressing the outliers inside this range:

   range: this determines how far the plot whiskers extend out from the
          box.  If ‘range’ is positive, the whiskers extend to the most
          extreme data point which is no more than ‘range’ times the
          interquartile range from the box. A value of zero causes the
          whiskers to extend to the data extremes.

# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)

How do I create a dictionary with keys from a list and values defaulting to (say) zero?

d = dict([(x,0) for x in a])

**edit Tim's solution is better because it uses generators see the comment to his answer.

Get Folder Size from Windows Command Line

I think your only option will be diruse (a highly supported 3rd party solution):

Get file/directory size from command line

The Windows CLI is unfortuntely quite restrictive, you could alternatively install Cygwin which is a dream to use compared to cmd. That would give you access to the ported Unix tool du which is the basis of diruse on windows.

Sorry I wasn't able to answer your questions directly with a command you can run on the native cli.

WordPress Get the Page ID outside the loop

You can also create a generic function to get the ID of the post, whether its outside or inside the loop (handles both the cases):

<?php

/**
 * @uses WP_Query
 * @uses get_queried_object()
 * @see get_the_ID()
 * @return int
 */
function get_the_post_id() {
  if (in_the_loop()) {
       $post_id = get_the_ID();
  } else {
       global $wp_query;
       $post_id = $wp_query->get_queried_object_id();
         }
  return $post_id;
} ?>

And simply do:

$page_id = get_the_post_id();

How can I determine browser window size on server side C#

Here how I solved it using Cookies:

First of all, inside the website main script:

var browserWindowSize = getCookie("_browserWindowSize");
var newSize = $(window).width() + "," + $(window).height();
var reloadForCookieRefresh = false;

if (browserWindowSize == undefined || browserWindowSize == null || newSize != browserWindowSize) {
    setCookie("_browserWindowSize", newSize, 30);
    reloadForCookieRefresh = true;
}

if (reloadForCookieRefresh)
    window.location.reload();

function setCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "") + expires + "; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

And inside MVC action filter:

public class SetCurrentRequestDataFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // currentRequestService is registered per web request using IoC
        var currentRequestService = iocResolver.Resolve<ICurrentRequestService>();

        if (filterContext.HttpContext.Request.Cookies.AllKeys.Contains("_browserWindowSize"))
        {
            var browserWindowSize = filterContext.HttpContext.Request.Cookies.Get("_browserWindowSize").Value.Split(',');
            currentRequestService.browserWindowWidth = int.Parse(browserWindowSize[0]);
            currentRequestService.browserWindowHeight = int.Parse(browserWindowSize[1]);
        }

    }
}

where does MySQL store database files?

another way from MySQL Workbench:

enter image description here

Converting EditText to int? (Android)

You can use parseInt with try and catch block

try
{
    int myVal= Integer.parseInt(mTextView.getText().toString());
}
catch (NumberFormatException e)
{
    // handle the exception
    int myVal=0;
}

Or you can create your own tryParse method :

public Integer tryParse(Object obj) {
    Integer retVal;
    try {
        retVal = Integer.parseInt((String) obj);
    } catch (NumberFormatException nfe) {
        retVal = 0; // or null if that is your preference
    }
    return retVal;
}

and use it in your code like:

int myVal= tryParse(mTextView.getText().toString());

Note: The following code without try/catch will throw an exception

int myVal= new Integer(mTextView.getText().toString()).intValue();

Or

int myVal= Integer.decode(mTextView.getText().toString()).intValue();

Display the current time and date in an Android application

The obvious choices for displaying the time are the AnalogClock View and the DigitalClock View.

For example, the following layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:orientation="vertical">

    <AnalogClock
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"/>

    <DigitalClock 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:gravity="center" 
        android:textSize="20sp"/>
</LinearLayout>

Looks like this:

screenshot

Best practice: PHP Magic Methods __set and __get

I vote for a third solution. I use this in my projects and Symfony uses something like this too:

public function __call($val, $x) {
    if(substr($val, 0, 3) == 'get') {
        $varname = strtolower(substr($val, 3));
    }
    else {
        throw new Exception('Bad method.', 500);
    }
    if(property_exists('Yourclass', $varname)) {
        return $this->$varname;
    } else {
        throw new Exception('Property does not exist: '.$varname, 500);
    }
}

This way you have automated getters (you can write setters too), and you only have to write new methods if there is a special case for a member variable.

Change UITextField and UITextView Cursor / Caret Color

Setting tintColor for UITextField and UITextView works differently. While for UITextField you don't need to call additional code after updating tintColor to change cursor color, but for UITextView you need.

So after setting tintColor for UITextView (it doesn't matter in IB or in code) you need to call textView.tintColorDidChange() in order to apply it (actually it will pass text view's config down to its subviews hierarchy).

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

OK, two steps to this - first is to write a function that does the translation you want - I've put an example together based on your pseudo-code:

def label_race (row):
   if row['eri_hispanic'] == 1 :
      return 'Hispanic'
   if row['eri_afr_amer'] + row['eri_asian'] + row['eri_hawaiian'] + row['eri_nat_amer'] + row['eri_white'] > 1 :
      return 'Two Or More'
   if row['eri_nat_amer'] == 1 :
      return 'A/I AK Native'
   if row['eri_asian'] == 1:
      return 'Asian'
   if row['eri_afr_amer']  == 1:
      return 'Black/AA'
   if row['eri_hawaiian'] == 1:
      return 'Haw/Pac Isl.'
   if row['eri_white'] == 1:
      return 'White'
   return 'Other'

You may want to go over this, but it seems to do the trick - notice that the parameter going into the function is considered to be a Series object labelled "row".

Next, use the apply function in pandas to apply the function - e.g.

df.apply (lambda row: label_race(row), axis=1)

Note the axis=1 specifier, that means that the application is done at a row, rather than a column level. The results are here:

0           White
1        Hispanic
2           White
3           White
4           Other
5           White
6     Two Or More
7           White
8    Haw/Pac Isl.
9           White

If you're happy with those results, then run it again, saving the results into a new column in your original dataframe.

df['race_label'] = df.apply (lambda row: label_race(row), axis=1)

The resultant dataframe looks like this (scroll to the right to see the new column):

      lname   fname rno_cd  eri_afr_amer  eri_asian  eri_hawaiian   eri_hispanic  eri_nat_amer  eri_white rno_defined    race_label
0      MOST    JEFF      E             0          0             0              0             0          1       White         White
1    CRUISE     TOM      E             0          0             0              1             0          0       White      Hispanic
2      DEPP  JOHNNY    NaN             0          0             0              0             0          1     Unknown         White
3     DICAP     LEO    NaN             0          0             0              0             0          1     Unknown         White
4    BRANDO  MARLON      E             0          0             0              0             0          0       White         Other
5     HANKS     TOM    NaN             0          0             0              0             0          1     Unknown         White
6    DENIRO  ROBERT      E             0          1             0              0             0          1       White   Two Or More
7    PACINO      AL      E             0          0             0              0             0          1       White         White
8  WILLIAMS   ROBIN      E             0          0             1              0             0          0       White  Haw/Pac Isl.
9  EASTWOOD   CLINT      E             0          0             0              0             0          1       White         White

How to use ADB to send touch events to device using sendevent command?

Consider using Android's uiautomator, with adb shell uiautomator [...] or directly using the .jar that comes with the SDK.

How to delete rows from a pandas DataFrame based on a conditional expression

When you do len(df['column name']) you are just getting one number, namely the number of rows in the DataFrame (i.e., the length of the column itself). If you want to apply len to each element in the column, use df['column name'].map(len). So try

df[df['column name'].map(len) < 2]

How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5

return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
new object[] { param1, param2, param3 });

//Or

using(var context = new MyDataContext())
{
return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
new object[] { param1, param2, param3 }).ToList();
}

//Or

using(var context = new MyDataContext())
{
object[] parameters =  { param1, param2, param3 };

return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
parameters).ToList();
}

//Or

using(var context = new MyDataContext())
{  
return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
param1, param2, param3).ToList();
}

Getting Error "Form submission canceled because the form is not connected"

if you are seeing this error in React JS when you try to submit the form by pressing enter, make sure all your buttons in the form that do not submit the form have a type="button".

If you have only one button with type="submit" pressing Enter will submit the form as expected.

References:
https://dzello.com/blog/2017/02/19/demystifying-enter-key-submission-for-react-forms/ https://github.com/facebook/react/issues/2093

Declaring static constants in ES6 classes?

The cleanest way I've found of doing this is with TypeScript - see How to implement class constants?

class MyClass {
    static readonly CONST1: string = "one";
    static readonly CONST2: string = "two";
    static readonly CONST3: string = "three";
}

Renaming part of a filename

There are a couple of variants of a rename command, in your case, it may be as simple as

rename ABC XYZ *.dat

You may have a version which takes a Perl regex;

rename 's/ABC/XYZ/' *.dat

How can I check that two objects have the same set of property names?

You can serialize simple data to check for equality:

data1 = {firstName: 'John', lastName: 'Smith'};
data2 = {firstName: 'Jane', lastName: 'Smith'};
JSON.stringify(data1) === JSON.stringify(data2)

This will give you something like

'{firstName:"John",lastName:"Smith"}' === '{firstName:"Jane",lastName:"Smith"}'

As a function...

function compare(a, b) {
  return JSON.stringify(a) === JSON.stringify(b);
}
compare(data1, data2);

EDIT

If you're using chai like you say, check out http://chaijs.com/api/bdd/#equal-section

EDIT 2

If you just want to check keys...

function compareKeys(a, b) {
  var aKeys = Object.keys(a).sort();
  var bKeys = Object.keys(b).sort();
  return JSON.stringify(aKeys) === JSON.stringify(bKeys);
}

should do it.

Using generic std::function objects with member functions in one class

Either you need

std::function<void(Foo*)> f = &Foo::doSomething;

so that you can call it on any instance, or you need to bind a specific instance, for example this

std::function<void(void)> f = std::bind(&Foo::doSomething, this);

Check if an element is a child of a parent

Vanilla 1-liner for IE8+:

parent !== child && parent.contains(child);

Here, how it works:

_x000D_
_x000D_
function contains(parent, child) {_x000D_
  return parent !== child && parent.contains(child);_x000D_
}_x000D_
_x000D_
var parentEl = document.querySelector('#parent'),_x000D_
    childEl = document.querySelector('#child')_x000D_
    _x000D_
if (contains(parentEl, childEl)) {_x000D_
  document.querySelector('#result').innerText = 'I confirm, that child is within parent el';_x000D_
}_x000D_
_x000D_
if (!contains(childEl, parentEl)) {_x000D_
  document.querySelector('#result').innerText += ' and parent is not within child';_x000D_
}
_x000D_
<div id="parent">_x000D_
  <div>_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td><span id="child"></span></td>_x000D_
      </tr>_x000D_
    </table>_x000D_
  </div>_x000D_
</div>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

How to show the text on a ImageButton?

I solved this by putting the ImageButton and TextView inside a LinearLayout with vertical orientation. Works great!

<LinearLayout
    android:id="@+id/linLayout"
    android:layout_width="80dp"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <ImageButton
        android:id="@+id/camera_ibtn"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_gravity="center"
        android:background="@drawable/camera" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/take_pic"
        android:textColor="#FFFFFF"
        android:textStyle="bold" />

</LinearLayout>

How to get the size of a range in Excel

The Range object has both width and height properties, which are measured in points.

Spring Boot, Spring Data JPA with multiple DataSources

There is another way to have multiple dataSources by using @EnableAutoConfiguration and application.properties.

Basically put multiple dataSource configuration info on application.properties and generate default setup (dataSource and entityManagerFactory) automatically for first dataSource by @EnableAutoConfiguration. But for next dataSource, create dataSource, entityManagerFactory and transactionManager all manually by the info from property file.

Below is my example to setup two dataSources. First dataSource is setup by @EnableAutoConfiguration which can be assigned only for one configuration, not multiple. And that will generate 'transactionManager' by DataSourceTransactionManager, that looks default transactionManager generated by the annotation. However I have seen the transaction not beginning issue on the thread from scheduled thread pool only for the default DataSourceTransactionManager and also when there are multiple transaction managers. So I create transactionManager manually by JpaTransactionManager also for the first dataSource with assigning 'transactionManager' bean name and default entityManagerFactory. That JpaTransactionManager for first dataSource surely resolves the weird transaction issue on the thread from ScheduledThreadPool.

Update for Spring Boot 1.3.0.RELEASE

I found my previous configuration with @EnableAutoConfiguration for default dataSource has issue on finding entityManagerFactory with Spring Boot 1.3 version. Maybe default entityManagerFactory is not generated by @EnableAutoConfiguration, once after I introduce my own transactionManager. So now I create entityManagerFactory by myself. So I don't need to use @EntityScan. So it looks I'm getting more and more out of the setup by @EnableAutoConfiguration.

Second dataSource is setup without @EnableAutoConfiguration and create 'anotherTransactionManager' by manual way.

Since there are multiple transactionManager extends from PlatformTransactionManager, we should specify which transactionManager to use on each @Transactional annotation

Default Repository Config

@Configuration
@EnableTransactionManagement
@EnableAutoConfiguration
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactory",
        transactionManagerRef = "transactionManager",
        basePackages = {"com.mysource.repository"})
public class RepositoryConfig {
    @Autowired
    JpaVendorAdapter jpaVendorAdapter;

    @Autowired
    DataSource dataSource;

    @Bean(name = "entityManager")
    public EntityManager entityManager() {
        return entityManagerFactory().createEntityManager();
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public EntityManagerFactory entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
        emf.setDataSource(dataSource);
        emf.setJpaVendorAdapter(jpaVendorAdapter);
        emf.setPackagesToScan("com.mysource.model");
        emf.setPersistenceUnitName("default");   // <- giving 'default' as name
        emf.afterPropertiesSet();
        return emf.getObject();
    }

    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager tm = new JpaTransactionManager();
        tm.setEntityManagerFactory(entityManagerFactory());
        return tm;
    }
}

Another Repository Config

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "anotherEntityManagerFactory",
        transactionManagerRef = "anotherTransactionManager",
        basePackages = {"com.mysource.anothersource.repository"})
public class AnotherRepositoryConfig {
    @Autowired
    JpaVendorAdapter jpaVendorAdapter;

    @Value("${another.datasource.url}")
    private String databaseUrl;

    @Value("${another.datasource.username}")
    private String username;

    @Value("${another.datasource.password}")
    private String password;

    @Value("${another.dataource.driverClassName}")
    private String driverClassName;

    @Value("${another.datasource.hibernate.dialect}")
    private String dialect;

    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource(databaseUrl, username, password);
        dataSource.setDriverClassName(driverClassName);
        return dataSource;
    }

    @Bean(name = "anotherEntityManager")
    public EntityManager entityManager() {
        return entityManagerFactory().createEntityManager();
    }

    @Bean(name = "anotherEntityManagerFactory")
    public EntityManagerFactory entityManagerFactory() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.dialect", dialect);

        LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
        emf.setDataSource(dataSource());
        emf.setJpaVendorAdapter(jpaVendorAdapter);
        emf.setPackagesToScan("com.mysource.anothersource.model");   // <- package for entities
        emf.setPersistenceUnitName("anotherPersistenceUnit");
        emf.setJpaProperties(properties);
        emf.afterPropertiesSet();
        return emf.getObject();
    }

    @Bean(name = "anotherTransactionManager")
    public PlatformTransactionManager transactionManager() {
        return new JpaTransactionManager(entityManagerFactory());
    }
}

application.properties

# database configuration
spring.datasource.url=jdbc:h2:file:~/main-source;AUTO_SERVER=TRUE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.continueOnError=true
spring.datasource.initialize=false

# another database configuration
another.datasource.url=jdbc:sqlserver://localhost:1433;DatabaseName=another;
another.datasource.username=username
another.datasource.password=
another.datasource.hibernate.dialect=org.hibernate.dialect.SQLServer2008Dialect 
another.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver

Choose proper transactionManager for @Transactional annotation

Service for first datasource

@Service("mainService")
@Transactional("transactionManager")
public class DefaultDataSourceServiceImpl implements DefaultDataSourceService       
{

   //

}

Service for another datasource

@Service("anotherService")
@Transactional("anotherTransactionManager")
public class AnotherDataSourceServiceImpl implements AnotherDataSourceService 
{

   //

}

Hiding the R code in Rmarkdown/knit and just showing the results

Alternatively, you can also parse a standard markdown document (without code blocks per se) on the fly by the markdownreports package.

What is context in _.each(list, iterator, [context])?

As explained in other answers, context is the this context to be used inside callback passed to each.

I'll explain this with the help of source code of relevant methods from underscore source code

The definition of _.each or _.forEach is as follows:

_.each = _.forEach = function(obj, iteratee, context) {
  iteratee = optimizeCb(iteratee, context);

  var i, length;
  if (isArrayLike(obj)) {
    for (i = 0, length = obj.length; i < length; i++) {
      iteratee(obj[i], i, obj);
    }
  } else {
    var keys = _.keys(obj);
    for (i = 0, length = keys.length; i < length; i++) {
      iteratee(obj[keys[i]], keys[i], obj);
    }
  }
  return obj;
};

Second statement is important to note here

iteratee = optimizeCb(iteratee, context);

Here, context is passed to another method optimizeCb and the returned function from it is then assigned to iteratee which is called later.

var optimizeCb = function(func, context, argCount) {
  if (context === void 0) return func;
  switch (argCount == null ? 3 : argCount) {
    case 1:
      return function(value) {
        return func.call(context, value);
      };
    case 2:
      return function(value, other) {
        return func.call(context, value, other);
      };
    case 3:
      return function(value, index, collection) {
        return func.call(context, value, index, collection);
      };
    case 4:
      return function(accumulator, value, index, collection) {
        return func.call(context, accumulator, value, index, collection);
      };
  }
  return function() {
    return func.apply(context, arguments);
  };
};

As can be seen from the above method definition of optimizeCb, if context is not passed then func is returned as it is. If context is passed, callback function is called as

func.call(context, other_parameters);
          ^^^^^^^

func is called with call() which is used to invoke a method by setting this context of it. So, when this is used inside func, it'll refer to context.

_x000D_
_x000D_
// Without `context`_x000D_
_.each([1], function() {_x000D_
  console.log(this instanceof Window);_x000D_
});_x000D_
_x000D_
_x000D_
// With `context` as `arr`_x000D_
var arr = [1, 2, 3];_x000D_
_.each([1], function() {_x000D_
  console.log(this);_x000D_
}, arr);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

You can consider context as the last optional parameter to forEach in JavaScript.

Finding child element of parent pure javascript

If you already have var parent = document.querySelector('.parent'); you can do this to scope the search to parent's children:

parent.querySelector('.child')

fopen deprecated warning

Consider using a portability library like glib or the apache portable runtime. These usually provide safe, portable alternatives to calls like these. It's a good thing too, because these insecure calls are deprecated in most modern environments.

How to change CSS using jQuery?

Ignore the people that are suggesting that the property name is the issue. The jQuery API documentation explicitly states that either notation is acceptable: http://api.jquery.com/css/

The actual problem is that you are missing a closing curly brace on this line:

$("#myParagraph").css({"backgroundColor":"black","color":"white");

Change it to this:

$("#myParagraph").css({"backgroundColor": "black", "color": "white"});

Here's a working demo: http://jsfiddle.net/YPYz8/

_x000D_
_x000D_
$(init);_x000D_
    _x000D_
function init() {_x000D_
    $("h1").css("backgroundColor", "yellow");_x000D_
    $("#myParagraph").css({ "backgroundColor": "black", "color": "white" });_x000D_
    $(".bordered").css("border", "1px solid black");_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
<div class="bordered">_x000D_
    <h1>Header</h1>_x000D_
    <p id="myParagraph">This is some paragraph text</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

AngularJS access parent scope from child controller

I believe I had a similar quandary recently

function parentCtrl() {
   var pc = this; // pc stands for parent control
   pc.foobar = 'SomeVal';
}

function childCtrl($scope) {

   // now how do I get the parent control 'foobar' variable?
   // I used $scope.$parent

   var parentFoobarVariableValue = $scope.$parent.pc.foobar;

   // that did it
}

My setup was a little different, but the same thing should probably still work

How to pass json POST data to Web API method as an object?

Working with POST in webapi can be tricky! Would like to add to the already correct answer..

Will focus specifically on POST as dealing with GET is trivial. I don't think many would be searching around for resolving an issue with GET with webapis. Anyways..

If your question is - In MVC Web Api, how to- - Use custom action method names other than the generic HTTP verbs? - Perform multiple posts? - Post multiple simple types? - Post complex types via jQuery?

Then the following solutions may help:

First, to use Custom Action Methods in Web API, add a web api route as:

public static void Register(HttpConfiguration config)
{
    config.Routes.MapHttpRoute(
        name: "ActionApi",
        routeTemplate: "api/{controller}/{action}");
}

And then you may create action methods like:

[HttpPost]
public string TestMethod([FromBody]string value)
{
    return "Hello from http post web api controller: " + value;
}

Now, fire the following jQuery from your browser console

$.ajax({
    type: 'POST',
    url: 'http://localhost:33649/api/TestApi/TestMethod',
    data: {'':'hello'},
    contentType: 'application/x-www-form-urlencoded',
    dataType: 'json',
    success: function(data){ console.log(data) }
});

Second, to perform multiple posts, It is simple, create multiple action methods and decorate with the [HttpPost] attrib. Use the [ActionName("MyAction")] to assign custom names, etc. Will come to jQuery in the fourth point below

Third, First of all, posting multiple SIMPLE types in a single action is not possible. Moreover, there is a special format to post even a single simple type (apart from passing the parameter in the query string or REST style). This was the point that had me banging my head with Rest Clients (like Fiddler and Chrome's Advanced REST client extension) and hunting around the web for almost 5 hours when eventually, the following URL proved to be of help. Will quote the relevant content for the link might turn dead!

Content-Type: application/x-www-form-urlencoded
in the request header and add a = before the JSON statement:
={"Name":"Turbo Tina","Email":"[email protected]"}

PS: Noticed the peculiar syntax?

http://forums.asp.net/t/1883467.aspx?The+received+value+is+null+when+I+try+to+Post+to+my+Web+Api

Anyways, let us get over that story. Moving on:

Fourth, posting complex types via jQuery, ofcourse, $.ajax() is going to promptly come in the role:

Let us say the action method accepts a Person object which has an id and a name. So, from javascript:

var person = { PersonId:1, Name:"James" }
$.ajax({
    type: 'POST',
    url: 'http://mydomain/api/TestApi/TestMethod',
    data: JSON.stringify(person),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function(data){ console.log(data) }
});

And the action will look like:

[HttpPost]
public string TestMethod(Person person)
{
    return "Hello from http post web api controller: " + person.Name;
}

All of the above, worked for me!! Cheers!

Display a message in Visual Studio's output window when not debug mode?

The results are not in the Output window but in the Test Results Detail (TestResult Pane at the bottom, right click on on Test Results and go to TestResultDetails).

This works with Debug.WriteLine and Console.WriteLine.

How to increase memory limit for PHP over 2GB?

For unlimited memory limit set -1 in memory_limit variable:

ini_set('memory_limit', '-1');

C# static class constructor

Yes, a static class can have static constructor, and the use of this constructor is initialization of static member.

static class Employee1
{
    static int EmpNo;
    static Employee1()
    {
        EmpNo = 10;
        // perform initialization here
    }
    public static void Add()
    { 

    }
    public static void Add1()
    { 

    }
}

and static constructor get called only once when you have access any type member of static class with class name Class1

Suppose you are accessing the first EmployeeName field then constructor get called this time, after that it will not get called, even if you will access same type member.

 Employee1.EmployeeName = "kumod";
        Employee1.Add();
        Employee1.Add();

Unable to verify leaf signature

The Secure Solution

Rather than turning off security you can add the necessary certificates to the chain. First install ssl-root-cas package from npm:

npm install ssl-root-cas

This package contains many intermediary certificates that browsers trust but node doesn't.

var sslRootCAs = require('ssl-root-cas/latest')
sslRootCAs.inject()

Will add the missing certificates. See here for more info:

https://git.coolaj86.com/coolaj86/ssl-root-cas.js

Also, See the next answer below

What is the facade design pattern?

A facade is a class with a level of functionality that lies between a toolkit and a complete application, offering a simplified usage of the classes in a package or subsystem. The intent of the Facade pattern is to provide an interface that makes a subsystem easy to use. -- Extract from book Design Patterns in C#.

Right way to write JSON deserializer in Spring or extend it

With Spring MVC 4.2.1.RELEASE, you need to use the new Jackson2 dependencies as below for the Deserializer to work.

Dont use this

<dependency>  
            <groupId>org.codehaus.jackson</groupId>  
            <artifactId>jackson-mapper-asl</artifactId>  
            <version>1.9.12</version>  
        </dependency>  

Use this instead.

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.2</version>
        </dependency>  

Also use com.fasterxml.jackson.databind.JsonDeserializer and com.fasterxml.jackson.databind.annotation.JsonDeserialize for the deserialization and not the classes from org.codehaus.jackson

Failed to create provisioning profile

The issue behind this error is Unavailability of App ID with given Bundle Identifier

Solution: Change Bundle Identifier simple :)

Eclipse Optimize Imports to Include Static Imports

Shortcut for static import: CTRL + SHIFT + M

Retrieve a single file from a repository

I use this

$ cat ~/.wgetrc
check_certificate = off

$ wget https://raw.github.com/jquery/jquery/master/grunt.js
HTTP request sent, awaiting response... 200 OK
Length: 11339 (11K) [text/plain]
Saving to: `grunt.js'

HTML form input tag name element array with JavaScript

Here’s some PHP and JavaScript demonstration code that shows a simple way to create indexed fields on a form (fields that have the same name) and then process them in both JavaScript and PHP. The fields must have both "ID" names and "NAME" names. Javascript uses the ID and PHP uses the NAME.

<?php
// How to use same field name multiple times on form
// Process these fields in Javascript and PHP
// Must use "ID" in Javascript and "NAME" in PHP 
echo "<HTML>";
echo "<HEAD>";
?>
<script type="text/javascript">
function TestForm(form) {
// Loop through the HTML form field (TheId) that is returned as an array. 
// The form field has multiple (n) occurrences on the form, each which has the same name.
// This results in the return of an array of elements indexed from 0 to n-1.
// Use ID  in Javascript
var i = 0;
document.write("<P>Javascript responding to your button click:</P>");
for (i=0; i < form.TheId.length; i++) {
  document.write(form.TheId[i].value);
  document.write("<br>");
}  
}
</script>
<?php
echo "</HEAD>";
echo "<BODY>";
$DQ = '"';  # Constant for building string with double quotes in it.

if (isset($_POST["MyButton"])) {
  $TheNameArray = $_POST["TheName"];  # Use NAME in PHP
  echo "<P>Here are the names you submitted to server:</P>";
  for ($i = 0; $i <3; $i++) {   
    echo $TheNameArray[$i] . "<BR>";
  } 
}
echo "<P>Enter names and submit to server or Javascript</P>";
echo "<FORM NAME=TstForm METHOD=POST ACTION=" ;
echo $DQ . "TestArrayFormToJavascript2.php" . $DQ . "OnReset=" . $DQ . "return allowreset(this)" . $DQ . ">";
echo "<FORM>";
echo "<INPUT ID = TheId NAME=" . $DQ . "TheName[]" . $DQ . " VALUE=" . $DQ . "" . $DQ . ">";
echo "<INPUT ID = TheId NAME=" . $DQ . "TheName[]" . $DQ . " VALUE=" . $DQ . "" . $DQ . ">";
echo "<INPUT ID = TheId NAME=" . $DQ . "TheName[]" . $DQ . " VALUE=" . $DQ . "" . $DQ . ">";
echo "<P><INPUT TYPE=submit NAME=MyButton VALUE=" . $DQ . "Submit to server"    . $DQ . "></P>";
echo "<P><BUTTON onclick=" . $DQ . "TestForm(this.form)" . $DQ . ">Submit to Javascript</BUTTON></P>"; 
echo "</FORM>";
echo "</BODY>";
echo "</HTML>";

Xcode 6: Keyboard does not show up in simulator

This seems to be a bug in iOS 8. There are two fixes to this problem :

  1. Toggle between simulator keyboard and MacBook keyboard using the Command+K shortcut.

  2. Reattach keyboard to simulator :

    a. Open Simulator

    b. Select Hardware -> Keyboard

    c. Uncheck and then check 'Connect Hardware Keyboard'

Screenshot for step 2

OR simply press the Shift + Command + K shortcut

How to auto-format code in Eclipse?

Another option is to go to Window->Preferences->Java->Editor->SaveActions and check the Format source code option. Then your source code will be formatted truly automatically each time you save it.

Handling click events on a drawable within an EditText

Simply copy paste the following code and it does the trick.

editMsg.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            final int DRAWABLE_LEFT = 0;
            final int DRAWABLE_TOP = 1;
            final int DRAWABLE_RIGHT = 2;
            final int DRAWABLE_BOTTOM = 3;

            if(event.getAction() == MotionEvent.ACTION_UP) {
                if(event.getRawX() >= (editMsg.getRight() - editMsg.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
                    // your action here

                    Toast.makeText(ChatActivity.this, "Message Sent", Toast.LENGTH_SHORT).show();
                    return true;
                }
            }
            return false;
        }
    });

Properly escape a double quote in CSV

Use 2 quotes:

"Samsung U600 24"""

C++ -- expected primary-expression before ' '

You don't need "string" in your call to wordLengthFunction().

int wordLength = wordLengthFunction(string word);

should be

int wordLength = wordLengthFunction(word);

How is a tag different from a branch in Git? Which should I use, here?

simple:

Tags are expected to always point at the same version of a project, while heads are expected to advance as development progresses.

Git User Manual

Find unique lines

sort -d "file name" | uniq -u

this worked for me for a similar one. Use this if it is not arranged. You can remove sort if it is arranged

Match multiline text using regular expression

This has nothing to do with the MULTILINE flag; what you're seeing is the difference between the find() and matches() methods. find() succeeds if a match can be found anywhere in the target string, while matches() expects the regex to match the entire string.

Pattern p = Pattern.compile("xyz");

Matcher m = p.matcher("123xyzabc");
System.out.println(m.find());    // true
System.out.println(m.matches()); // false

Matcher m = p.matcher("xyz");
System.out.println(m.matches()); // true

Furthermore, MULTILINE doesn't mean what you think it does. Many people seem to jump to the conclusion that you have to use that flag if your target string contains newlines--that is, if it contains multiple logical lines. I've seen several answers here on SO to that effect, but in fact, all that flag does is change the behavior of the anchors, ^ and $.

Normally ^ matches the very beginning of the target string, and $ matches the very end (or before a newline at the end, but we'll leave that aside for now). But if the string contains newlines, you can choose for ^ and $ to match at the start and end of any logical line, not just the start and end of the whole string, by setting the MULTILINE flag.

So forget about what MULTILINE means and just remember what it does: changes the behavior of the ^ and $ anchors. DOTALL mode was originally called "single-line" (and still is in some flavors, including Perl and .NET), and it has always caused similar confusion. We're fortunate that the Java devs went with the more descriptive name in that case, but there was no reasonable alternative for "multiline" mode.

In Perl, where all this madness started, they've admitted their mistake and gotten rid of both "multiline" and "single-line" modes in Perl 6 regexes. In another twenty years, maybe the rest of the world will have followed suit.

Get Selected value from dropdown using JavaScript

Working jsbin: http://jsbin.com/ANAYeDU/4/edit

Main bit:

function answers()
{

var element = document.getElementById("mySelect");
var elementValue = element.value;

if(elementValue == "To measure time"){
  alert("Thats correct"); 
  }
}

-bash: syntax error near unexpected token `newline'

The characters '<', and '>', are to indicate a place-holder, you should remove them to read:

php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME

Find and Replace Inside a Text File from a Bash Command

I was surprised when I stumbled over this...

There is a replace command which ships with the "mysql-server" package, so if you have installed it try it out:

# replace string abc to XYZ in files
replace "abc" "XYZ" -- file.txt file2.txt file3.txt

# or pipe an echo to replace
echo "abcdef" |replace "abc" "XYZ"

See man replace for more on this.

Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in

Use getJSON

$.getJSON(
'index.php?r=admin/post/ajax',
{"parentCatId":parentCatId},
function(data){                     
    $.each(data, function(key, value){
        console.log(key + ":" + value)
    })
});

Detail look here http://api.jquery.com/jQuery.getJSON/

How to solve COM Exception Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))?

My problem and the solution

I have a 32 bit third party dll which i have installed in 2008 R2 machine which is 64 bit.

I have a wcf service created in .net 4.5 framework which calls the 32 bit third party dll for process. Now i have build property set to target 'any' cpu and deployed it to the 64 bit machine.

when i tried to invoke the wcf service got error "80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG"

Now i used ProcMon.exe to trace the com registry issue and identified that the process is looking for the registry entry at HKLM\CLSID and HKCR\CLSID where there is no entry.

Came to know that Microsoft will not register the 32 bit com components to the paths HKLM\CLSID, HKCR\CLSID in 64 bit machine rather it places the entry in HKLM\Wow6432Node\CLSID and HKCR\Wow6432Node\CLSID paths.

Now the conflict is 64 bit process trying to invoke 32 bit process in 64 bit machine which will look for the registry entry in HKLM\CLSID, HKCR\CLSID. The solution is we have to force the 64 bit process to look at the registry entry at HKLM\Wow6432Node\CLSID and HKCR\Wow6432Node\CLSID.

This can be achieved by configuring the wcf service project properties to target to 'X86' machine instead of 'Any'.

After deploying the 'X86' version to the 2008 R2 server got the issue "System.BadImageFormatException: Could not load file or assembly"

Solution to this badimageformatexception is setting the 'Enable32bitApplications' to 'True' in IIS Apppool properties for the right apppool.

Creating a jQuery object from a big HTML-string

var jQueryObject = $('<div></div>').html( string ).children();

This creates a dummy jQuery object in which you can put the string as HTML. Then, you get the children only.

How to change the status bar color in Android?

To Change the color of the status bar go to res/values-v21/styles.xml and color of status bar

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <item name="colorPrimary">@color/color_primary</item>
        <item name="colorPrimaryDark">@color/color_secondary</item>
        <item name="colorAccent">@color/color_accent</item>
        <item name="android:statusBarColor">#0000FF</item>
    </style>
</resources>

Convert dd-mm-yyyy string to date

Another possibility:

var from = "10-11-2011"; 
var numbers = from.match(/\d+/g); 
var date = new Date(numbers[2], numbers[0]-1, numbers[1]);

Match the digits and reorder them

Checking cin input stream produces an integer

There is a function in c called isdigit(). That will suit you just fine. Example:

int var1 = 'h';
int var2 = '2';

if( isdigit(var1) )
{
   printf("var1 = |%c| is a digit\n", var1 );
}
else
{
   printf("var1 = |%c| is not a digit\n", var1 );
}
if( isdigit(var2) )
{
  printf("var2 = |%c| is a digit\n", var2 );
}
else
{
   printf("var2 = |%c| is not a digit\n", var2 );
}

From here

Dump Mongo Collection into JSON format

Here's mine command for reference:

mongoexport --db AppDB --collection files --pretty --out output.json

On Windows 7 (MongoDB 3.4), one has to move the cmd to the place where mongod.exe and mongo.exe file resides => C:\MongoDB\Server\3.4\bin else it won't work saying it does not recongnize mongoexport command.

Single selection in RecyclerView

This might help for those who want a single radiobutton to work --> Radio Button RecycleView - Gist

If lambda expressions aren't supported, use this instead:

View.OnClickListener listener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        notifyItemChanged(mSelectedItem); // to update last selected item.
        mSelectedItem = getAdapterPosition();
    }
};

Cheers

How to retrieve the LoaderException property?

Another Alternative for those who are probing around and/or in interactive mode:

$Error[0].Exception.LoaderExceptions

Note: [0] grabs the most recent Error from the stack

TypeScript - Append HTML to container element in Angular 2

You could do something like this:

htmlComponent.ts

htmlVariable: string = "<b>Some html.</b>"; //this is html in TypeScript code that you need to display

htmlComponent.html

<div [innerHtml]="htmlVariable"></div> //this is how you display html code from TypeScript in your html

A server is already running. Check …/tmp/pids/server.pid. Exiting - rails

Run this command -

_x000D_
_x000D_
lsof -wni tcp:3000
_x000D_
_x000D_
_x000D_

then you will get the following table -

_x000D_
_x000D_
COMMAND  PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
ruby    2552 shyam   17u  IPv4  44599      0t0  TCP 127.0.0.1:3000 (LISTEN)
ruby    2552 shyam   18u  IPv6  44600      0t0  TCP [::1]:3000 (LISTEN)
_x000D_
_x000D_
_x000D_

Run this command and replace PID from the Above table

_x000D_
_x000D_
kill -9 PID
_x000D_
_x000D_
_x000D_

example:

_x000D_
_x000D_
kill -9 2552
_x000D_
_x000D_
_x000D_

Codeigniter how to create PDF

I've used dompdf with some success before. Although it can be a bit fussy about malformed HTML and there are still some CSS methods that aren't supported (e.g. css float does not work).

Download the package from github, and place it into a folder called dompdf in your application/thirdparty directory.

You can then create a helper with some functions to use the dompdf library, here is an example:

dompdf_helper.php :

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

function pdf_create($html, $filename='', $stream=TRUE) 
{
    include APPPATH.'thirdparty/dompdf/dompdf_config.inc.php';

    $dompdf = new DOMPDF();
    $dompdf->load_html($html);
    $dompdf->render();
    if ($stream) {
        $dompdf->stream($filename.".pdf", array("Attachment" => 0));
    } else {
        return $dompdf->output();
    }
}

You simply pass the pdf_create method your HTML as a string, the filename for the pdf file it will generate, and then an optional thirdparameter. The third parameter is a true/false flag to determine if it should save the file to your server before prompting the user to download it or not.

Could not load file or assembly '***.dll' or one of its dependencies

I recently hit this issue, the app would run fine on the developer machines and select others machines but not on recently installed machines. It turned out that the machines it did work on had the Visual C++ 11 Runtime installed while the freshly installed machines didn't. Adding the Visual C++ 11 Runtime redistributable to the app installer fixed the issue...

Javascript parse float is ignoring the decimals after my comma

For anyone arriving here wondering how to deal with this problem where commas (,) and full stops (.) might be involved but the exact number format may not be known - this is how I correct a string before using parseFloat() (borrowing ideas from other answers):

function preformatFloat(float){
   if(!float){
      return '';
   };

   //Index of first comma
   const posC = float.indexOf(',');

   if(posC === -1){
      //No commas found, treat as float
      return float;
   };

   //Index of first full stop
   const posFS = float.indexOf('.');

   if(posFS === -1){
      //Uses commas and not full stops - swap them (e.g. 1,23 --> 1.23)
      return float.replace(/\,/g, '.');
   };

   //Uses both commas and full stops - ensure correct order and remove 1000s separators
   return ((posC < posFS) ? (float.replace(/\,/g,'')) : (float.replace(/\./g,'').replace(',', '.')));
};
// <-- parseFloat(preformatFloat('5.200,75'))
// --> 5200.75

At the very least, this would allow parsing of British/American and European decimal formats (assuming the string contains a valid number).

Private class declaration

To answer your question:

If we can have inner private class then why can't we have outer private class...?

You can, the distinction is that the inner class is at the "class" access level, whereas the "outer" class is at the "package" access level. From the Oracle Tutorials:

If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes — you will learn about them in a later lesson.)

Thus, package-private (declaring no modifier) is the effect you would expect from declaring an "outer" class private, the syntax is just different.

How to change the scrollbar color using css

You can use the following attributes for webkit, which reach into the shadow DOM:

::-webkit-scrollbar              { /* 1 */ }
::-webkit-scrollbar-button       { /* 2 */ }
::-webkit-scrollbar-track        { /* 3 */ }
::-webkit-scrollbar-track-piece  { /* 4 */ }
::-webkit-scrollbar-thumb        { /* 5 */ }
::-webkit-scrollbar-corner       { /* 6 */ }
::-webkit-resizer                { /* 7 */ }

Here's a working fiddle with a red scrollbar, based on code from this page explaining the issues.

http://jsfiddle.net/hmartiro/Xck2A/1/

Using this and your solution, you can handle all browsers except Firefox, which at this point I think still requires a javascript solution.

encrypt and decrypt md5

/* you  can match the exact string with table value*/

if(md5("string to match") == $res["hashstring"])
 echo "login correct";

Lua String replace

Try:

name = "^aH^ai"
name = name:gsub("%^a", "")

See also: http://lua-users.org/wiki/StringLibraryTutorial

How do you use "git --bare init" repository?

Based on Mark Longair & Roboprog answers :

if git version >= 1.8

git init --bare --shared=group .git
git config receive.denyCurrentBranch ignore

Or :

if git version < 1.8

mkdir .git
cd .git
git init --bare --shared=group 
git config receive.denyCurrentBranch ignore

Setting unique Constraint with fluent API?

@coni2k 's answer is correct however you must add [StringLength] attribute for it to work otherwise you will get an invalid key exception (Example bellow).

[StringLength(65)]
[Index("IX_FirstNameLastName", 1, IsUnique = true)]
public string FirstName { get; set; }

[StringLength(65)]
[Index("IX_FirstNameLastName", 2, IsUnique = true)]
public string LastName { get; set; }

Convert list of ASCII codes to string (byte array) in Python

This is reviving an old question, but in Python 3, you can just use bytes directly:

>>> bytes([17, 24, 121, 1, 12, 222, 34, 76])
b'\x11\x18y\x01\x0c\xde"L'

How to check if a file exists in the Documents directory in Swift?

An alternative/recommended Code Pattern in Swift 3 would be:

  1. Use URL instead of FileManager
  2. Use of exception handling

    func verifyIfSqliteDBExists(){
        let docsDir     : URL       = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let dbPath      : URL       = docsDir.appendingPathComponent("database.sqlite")
    
        do{
            let sqliteExists : Bool = try dbPath.checkResourceIsReachable()
            print("An sqlite database exists at this path :: \(dbPath.path)")
    
        }catch{
            print("SQLite NOT Found at :: \(strDBPath)")
        }
    }
    

Handling of non breaking space: <p>&nbsp;</p> vs. <p> </p>

If I understand your issue this should work

&emsp—the em space; this should be a very wide space, typically as much as four real spaces. &ensp—the en space; this should be a somewhat wide space, roughly two regular spaces. &thinsp—this will be a narrow space, even more narrow than a regular space.

Sources: http://hea-www.harvard.edu/~fine/Tech/html-sentences.html

How can one see the structure of a table in SQLite?

.schema TableName

Where TableName is the name of the Table

How to add a Java Properties file to my Java Project in Eclipse

If you are working with core java, create your file(.properties) by right clicking your project. If the file is present inside your package or src folder it will throw an file not found error

Select all 'tr' except the first one

You could also use a pseudo class selector in your CSS like this:

.desc:not(:first-child) {
    display: none;
}

That will not apply the class to the first element with the class .desc.

Here's a JSFiddle with an example: http://jsfiddle.net/YYTFT/, and this is a good source to explain pseudo class selectors: http://css-tricks.com/pseudo-class-selectors/

how to call scalar function in sql server 2008

You have a scalar valued function as opposed to a table valued function. The from clause is used for tables. Just query the value directly in the column list.

select dbo.fun_functional_score('01091400003')

Sending an Intent to browser to open specific URL

In some cases URL may start with "www". In this case you will get an exception:

android.content.ActivityNotFoundException: No Activity found to handle Intent

The URL must always start with "http://" or "https://" so I use this snipped of code:

if (!url.startsWith("https://") && !url.startsWith("http://")){
    url = "http://" + url;
}
Intent openUrlIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(openUrlIntent);

c# how to add byte to byte array

You can't do that. It's not possible to resize an array. You have to create a new array and copy the data to it:

bArray = addByteToArray(bArray,  newByte);

code:

public byte[] addByteToArray(byte[] bArray, byte newByte)
{
    byte[] newArray = new byte[bArray.Length + 1];
    bArray.CopyTo(newArray, 1);
    newArray[0] = newByte;
    return newArray;
}

Forward declaring an enum in C++

My solution to your problem would be to either:

1 - use int instead of enums: Declare your ints in an anonymous namespace in your CPP file (not in the header):

namespace
{
   const int FUNCTIONALITY_NORMAL = 0 ;
   const int FUNCTIONALITY_RESTRICTED = 1 ;
   const int FUNCTIONALITY_FOR_PROJECT_X = 2 ;
}

As your methods are private, no one will mess with the data. You could even go further to test if someone sends you an invalid data:

namespace
{
   const int FUNCTIONALITY_begin = 0 ;
   const int FUNCTIONALITY_NORMAL = 0 ;
   const int FUNCTIONALITY_RESTRICTED = 1 ;
   const int FUNCTIONALITY_FOR_PROJECT_X = 2 ;
   const int FUNCTIONALITY_end = 3 ;

   bool isFunctionalityCorrect(int i)
   {
      return (i >= FUNCTIONALITY_begin) && (i < FUNCTIONALITY_end) ;
   }
}

2 : create a full class with limited const instantiations, like done in Java. Forward declare the class, and then define it in the CPP file, and instanciate only the enum-like values. I did something like that in C++, and the result was not as satisfying as desired, as it needed some code to simulate an enum (copy construction, operator =, etc.).

3 : As proposed before, use the privately declared enum. Despite the fact an user will see its full definition, it won't be able to use it, nor use the private methods. So you'll usually be able to modify the enum and the content of the existing methods without needing recompiling of code using your class.

My guess would be either the solution 3 or 1.

Parse query string in JavaScript

If you know that you will only have that one querystring variable you can simply do:

var dest = location.search.replace(/^.*?\=/, '');

How do I set the rounded corner radius of a color drawable using xml?

Use the <shape> tag to create a drawable in XML with rounded corners. (You can do other stuff with the shape tag like define a color gradient as well).

Here's a copy of a XML file I'm using in one of my apps to create a drawable with a white background, black border and rounded corners:

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#ffffffff"/>    
             
    <stroke android:width="3dp"
            android:color="#ff000000" />

    <padding android:left="1dp"
             android:top="1dp"
             android:right="1dp"
             android:bottom="1dp" /> 
             
    <corners android:radius="7dp" /> 
</shape>

Clean up a fork and restart it from the upstream

Love VonC's answer. Here's an easy version of it for beginners.

There is a git remote called origin which I am sure you are all aware of. Basically, you can add as many remotes to a git repo as you want. So, what we can do is introduce a new remote which is the original repo not the fork. I like to call it original

Let's add original repo's to our fork as a remote.

git remote add original https://git-repo/original/original.git

Now let's fetch the original repo to make sure we have the latest coded

git fetch original

As, VonC suggested, make sure we are on the master.

git checkout master

Now to bring our fork up to speed with the latest code on original repo, all we have to do is hard reset our master branch in accordance with the original remote.

git reset --hard original/master

And you are done :)

How do I specify "not equals to" when comparing strings in an XSLT <xsl:if>?

If you want to compare to a string literal you need to put it in (single) quotes:

<xsl:if test="Count != 'N/A'">

How can I find the number of years between two dates?

This will work and if you want the number of years replace 12 to 1

    String date1 = "07-01-2015";
    String date2 = "07-11-2015";
    int i = Integer.parseInt(date1.substring(6));
    int j = Integer.parseInt(date2.substring(6));
    int p = Integer.parseInt(date1.substring(3,5));
    int q = Integer.parseInt(date2.substring(3,5));


    int z;
    if(q>=p){
        z=q-p + (j-i)*12;
    }else{
        z=p-q + (j-i)*12;
    }
    System.out.println("The Total Months difference between two dates is --> "+z+" Months");

Removing MySQL 5.7 Completely

You need to remove the /var/lib/mysql folder. Also, purge when you remove the packages (I'm told this helps).

sudo apt-get remove --purge mysql-server mysql-client mysql-common

sudo rm -rf /var/lib/mysql

I was encountering similar issues. The second line got rid of my issues and allowed me to set up MySql from scratch. Hopefully it helps you too!

Getting a map() to return a list in Python 3.x

List-returning map function has the advantage of saving typing, especially during interactive sessions. You can define lmap function (on the analogy of python2's imap) that returns list:

lmap = lambda func, *iterable: list(map(func, *iterable))

Then calling lmap instead of map will do the job: lmap(str, x) is shorter by 5 characters (30% in this case) than list(map(str, x)) and is certainly shorter than [str(v) for v in x]. You may create similar functions for filter too.

There was a comment to the original question:

I would suggest a rename to Getting map() to return a list in Python 3.* as it applies to all Python3 versions. Is there a way to do this? – meawoppl Jan 24 at 17:58

It is possible to do that, but it is a very bad idea. Just for fun, here's how you may (but should not) do it:

__global_map = map #keep reference to the original map
lmap = lambda func, *iterable: list(__global_map(func, *iterable)) # using "map" here will cause infinite recursion
map = lmap
x = [1, 2, 3]
map(str, x) #test
map = __global_map #restore the original map and don't do that again
map(str, x) #iterator

Why does the jquery change event not trigger when I set the value of a select using val()?

If you've just added the select option to a form and you wish to trigger the change event, I've found a setTimeout is required otherwise jQuery doesn't pick up the newly added select box:

window.setTimeout(function() { jQuery('.languagedisplay').change();}, 1);

How can I print out C++ map values?

Since C++17 you can use range-based for loops together with structured bindings for iterating over your map. This improves readability, as you reduce the amount of needed first and second members in your code:

std::map<std::string, std::pair<std::string, std::string>> myMap;
myMap["x"] = { "a", "b" };
myMap["y"] = { "c", "d" };

for (const auto &[k, v] : myMap)
    std::cout << "m[" << k << "] = (" << v.first << ", " << v.second << ") " << std::endl;

Output:

m[x] = (a, b)
m[y] = (c, d)

Code on Coliru

get all keys set in memcached

Base on @mu ? answer here. I've written a cache dump script.

The script dumps all the content of a memcached server. It's tested with Ubuntu 12.04 and a localhost memcached, so your milage may vary.

#!/usr/bin/env bash

echo 'stats items'  \
| nc localhost 11211  \
| grep -oe ':[0-9]*:'  \
| grep -oe '[0-9]*'  \
| sort  \
| uniq  \
| xargs -L1 -I{} bash -c 'echo "stats cachedump {} 1000" | nc localhost 11211'

What it does, it goes through all the cache slabs and print 1000 entries of each.

Please be aware of certain limits of this script i.e. it may not scale for a 5GB cache server for example. But it's useful for debugging purposes on a local machine.

Start a fragment via Intent within a Fragment

Try this it may help you:

public void ButtonClick(View view) {
    Fragment mFragment = new YourNextFragment(); 
    getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mFragment).commit();
}

How do I detect when someone shakes an iPhone?

In iOS 8.3 (perhaps earlier) with Swift, it's as simple as overriding the motionBegan or motionEnded methods in your view controller:

class ViewController: UIViewController {
    override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent) {
        println("started shaking!")
    }

    override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
        println("ended shaking!")
    }
}