Programs & Examples On #Android animation

Animations can be integrated into Android Apps, through both Java and XML.

Animation fade in and out

we can simply use:

public void animStart(View view) {
        Log.d("count", String.valueOf(count));
        count =1;
    else if(count==1){
        Log.d("count", String.valueOf(count));
        count =0;

where i1 and i2 are defined in the onCreateView() as:

    i1 = (ImageView)findViewById(;
    i2 = (ImageView)findViewById(;

count is a class variable initilaized to 0.

The XML file is :

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android=""
            android:src="@drawable/second" />

          android:src="@drawable/first" />

@drawable/first and @drawable/second are the images in the drawable folder in res.

Show and hide a View with a slide up/down animation

Here's another way to do for multiple Button(In this case ImageView)

findViewById( View.OnClickListener() {
            public void onClick(View v) {

                if (strokeWidthIV.getAlpha() == 0f) {

                    strokeWidthIV.animate().translationXBy(-120 * 4).alpha(1f);
                    findViewById( * 3).alpha(1f);
                    findViewById( * 2).alpha(1f);
                } else {

                    strokeWidthIV.animate().translationXBy(120 * 4).alpha(0f);
                    findViewById( * 3).alpha(0f);
                    findViewById( * 2).alpha(0f);


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android=""

     android:contentDescription="Clear All"
     tools:ignore="HardcodedText" />

     android:contentDescription="Clear All"
     tools:ignore="HardcodedText" />

     android:contentDescription="Clear All"
     tools:ignore="HardcodedText" />

     android:contentDescription="Clear All"
     tools:ignore="HardcodedText" />

     tools:ignore="HardcodedText" />

How to apply slide animation between two activities in Android?

Here is a Slide Animation for you.

enter image description here

Let's say you have two activities.

  1. MovieDetailActivity
  2. AllCastActivity

And on click of a Button, this happens.

enter image description here

You can achieve this in 3 simple steps

1) Enable Content Transition

Go to your style.xml and add this line to enable the content transition.

<item name="android:windowContentTransitions">true</item>

2) Write Default Enter and Exit Transition for your AllCastActivity

public void setAnimation()
    if(Build.VERSION.SDK_INT>20) {
        Slide slide = new Slide();
        slide.setInterpolator(new AccelerateDecelerateInterpolator());

3) Start Activity with Intent

Write this method in Your MovieDetailActivity to start AllCastActivity

public void startActivity(){

Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putStringArrayListExtra(MOVIE_LIST, movie.getImages());

       ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(BlankActivity.this);
   else {

Most important!

put your setAnimation()method before setContentView() method otherwise the animation will not work.
So your AllCastActivity.javashould look like this

 class AllCastActivity extends AppcompatActivity {

   protected void onCreate(Bundle savedInstaceState)




   private void setAnimation(){

      if(Build.VERSION.SDK_INT>20) {
      Slide slide = new Slide();

How to animate a View with Translate Animation in Android

In order to move a View anywhere on the screen, I would recommend placing it in a full screen layout. By doing so, you won't have to worry about clippings or relative coordinates.

You can try this sample code:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
    android:orientation="vertical" android:id="@+id/rootLayout">

        android:text="MOVE" android:layout_centerHorizontal="true"/>

        android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>
        android:src="@drawable/ic_launcher" android:layout_centerVertical="true" android:layout_alignParentRight="true"/>
        android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_alignParentBottom="true" android:layout_marginBottom="100dip"/>

        android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false">

            android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_marginTop="150dip"/>


Your activity

public void onCreate(Bundle savedInstanceState) {

    ((Button) findViewById( )).setOnClickListener( new OnClickListener()
        public void onClick(View v)
            ImageView img = (ImageView) findViewById( );              
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( );
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( );                
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( );
            moveViewToScreenCenter( img );

private void moveViewToScreenCenter( View view )
    RelativeLayout root = (RelativeLayout) findViewById( );
    DisplayMetrics dm = new DisplayMetrics();
    this.getWindowManager().getDefaultDisplay().getMetrics( dm );
    int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();

    int originalPos[] = new int[2];
    view.getLocationOnScreen( originalPos );

    int xDest = dm.widthPixels/2;
    xDest -= (view.getMeasuredWidth()/2);
    int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;

    TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
    anim.setFillAfter( true );

The method moveViewToScreenCenter gets the View's absolute coordinates and calculates how much distance has to move from its current position to reach the center of the screen. The statusBarOffset variable measures the status bar height.

I hope you can keep going with this example. Remember that after the animation your view's position is still the initial one. If you tap the MOVE button again and again the same movement will repeat. If you want to change your view's position do it after the animation is finished.

Android translate animation - permanently move View to new position using AnimationListener

You should rather use ViewPropertyAnimator. This animates the view to its future position and you don't need to force any layout params on the view after the animation ends. And it's rather simple.



Note: This pixel is not relative to the view. This pixel is the pixel position in the screen.

Show DialogFragment with animation growing from a point

To get a full-screen dialog with animation, write the following ...


<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="actionModeBackground">?attr/colorPrimary</item>
    <item name="windowActionModeOverlay">true</item>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>

<style name="AppTheme.NoActionBar.FullScreenDialog">
    <item name="android:windowAnimationStyle">@style/Animation.WindowSlideUpDown</item>

<style name="Animation.WindowSlideUpDown" parent="@android:style/Animation.Activity">
    <item name="android:windowEnterAnimation">@anim/slide_up</item>
    <item name="android:windowExitAnimation">@anim/slide_down</item>


<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android=""



<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android=""


Java code:

public class MyDialog extends DialogFragment {

    public int getTheme() {

private void showDialog() {
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    Fragment previous = getSupportFragmentManager().findFragmentByTag(MyDialog.class.getName());
    if (previous != null) {

    MyDialog dialog = new MyDialog();, MyDialog.class.getName());

Android: show/hide a view using an animation

Try this.

    .setListener(new AnimatorListenerAdapter() {
        public void onAnimationEnd(Animator animation) {

Android Layout Animations from bottom to top and top to bottom on ImageView click

create directory in /res/anim and create bottom_to_original.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="">
        android:toYDelta="1%" />


    LinearLayout ll = findViewById(;

    Animation animation;
    animation = AnimationUtils.loadAnimation(getApplicationContext(),
    ll .setAnimation(animation);

How do android screen coordinates work?

enter image description here

This image presents both orientation(Landscape/Portrait)

To get MaxX and MaxY, read on.

For Android device screen coordinates, below concept will work.

Display mdisp = getWindowManager().getDefaultDisplay();
Point mdispSize = new Point();
int maxX = mdispSize.x; 
int maxY = mdispSize.y;

EDIT:- ** **for devices supporting android api level older than 13. Can use below code.

    Display mdisp = getWindowManager().getDefaultDisplay();
    int maxX= mdisp.getWidth();
    int maxY= mdisp.getHeight();

(x,y) :-

1) (0,0) is top left corner.

2) (maxX,0) is top right corner

3) (0,maxY) is bottom left corner

4) (maxX,maxY) is bottom right corner

here maxX and maxY are screen maximum height and width in pixels, which we have retrieved in above given code.

Android adding simple animations while setvisibility(view.Gone)

Try adding this line to the xml parent layout


Your layout will look like this

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android=""

    .......other code here


Android ImageView Animation

Inside the element put:


How to concatenate characters in java?

If you have a bunch of chars and want to concat them into a string, why not do

System.out.println("" + char1 + char2 + char3); 


Setting active profile and config location from command line in spring boot

A way that i do this on intellij is setting an environment variable on the command like so:

test setup on intellij

In this case i am setting the profile to test

Accessing certain pixel RGB value in openCV

The current version allows the cv::Mat::at function to handle 3 dimensions. So for a Mat object m,<uchar>(0,0,0) should work.

How can I simulate an array variable in MySQL?

Another way to see the same problem. Hope helpfull




SET v_tam = (SELECT (LENGTH(v_value) - LENGTH(REPLACE(v_value,',',''))));
SET v_pos = 1;

WHILE (v_tam >= v_pos)
    INSERT INTO split 
    SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(v_value,',',v_pos),',', -1);
    SET v_pos = v_pos + 1;

SELECT * FROM split;



CALL ARR('1006212,1006404,1003404,1006505,444,');

SQL: Select columns with NULL values only

An updated version of 'user2466387' version, with an additional small test which can improve performance, because it's useless to test non nullable columns:


The full code:


 @ColumnName sysname
,@DataType nvarchar(128)
,@cmd nvarchar(max)
,@TableSchema nvarchar(128) = 'dbo'
,@TableName sysname = 'TableName';

    c.TABLE_SCHEMA = @TableSchema
    AND c.TABLE_NAME = @TableName

OPEN getinfo;

FETCH NEXT FROM getinfo INTO @ColumnName, @DataType;

    SET @cmd = N'IF NOT EXISTS (SELECT * FROM ' + @TableSchema + N'.' + @TableName + N' WHERE [' + @ColumnName + N'] IS NOT NULL) RAISERROR(''' + @ColumnName + N' (' + @DataType + N')'', 0, 0) WITH NOWAIT;';
    EXECUTE (@cmd);

    FETCH NEXT FROM getinfo INTO @ColumnName, @DataType;

CLOSE getinfo;

How to make a phone call in android and come back to my activity when the call is done?

When starting your call, it looks fine.

There is a difference between android 11+ and down in bringing your app to the front though.

Android 10 or less you need to start a new intent, android 11+ you simply use BringTaskToFront

In the call state IDLE:

if (Build.VERSION.SDK_INT >= 11) {
    ActivityManager am = (ActivityManager) activity.getSystemService(Activity.ACTIVITY_SERVICE);
    am.moveTaskToFront(MyActivity.MyActivityTaskId, ActivityManager.MOVE_TASK_WITH_HOME);
} else {
    Intent intent = new Intent(activity, MyActivity.class);

I set the MyActivity.MyActivityTaskId when making the call on my activity like so, it this doesnt work, set this variable on the parent activity page of the page you want to get back to.

MyActivity.MyActivityTaskId = this.getTaskId();

MyActivityTaskId is a static variable on my activity class

public static int MyActivityTaskId = 0;

I hope this will work for you. I use the above code a bit differently, I open my app as soon as the call is answered sothat the user can see the details of the caller.

I have set some stuff in the AndroidManifest.xml as well:

/*Dont really know if this makes a difference*/
<activity android:name="MyActivity" android:taskAffinity="" android:launchMode="singleTask" />

and permissions:

<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.REORDER_TASKS" />

Please ask questions if or when you get stuck.

CSS Image size, how to fill, but not stretch?

Try something like this:

Using a container with overflow: hidden

EDIT: @Dominic Green beat me.

Is it possible to have empty RequestParam values use the defaultValue?

This was considered a bug in 2013:

and was fixed with version 3.2.2. Problem shouldn't occur in any versions after that and your code should work just fine.

How to call a JavaScript function from PHP?

You may not be able to directly do this, but the Xajax library is pretty close to what you want. I will demonstrate with an example. Here's a button on a webpage:

<button onclick="xajax_addCity();">Add New City</button> 

Our intuitive guess would be that xajax_addCity() is a Javascript function, right? Well, right and wrong. The cool thing Xajax allows is that we don't have any JS function called xajax_addCity(), but what we do have is a PHP function called addCity() that can do whatever PHP does!

<?php function addCity() { echo "Wow!"; } ?>

Think about it for a minute. We are virtually invoking a PHP function from Javascript code! That over-simplified example was just to whet the appetite, a better explanation is on the Xajax site, have fun!

How can I open a Shell inside a Vim Window?

:vsp or :sp - splits vim into two instance but you cannot use :shell in only one of them.

Why not display another tab of the terminal not another tab of vim. If you like the idea you can try it: Ctrl-shift-t. and move between them with Ctrl - pageup and Ctrl - pagedown

If you want just a few shell commands you can make any shell command in vim using !

For example :!./a.out.

How do I determine if a checkbox is checked?

The line where you define lfckv is run whenever the browser finds it. When you put it into the head of your document, the browser tries to find lifecheck id before the lifecheck element is created. You must add your script below the lifecheck input in order for your code to work.

Converting of Uri to String

Uri to String

Uri uri;
String stringUri;
stringUri = uri.toString();

String to Uri

Uri uri;
String stringUri;
uri = Uri.parse(stringUri);

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

I had the same problem, I was trying to listen the change on some select and actually the problem was I was using the event instead of the which is the select object.


$(document).on('change', $("select"), function(el) {


$(document).on('change', $("select"), function(el) {

Using an IF Statement in a MySQL SELECT query

try this code worked for me

SELECT user_display_image AS user_image,
       user_display_name AS user_name,
       (CASE WHEN invitee_status = 1 THEN "attending"
             WHEN invitee_status = 2 THEN "unsure"
             WHEN invitee_status = 3 THEN "declined"
             WHEN invitee_status = 0 THEN "notreviwed"
       END) AS invitee_status
  FROM your_table

What do I do when my program crashes with exception 0xc0000005 at address 0?

I was getting the same issue with a different application,

Faulting application name: javaw.exe, version:, time stamp: 0x55763d32
Faulting module name: mscorwks.dll, version: 2.0.50727.5485, time stamp: 0x53a11d6c
Exception code: 0xc0000005
Fault offset: 0x0000000000501090
Faulting process id: 0x2960
Faulting application start time: 0x01d0c39a93c695f2
Faulting application path: C:\Program Files\Java\jre1.8.0_51\bin\javaw.exe
Faulting module path:C:\Windows\Microsoft.NET\Framework64\v2.0.50727\mscorwks.dll

I was using the The Enhanced Mitigation Experience Toolkit (EMET) from Microsoft and I found by disabling the EMET features on javaw.exe in my case as this was the faulting application, it enabled my application to run successfully. Make sure you don't have any similar software with security protections on memory.

How to create multiple class objects with a loop in python?

you can use list to define it.

objs = list()
for i in range(10):

Access-Control-Allow-Origin Multiple Origin Domains?

For a fairly easy copy / paste for .NET applications, I wrote this to enable CORS from within a global.asax file. This code follows the advice given in the currently accepted answer, reflecting whatever origin back is given in the request into the response. This effectively achieves '*' without using it.

The reason for this is that it enables multiple other CORS features, including the ability to send an AJAX XMLHttpRequest with the 'withCredentials' attribute set to 'true'.

void Application_BeginRequest(object sender, EventArgs e)
    if (Request.HttpMethod == "OPTIONS")
        Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
        Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
        Response.AddHeader("Access-Control-Max-Age", "1728000");
        Response.AddHeader("Access-Control-Allow-Credentials", "true");

        if (Request.Headers["Origin"] != null)
            Response.AddHeader("Access-Control-Allow-Origin" , Request.Headers["Origin"]);
            Response.AddHeader("Access-Control-Allow-Origin" , "*");

How to set up devices for VS Code for a Flutter emulator

For me, when I was running "flutter doctor" command from Ubuntu Command line - It showed me below error.

[?] Android toolchain - develop for Android devices ? Unable to locate Android SDK.

From this error, it is obvious that "flutter doctor" was not able to find the "android sdk" and the reason for that was my android sdk was downloaded in a custom location on my Ubuntu machine.

So we must need to tell "flutter doctor" about this custom android location, using below command,

flutter config --android-sdk /home/myhome/Downloads/softwares/android-sdk/

Need to replace /home/myhome/Downloads/softwares/android-sdk/ with path to your custom location/place where android sdk is available.

Once this is done, and re-run "flutter doctor" and now it has detected the android sdk location and hence I could run avd/emulator by typing "flutter run"

Undefined symbols for architecture i386

well i found a solution to this problem for who want to work with xCode 4. All what you have to do is importing frameworks from the SimulatorSDK folder /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk/System/Library/Frameworks

i don't know if it works when you try to test your app on a real iDevice, but i'm sure that it works on simulator.


What should I use to open a url instead of urlopen in urllib3

With gazpacho you could pipeline the page straight into a parse-able soup object:

from gazpacho import Soup
url = ""
soup = Soup.get(url)

And run finds on top of it:


How can I get table names from an MS Access Database?

You can use schemas in Access.

Sub ListAccessTables2(strDBPath)
   Dim cnnDB As ADODB.Connection
   Dim rstList As ADODB.Recordset

   Set cnnDB = New ADODB.Connection

   ' Open the connection.
   With cnnDB
      .Provider = "Microsoft.Jet.OLEDB.4.0"
      .Open strDBPath
   End With

   ' Open the tables schema rowset.
   Set rstList = cnnDB.OpenSchema(adSchemaTables)

   ' Loop through the results and print the
   ' names and types in the Immediate pane.
   With rstList
      Do While Not .EOF
         If .Fields("TABLE_TYPE") <> "VIEW" Then
            Debug.Print .Fields("TABLE_NAME") & vbTab & _
         End If
   End With
   Set cnnDB = Nothing
End Sub


How can getContentResolver() be called in Android?

The getContentResolver()method is also used when you query a Contact, using a Cursor object. I have used getContentResolver() to query the Android phone Contacts app, looking for contact info from a person's phone number, to include in my app. The different elements in a query (as shown below) represent what kind of contact details you want, and if they should be ordered, etc. Here is another example.

From the Content Provider Basics page from Android docs.

// Queries the user dictionary and returns results
mCursor = getContentResolver().query(
    UserDictionary.Words.CONTENT_URI,   // The content URI of the words table
    mProjection,                        // The columns to return for each row
    mSelectionClause                    // Selection criteria
    mSelectionArgs,                     // Selection criteria
    mSortOrder);                        // The sort order for the returned rows

HTML page disable copy/paste

You cannot prevent people from copying text from your page. If you are trying to satisfy a "requirement" this may work for you:

<body oncopy="return false" oncut="return false" onpaste="return false">

How to disable Ctrl C/V using javascript for both internet explorer and firefox browsers

A more advanced aproach:

How to detect Ctrl+V, Ctrl+C using JavaScript?

Edit: I just want to emphasise that disabling copy/paste is annoying, won't prevent copying and is 99% likely a bad idea.

How to uninstall a package installed with pip install --user

I am running Anaconda version 4.3.22 and a python3.6.1 environment, and had this problem. Here's the history and the fix:

pip uninstall opencv-python # -- the original step. failed.

ImportError: DLL load failed: The specified module could not be found.

I did this into my python3.6 environment and got this error.

python -m pip install opencv-python # same package as above.
conda install -c conda-forge opencv # separate install parallel to opencv
pip-install opencv-contrib-python # suggested by another user here. doesn't resolve it.

Next, I tried downloading python3.6 and putting the python3.dll in the folder and in various folders. nothing changed.

finally, this fixed it:

pip uninstall opencv-python

(the other conda-forge version is still installed) This left only the conda version, and that works in 3.6.

>>>import cv2


What is the purpose of willSet and didSet in Swift?

The many well-written existing answers cover the question well, but I'll mention, in some detail, an addition that I believe is worth covering.

The willSet and didSet property observers can be used to call delegates, e.g., for class properties that are only ever updated by user interaction, but where you want to avoid calling the delegate at object initialization.

I'll cite Klaas up-voted comment to the accepted answer:

willSet and didSet observers are not called when a property is first initialized. They are only called when the property’s value is set outside of an initialization context.

This is a quite neat as it means e.g. the didSet property is a good choice of launch point for delegate callbacks & functions, for your own custom classes.

As an example, consider some custom user control object, with some key property value (e.g. position in rating control), implemented as a subclass of UIView:

// CustomUserControl.swift
protocol CustomUserControlDelegate {
    func didChangeValue(value: Int)
    // func didChangeValue(newValue: Int, oldValue: Int)
    // func didChangeValue(customUserControl: CustomUserControl)
    // ... other more sophisticated delegate functions

class CustomUserControl: UIView {

    // Properties
    // ...
    private var value = 0 {
        didSet {
            // Possibly do something ...

            // Call delegate.
            // delegate?.didChangeValue(value, oldValue: oldValue)
            // delegate?.didChangeValue(self)

    var delegate: CustomUserControlDelegate?

    // Initialization
    required init?(...) { 
        // Initialise something ...

        // E.g. 'value = 1' would not call didSet at this point

    // ... some methods/actions associated with your user control.

After which your delegate functions can be used in, say, some view controller to observe key changes in the model for CustomViewController, much like you'd use the inherent delegate functions of the UITextFieldDelegate for UITextField objects (e.g. textFieldDidEndEditing(...)).

For this simple example, use a delegate callback from the didSet of the class property value to tell a view controller that one of it's outlets have had associated model update:

// ViewController.swift
Import UIKit
// ...

class ViewController: UIViewController, CustomUserControlDelegate {

    // Properties
    // ...
    @IBOutlet weak var customUserControl: CustomUserControl!

    override func viewDidLoad() {
        // ...

        // Custom user control, handle through delegate callbacks.
        customUserControl = self

    // ...

    // CustomUserControlDelegate
    func didChangeValue(value: Int) {
        // do some stuff with 'value' ...

    // func didChangeValue(newValue: Int, oldValue: Int) {
        // do some stuff with new as well as old 'value' ...
        // custom transitions? :)

    //func didChangeValue(customUserControl: CustomUserControl) {
    //    // Do more advanced stuff ...

Here, the value property has been encapsulated, but generally: in situations like these, be careful not to update the value property of the customUserControl object in the scope of the associated delegate function (here: didChangeValue()) in the view controller, or you'll end up with infinite recursion.

Assert equals between 2 Lists in Junit

You can use assertEquals in junit.

import org.junit.Assert;   
import org.junit.Test;

    public void test_array_pass()
        List<String> actual = Arrays.asList("fee", "fi", "foe");
        List<String> expected = Arrays.asList("fee", "fi", "foe");

If the order of elements is different then it will return error.

If you are asserting a model object list then you should override the equals method in the specific model.

    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        if (obj != null && obj instanceof ModelName) {
            ModelName other = (ModelName) obj;
            return this.getItem().equals(other.getItem()) ;
        return false;

How to parse unix timestamp to time.Time

Sharing a few functions which I created for dates:

Please note that I wanted to get time for a particular location (not just UTC time). If you want UTC time, just remove loc variable and .In(loc) function call.

func GetTimeStamp() string {
     loc, _ := time.LoadLocation("America/Los_Angeles")
     t := time.Now().In(loc)
     return t.Format("20060102150405")
func GetTodaysDate() string {
    loc, _ := time.LoadLocation("America/Los_Angeles")
    current_time := time.Now().In(loc)
    return current_time.Format("2006-01-02")

func GetTodaysDateTime() string {
    loc, _ := time.LoadLocation("America/Los_Angeles")
    current_time := time.Now().In(loc)
    return current_time.Format("2006-01-02 15:04:05")

func GetTodaysDateTimeFormatted() string {
    loc, _ := time.LoadLocation("America/Los_Angeles")
    current_time := time.Now().In(loc)
    return current_time.Format("Jan 2, 2006 at 3:04 PM")

func GetTimeStampFromDate(dtformat string) string {
    form := "Jan 2, 2006 at 3:04 PM"
    t2, _ := time.Parse(form, dtformat)
    return t2.Format("20060102150405")

Using Mysql in the command line in osx - command not found?

That means /usr/local/mysql/bin/mysql is not in the PATH variable..

Either execute /usr/local/mysql/bin/mysql to get your mysql shell,

or type this in your terminal:


to add that to your PATH variable so you can just run mysql without specifying the path

OpenSSL Command to check if a server is presenting a certificate

I was debugging an SSL issue today which resulted in the same write:errno=104 error. Eventually I found out that the reason for this behaviour was that the server required SNI (servername TLS extensions) to work correctly. Supplying the -servername option to openssl made it connect successfully:

openssl s_client -connect domain.tld:443 -servername domain.tld

Hope this helps.

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

I hope this answer is not considered too off-topic, but I had a similar issue where I was looking for a tool to parse only parts of a nested JSON which is not that straightforward with the accepted solutions.

If you have a similar issue, it might be worth to check out JTokken as described in this original post or in my answer to a similar question.

How to undo the last commit in git

I think you haven't messed up yet. Try:

git reset HEAD^

This will bring the dir to state before you've made the commit, HEAD^ means the parent of the current commit (the one you don't want anymore), while keeping changes from it (unstaged).

Changing java platform on which netbeans runs

on Fedora it is currently impossible to set a new jdk-HOME to some sdk. They designed it such that it will always break. Try --jdkhome [whatever] but in all likelihood it will break and show some cryptic nonsensical error message as usual.

keyCode values for numeric keypad?

Yes, they are different and while many people have made a great suggestion of using console.log to see for yourself. However, I didn't see anyone mention event.location that you can use that to determine if the number is coming from the keypad event.location === 3 vs the top of the main keyboard / general keys event.location === 0. This approach would be best suited for when you need to generally determine if keystrokes are coming from a region of the keyboard or not, event.key is likely better for the specific keys.

Service Reference Error: Failed to generate code for the service reference

face same issue, resolved by running Visual Studio in Admin mode

How to find where javaw.exe is installed?

Open a cmd shell,

cd \\
dir javaw.exe /s

How do I tokenize a string sentence in NLTK?

This is actually on the main page of

>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']

How do I get IntelliJ to recognize common Python modules?

Use a Requirements File (see link to JetBrains documentation)

In my case I needed arrow. So, I added


to my projects requirements.txt

Then Intellij prompted me to add the library the first time that I wrote import arrow in a Python script

Targeting both 32bit and 64bit with Visual Studio in same solution/project

You can use a condition to an ItemGroup for the dll references in the project file.
This will cause visual studio to recheck the condition and references whenever you change the active configuration.
Just add a condition for each configuration.


 <ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
    <Reference Include="DLLName">
    <ProjectReference Include="..\MyOtherProject.vcxproj">

if (select count(column) from table) > 0 then

You cannot directly use a SQL statement in a PL/SQL expression:

SQL> begin
  2     if (select count(*) from dual) >= 1 then
  3        null;
  4     end if;
  5  end;
  6  /
        if (select count(*) from dual) >= 1 then
ERROR at line 2:
ORA-06550: line 2, column 6:
PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:

You must use a variable instead:

SQL> set serveroutput on
SQL> declare
  2     v_count number;
  3  begin
  4     select count(*) into v_count from dual;
  6     if v_count >= 1 then
  7             dbms_output.put_line('Pass');
  8     end if;
  9  end;
 10  /

PL/SQL procedure successfully completed.

Of course, you may be able to do the whole thing in SQL:

update my_table
set x = y
where (select count(*) from other_table) >= 1;

It's difficult to prove that something is not possible. Other than the simple test case above, you can look at the syntax diagram for the IF statement; you won't see a SELECT statement in any of the branches.

What __init__ and self do in Python?

Yep, you are right, these are oop constructs.

__init__ is the constructor for a class. The self parameter refers to the instance of the object (like this in C++).

class Point:
    def __init__(self, x, y):
        self._x = x
        self._y = y

The __init__ method gets called when memory for the object is allocated:

x = Point(1,2)

It is important to use the self parameter inside an object's method if you want to persist the value with the object. If, for instance, you implement the __init__ method like this:

class Point:
    def __init__(self, x, y):
        _x = x
        _y = y

Your x and y parameters would be stored in variables on the stack and would be discarded when the init method goes out of scope. Setting those variables as self._x and self._y sets those variables as members of the Point object (accessible for the lifetime of the object).

How to make an HTTP get request with parameters

First WebClient is easier to use; GET arguments are specified on the query-string - the only trick is to remember to escape any values:

        string address = string.Format(
            Uri.EscapeDataString("escape me"),
            Uri.EscapeDataString("& me !!"));
        string text;
        using (WebClient client = new WebClient())
            text = client.DownloadString(address);

No numeric types to aggregate - change in groupby() behaviour?

How are you generating your data?

See how the output shows that your data is of 'object' type? the groupby operations specifically check whether each column is a numeric dtype first.

In [31]: data
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2557 entries, 2004-01-01 00:00:00 to 2010-12-31 00:00:00
Freq: <1 DateOffset>
Columns: 360 entries, -89.75 to 89.75
dtypes: object(360)

look ?

Did you initialize an empty DataFrame first and then filled it? If so that's probably why it changed with the new version as before 0.9 empty DataFrames were initialized to float type but now they are of object type. If so you can change the initialization to DataFrame(dtype=float).

You can also call frame.astype(float)

SVN 405 Method Not Allowed

I got this error because I replaced URL address with new one ending up with "/". I mean record in wc.db database in .svn folder in REPOSITORY table.

When I removed sign: "/" then the error went away.

Android offline documentation and sample codes

This thread is a little old, and I am brand new to this, but I think I found the preferred solution.

First, I assume that you are using Eclipse and the Android ADT plugin.

In Eclipse, choose Window/Android SDK Manager. In the display, expand the entry for the MOST RECENT PLATFORM, even if that is not the platform that your are developing for. As of Jan 2012, it is "Android 4.0.3 (API 15)". When expanded, the first entry is "Documentation for Android SDK" Click the checkbox next to it, and then click the "Install" button.

When done, you should have a new directory in your "android-sdks" called "doc". Look for "offline.html" in there. Since this is packaged with the most recent version, it will document the most recent platform, but it should also show the APIs for previous versions.

Get value from SimpleXMLElement Object

if you don't know the value of XML Element, you can use

$value = (string) $xml->code[0]->lat;

if (ctype_digit($value)) {
    // the value is probably an integer because consists only of digits

It works when you need to determine if value is a number, because (string) will always return string and is_int($value) returns false

Multiple radio button groups in MVC 4 Razor

I fixed a similar issue building a RadioButtonFor with pairs of text/value from a SelectList. I used a ViewBag to send the SelectList to the View, but you can use data from model too. My web application is a Blog and I have to build a RadioButton with some types of articles when he is writing a new post.

The code below was simplyfied.

List<SelectListItem> items = new List<SelectListItem>();

Dictionary<string, string> dictionary = new Dictionary<string, string>();

dictionary.Add("Texto", "1");
dictionary.Add("Foto", "2");
dictionary.Add("Vídeo", "3");

foreach (KeyValuePair<string, string> pair in objBLL.GetTiposPost())
    items.Add(new SelectListItem() { Text = pair.Key, Value = pair.Value, Selected = false });

ViewBag.TiposPost = new SelectList(items, "Value", "Text");

In the View, I used a foreach to build a radiobutton.

<div class="form-group">
    <div class="col-sm-10">
        @foreach (var item in (SelectList)ViewBag.TiposPost)
            @Html.RadioButtonFor(model => model.IDTipoPost, item.Value, false)
            <label class="control-label">@item.Text</label>


Notice that I used RadioButtonFor in order to catch the option value selected by user, in the Controler, after submit the form. I also had to put the item.Text outside the RadioButtonFor in order to show the text options.

Hope it's useful!

How to use forEach in vueJs?

In VueJS you can loop through an array like this : const array1 = ['a', 'b', 'c'];

Array.from(array1).forEach(element => 

in my case I want to loop through files and add their types to another array:

 Array.from(files).forEach((file) => {
       if(this.mediaTypes.image.includes(file.type)) {

JUnit 5: How to assert an exception is thrown?

Actually I think there is a error in the documentation for this particular example. The method that is intended is expectThrows

public static void assertThrows(
public static <T extends Throwable> T expectThrows(

Java double comparison epsilon

While I agree with the idea that double is bad for money, still the idea of comparing doubles has interest. In particular the suggested use of epsilon is only suited to numbers in a specific range. Here is a more general use of an epsilon, relative to the ratio of the two numbers (test for 0 is omitted):

boolean equal(double d1, double d2) {
  double d = d1 / d2;
  return (Math.abs(d - 1.0) < 0.001);

How to open a new window on form submit

i believe this jquery work for you well please check a code below.

this will make your submit action works and open a link in new tab whether you want to open action url again or a new link

setTimeout(function () {'','_blank');}, 1000);});})

This code works for me perfect..

How to configure SMTP settings in web.config

Web.Config file:

            <smtp from="[email protected]">
                <network host="" 
                 userName="[email protected]" 

limit text length in php and provide 'Read more' link

I have combine two different answers:

  1. Limit the characters
  2. Complete HTML missing tags

    $string = strip_tags($strHTML);
    $yourText = $strHTML;
    if (strlen($string) > 350) {
        $stringCut = substr($post->body, 0, 350);
        $doc = new DOMDocument();
        $yourText = $doc->saveHTML();
    $yourText."...<a href=''>View More</a>"

In Python, is there an elegant way to print a list in a custom format without explicit looping?

l = [1, 2, 3]
print '\n'.join(['%i: %s' % (n, l[n]) for n in xrange(len(l))])

Class JavaLaunchHelper is implemented in two places

I am using Intellij Idea 2017 and I got into the same problem. What solved the problem for me was to simply

  1. close the project in intelliJ
  2. File -> New -> project from existing resources
  3. use Import from external model (if any)
  4. open the project again.

POST JSON fails with 415 Unsupported media type, Spring 3 mvc

I faced this issue when I integrated spring boot with spring mvc. I solved it by just adding these dependencies.


Java sending and receiving file (byte[]) over sockets

Adding up on EJP's answer; use this for more fluidity. Make sure you don't put his code inside a bigger try catch with more code between the .read and the catch block, it may return an exception and jump all the way to the outer catch block, safest bet is to place EJPS's while loop inside a try catch, and then continue the code after it, like:

int count;
byte[] bytes = new byte[4096];
try {
    while ((count = > 0) {
        bos.write(bytes, 0, count);
} catch ( Exception e )
    //It will land here....
// Then continue from here

EDIT: ^This happened to me cuz I didn't realize you need to put socket.shutDownOutput() if it's a client-to-server stream!

Hope this post solves any of your issues

Exposing the current state name with ui router

In my current project the solution looks like this:

I created an abstract Language State

$stateProvider.state('language', {
    abstract: true,
    url: '/:language',
    template: '<div ui-view class="lang-{{language}}"></div>'

Every state in the project has to depend on this state

$stateProvider.state('language.dashboard', {
    url: '/dashboard'

The language switch buttons calls a custom function:

<a ng-click="footer.setLanguage('de')">de</a>

And the corresponding function looks like this (inside a controller of course):

this.setLanguage = function(lang) {
    FooterLog.log('switch to language', lang);
    $state.go($state.current, { language: lang }, {
        location: true,
        reload: true,
        inherit: true
    }).then(function() {
        FooterLog.log('transition successfull');

This works, but there is a nicer solution just changing a value in the state params from html:

<a ui-sref="{ language: 'de' }">de</a>

Unfortunately this does not work, see

Simple dynamic breadcrumb

Hmm, from the examples you gave it seems like "$_SERVER['REQUEST_URI']" and the explode() function could help you. You could use explode to break up the URL following the domain name into an array, separating it at each forward-slash.

As a very basic example, something like this could be implemented:

$crumbs = explode("/",$_SERVER["REQUEST_URI"]);
foreach($crumbs as $crumb){
    echo ucfirst(str_replace(array(".php","_"),array(""," "),$crumb) . ' ');

How can I export a GridView.DataSource to a datatable or dataset?


I was having the same issue as you, and this is the code I used to figure it out. Although, I don't use the footer row section for my purposes, I did include it in this code.

    DataTable dt = new DataTable();

    // add the columns to the datatable            
    if (GridView1.HeaderRow != null)

        for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)

    //  add each of the data rows to the table
    foreach (GridViewRow row in GridView1.Rows)
        DataRow dr;
        dr = dt.NewRow();

        for (int i = 0; i < row.Cells.Count; i++)
            dr[i] = row.Cells[i].Text.Replace("&nbsp;","");

    //  add the footer row to the table
    if (GridView1.FooterRow != null)
        DataRow dr;
        dr = dt.NewRow();

        for (int i = 0; i < GridView1.FooterRow.Cells.Count; i++)
            dr[i] = GridView1.FooterRow.Cells[i].Text.Replace("&nbsp;","");

How to read the Stock CPU Usage data

So far this has been the most helpful source of information regarding this I could find. Apparently the numbers do NOT reperesent load average in %:

Initializing C# auto-properties

This will be possible in C# 6.0:

public int Y { get; } = 2;

How do I initialize an empty array in C#?

Try this:

string[] a = new string[] { };

Most efficient way to append arrays in C#?

Olmo's suggestion is very good, but I'd add this: If you're not sure about the size, it's better to make it a little bigger than a little smaller. When a list is full, keep in mind it will double its size to add more elements.

For example: suppose you will need about 50 elements. If you use a 50 elements size and the final number of elements is 51, you'll end with a 100 sized list with 49 wasted positions.

OpenSSL and error in reading openssl.conf file

I had the same issue on Windows. It was resolved by setting the environment variable as follow:

Variable name: OPENSSL_CONF Variable value: C:(OpenSSl Directory)\bin\openssl.cnf

How can I get a collection of keys in a JavaScript dictionary?

For new browsers: Object.keys( MY_DICTIONARY ) will return an array of keys. Else you may want to go the old school way:

var keys = []
for(var key in dic) keys.push( key );

How large is a DWORD with 32- and 64-bit code?

No ... on all Windows platforms DWORD is 32 bits. LONGLONG or LONG64 is used for 64 bit types.

C#, Looping through dataset and show each record from a dataset column

DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());

How can prepared statements protect from SQL injection attacks?

When you create and send a prepared statement to the DBMS, it's stored as the SQL query for execution.

You later bind your data to the query such that the DBMS uses that data as the query parameters for execution (parameterization). The DBMS doesn't use the data you bind as a supplemental to the already compiled SQL query; it's simply the data.

This means it's fundamentally impossible to perform SQL injection using prepared statements. The very nature of prepared statements and their relationship with the DBMS prevents this.

Can a Windows batch file determine its own file name?


Use the special %0 variable to get the path to the current file.

Write %~n0 to get just the filename without the extension.

Write %~n0%~x0 to get the filename and extension.

Also possible to write %~nx0 to get the filename and extension.

ggplot2 plot area margins?

You can adjust the plot margins with plot.margin in theme() and then move your axis labels and title with the vjust argument of element_text(). For example :

qplot(rnorm(100)) +
    ggtitle("Title") +
    theme(axis.title.x=element_text(vjust=-2)) +
    theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
    theme(plot.title=element_text(size=15, vjust=3)) +
    theme(plot.margin = unit(c(1,1,1,1), "cm"))

will give you something like this :

enter image description here

If you want more informations about the different theme() parameters and their arguments, you can just enter ?theme at the R prompt.

How to fix "unable to write 'random state' " in openssl

slf4j: how to log formatted message, object array, exception

In addition to @Ceki 's answer, If you are using logback and setup a config file in your project (usually logback.xml), you can define the log to plot the stack trace as well using

    <pattern>%date |%-5level| [%thread] [%file:%line] - %msg%n%ex{full}</pattern> 

the %ex in pattern is what makes the difference

"Unable to launch the IIS Express Web server" error

So after trying all the solution, I just uninstall "One Drive" from my PC & the problem is resolved.


  • I was trying to run .net core web application.
  • Visual Studio 2017 version 15.9.5
  • Windows 10 Pro, 64 bit


If you're using a real device, you've simply run out of internal memory. Just go to Android settings -> Applications, and move some apps to the SD card or uninstall some apps.

If you're using the emulator, see RacZo's answer.

JQuery confirm dialog

Try this one

  .html('<div><h6>Yes or No?</h6></div>')
      modal: true, title: 'message', zIndex: 10000, autoOpen: true,
      width: 'auto', resizable: false,
      buttons: {
          Yes: function () {
          No: function () {
      close: function (event, ui) {


Typescript interface default values

You could use two separate configs. One as the input with optional properties (that will have default values), and another with only the required properties. This can be made convenient with & and Required:

interface DefaultedFuncConfig {
  b?: boolean;

interface MandatoryFuncConfig {
  a: boolean;

export type FuncConfig = MandatoryFuncConfig & DefaultedFuncConfig;
export const func = (config: FuncConfig): Required<FuncConfig> => ({
  b: true,

// will compile
func({ a: true });
func({ a: true, b: true });

// will error
func({ b: true });

JavaScript Number Split into individual digits

I used this simple way of doing it.

To split digits

var N = 69;
var arr = N.toString().split('').map(Number)
// outputs [6,9]
console.log( arr ); 

To add them together

console.log(arr.reduce( (a,b) => a+b )); // 15

moving committed (but not pushed) changes to a new branch after pull

What about:

  1. Branch from the current HEAD.
  2. Make sure you are on master, not your new branch.
  3. git reset back to the last commit before you started making changes.
  4. git pull to re-pull just the remote changes you threw away with the reset.

Or will that explode when you try to re-merge the branch?

What does "xmlns" in XML mean?

I think the biggest confusion is that xml namespace is pointing to some kind of URL that doesn't have any information. But the truth is that the person who invented below namespace:


could also call it like that:


This is just a unique identifier. However it is established that you should put there URL that is unique and can potentially point to the specification of used tags/attributes in that namespace. It's not required tho.

Why it should be unique? Because namespaces purpose is to have them unique so the attribute for example called background from your namespace can be distinguished from the background from another namespace.

Because of that uniqueness you do not need to worry that if you create your custom attribute you gonna have name collision.

How to install PostgreSQL's pg gem on Ubuntu?

apt-get install ruby-dev worked for me.

align images side by side in html

You mean something like this?

<div class="image123">
    <div class="imgContainer">
        <img src="/images/tv.gif" height="200" width="200"/>
        <p>This is image 1</p>
    <div class="imgContainer">
        <img class="middle-img" src="/images/tv.gif"/ height="200" width="200"/>
        <p>This is image 2</p>
    <div class="imgContainer">
         <img src="/images/tv.gif"/ height="200" width="200"/>
        <p>This is image 3</p>

with the imgContainer style as


Also see this jsfiddle.

How do I ignore files in Subversion?

If you are using TortoiseSVN, right-click on a file and then select TortoiseSVN / Add to ignore list. This will add the file/wildcard to the svn:ignore property.

svn:ignore will be checked when you are checking in files, and matching files will be ignored. I have the following ignore list for a Visual Studio .NET project:

bin obj

You can find this list in the context menu at TortoiseSVN / Properties.

CryptographicException 'Keyset does not exist', but only through WCF

Received this error while using the openAM Fedlet on IIS7

Changing the user account for the default website resolved the issue. Ideally, you would want this to be a service account. Perhaps even the IUSR account. Suggest looking up methods for IIS hardening to nail it down completely.

How to convert ISO8859-15 to UTF8?

in my case, the file command tells a wrong encoding, so i tried converting with all the possible encodings, and found out the right one.

execute this script and check the result file.

for i in `iconv -l`
   echo $i
   iconv -f $i -t UTF-8 yourfile | grep "hint to tell converted success or not"
done &>/tmp/converted

how do I initialize a float to its max/min value?

May I suggest that you initialize your "max and min so far" variables not to infinity, but to the first number in the array?

Have a variable in images path in Sass?

Was searching around for an answer to the same question, but think I found a better solution:

Basically, you can set your image path in config.rb and you use the image-url() helper

How to add a response header on nginx when using proxy_pass?

As oliver writes:

add_header works as well with proxy_pass as without.

However, as Shane writes, as of Nginx 1.7.5, you must pass always in order to get add_header to work for error responses, like so:

add_header  X-Upstream  $upstream_addr always;

How to make shadow on border-bottom?

New method for an old question

enter image description here

It seems like in the answers provided the issue was always how the box border would either be visible on the left and right of the object or you'd have to inset it so far that it didn't shadow the whole length of the container properly.

This example uses the :after pseudo element along with a linear gradient with transparency in order to put a drop shadow on a container that extends exactly to the sides of the element you wish to shadow.

Worth noting with this solution is that if you use padding on the element that you wish to drop shadow, it won't display correctly. This is because the after pseudo element appends it's content directly after the elements inner content. So if you have padding, the shadow will appear inside the box. This can be overcome by eliminating padding on outer container (where the shadow applies) and using an inner container where you apply needed padding.

Example with padding and background color on the shadowed div:

enter image description here

If you want to change the depth of the shadow, simply increase the height style in the after pseudo element. You can also obviously darken, lighten, or change colors in the linear gradient styles.

body {_x000D_
  background: #eee;_x000D_
.bottom-shadow {_x000D_
  width: 80%;_x000D_
  margin: 0 auto;_x000D_
.bottom-shadow:after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  height: 8px;_x000D_
  background: transparent;_x000D_
  background: -moz-linear-gradient(top, rgba(0,0,0,0.4) 0%, rgba(0,0,0,0) 100%); /* FF3.6-15 */_x000D_
  background: -webkit-linear-gradient(top, rgba(0,0,0,0.4) 0%,rgba(0,0,0,0) 100%); /* Chrome10-25,Safari5.1-6 */_x000D_
  background: linear-gradient(to bottom, rgba(0,0,0,0.4) 0%,rgba(0,0,0,0) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient(   startColorstr='#a6000000', endColorstr='#00000000',GradientType=0 ); /* IE6-9 */_x000D_
.bottom-shadow div {_x000D_
  padding: 18px;_x000D_
  background: #fff;_x000D_
<div class="bottom-shadow">_x000D_
    Shadows, FTW!_x000D_

Check if a number is a perfect square

The idea is to run a loop from i = 1 to floor(sqrt(n)) then check if squaring it makes n.

bool isPerfectSquare(int n) 
    for (int i = 1; i * i <= n; i++) { 

        // If (i * i = n) 
        if ((n % i == 0) && (n / i == i)) { 
            return true; 
    return false; 

Get source JARs from Maven repository

You can, if they are uploaded. Generally they are called "frameworkname-version-source(s)"

Array.sort() doesn't sort numbers correctly

The default sort for arrays in Javascript is an alphabetical search. If you want a numerical sort, try something like this:

var a = [ 1, 100, 50, 2, 5];
a.sort(function(a,b) { return a - b; });

Genymotion Android emulator - adb access?

Simply do this, with genymotion device running you can open Virtual Box , and see that there is a VM for you device , then go to network Settings of the VM, NAT and do port forwarding of local 5555 to remote 5555 screen attachedVirtual Box Nat Network Port forwarding

Openssl : error "self signed certificate in certificate chain"

If you're running Charles and trying to build a container then you'll most likely get this error.

Make sure to disable Charles (macos) proxy under proxy -> macOS proxy

Charles is an

HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP and SSL / HTTPS traffic between their machine and the Internet.

So anything similar may cause the same issue.


The delete with the cascade option only applied to tables with foreign keys defined. If you do a delete, and it says you cannot because it would violate the foreign key constraint, the cascade will cause it to delete the offending rows.

If you want to delete associated rows in this way, you will need to define the foreign keys first. Also, remember that unless you explicitly instruct it to begin a transaction, or you change the defaults, it will do an auto-commit, which could be very time consuming to clean up.

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

To differentiate the routes, try adding a constraint that id must be numeric:

         name: "DefaultApi",
         routeTemplate: "api/{controller}/{id}",
         constraints: new { id = @"\d+" }, // Only matches if "id" is one or more digits.
         defaults: new { id = System.Web.Http.RouteParameter.Optional }

Java: Local variable mi defined in an enclosing scope must be final or effectively final

As I can see the array is of String only.For each loop can be used to get individual element of the array and put them in local inner class for use.

Below is the code snippet for it :

    for (String color : colors ){

String pos = Character.toUpperCase(color.charAt(0)) + color.substring(1);
JMenuItem Jmi =new JMenuItem(pos);
Jmi.setIcon(new IconA(color));

Jmi.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JMenuItem item = (JMenuItem) e.getSource();
            IconA icon = (IconA) item.getIcon();
            // HERE YOU USE THE String color variable and no errors!!!
            Color kolorIkony = getColour(color); 



Xcode stuck on Indexing

Close Your Xcode , close any git client(source tree or terminal)if it is opened and finally restart your project.

Conda uninstall one package and one package only

You can use conda remove --force.

The documentation says:

--force               Forces removal of a package without removing packages
                      that depend on it. Using this option will usually
                      leave your environment in a broken and inconsistent

Escape single quote character for use in an SQLite query

Just in case if you have a loop or a json string that need to insert in the database. Try to replace the string with a single quote . here is my solution. example if you have a string that contain's a single quote.

String mystring = "Sample's";
String myfinalstring = mystring.replace("'","''");

 String query = "INSERT INTO "+table name+" ("+field1+") values ('"+myfinalstring+"')";

this works for me in c# and java

Convert MFC CString to integer

The problem with the accepted answer is that it cannot signal failure. There's strtol (STRing TO Long) which can. It's part of a larger family: wcstol (Wide Character String TO Long, e.g. Unicode), strtoull (TO Unsigned Long Long, 64bits+), wcstoull, strtof (TO Float) and wcstof.

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

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

In your modal view controller:

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

If you are working with a storyboard:

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

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

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

How to add,set and get Header in request of HttpClient?

You can test-drive this code exactly as is using the public GitHub API (don't go over the request limit):

public class App {

    public static void main(String[] args) throws IOException {

        CloseableHttpClient client = HttpClients.custom().build();

        // (1) Use the new Builder API (from v4.3)
        HttpUriRequest request = RequestBuilder.get()
                // (2) Use the included enum
                .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                // (3) Or your own
                .setHeader("Your own very special header", "value")

        CloseableHttpResponse response = client.execute(request);

        // (4) How to read all headers with Java8
        List<Header> httpHeaders = Arrays.asList(response.getAllHeaders());;

        // close client and response

Python find elements in one list that are not in the other

If the number of occurences should be taken into account you probably need to use something like collections.Counter:

list_1=["a", "b", "c", "d", "e"]
list_2=["a", "f", "c", "m"] 
from collections import Counter
cnt1 = Counter(list_1)
cnt2 = Counter(list_2)
final = [key for key, counts in cnt2.items() if cnt1.get(key, 0) != counts]

>>> final
['f', 'm']

As promised this can also handle differing number of occurences as "difference":

list_1=["a", "b", "c", "d", "e", 'a']
cnt1 = Counter(list_1)
cnt2 = Counter(list_2)
final = [key for key, counts in cnt2.items() if cnt1.get(key, 0) != counts]

>>> final
['a', 'f', 'm']

Load jQuery with Javascript and use jQuery

There's a working JSFiddle with a small example here, that demonstrates exactly what you are looking for (unless I've misunderstood your request):

There are a few issues with that method of loading javascript dynamically. When it comes to the very basal frameworks, like jQuery, you actually probably want to load them statically, because otherwise, you would have to write a whole JavaScript loading framework...

You could use some of the existing JavaScript loaders, or write your own by watching for window.jQuery to get defined.

// Immediately-invoked function expression
(function() {
    // Load the script
    var script = document.createElement("SCRIPT");
    script.src = '';
    script.type = 'text/javascript';
    script.onload = function() {
        var $ = window.jQuery;
        // Use $ here...

Just remember that if you need to support really old browsers, like IE8, load event handlers do not execute. In that case, you would need to poll for the existance of window.jQuery using repeated window.setTimeout. There is a working JSFiddle with that method here:

There are lots of people who have already done what you need to do. Check out some of the existing JavaScript Loader frameworks, like:

Why is this printing 'None' in the output?

Because of double print function. I suggest you to use return instead of print inside the function definition.

def lyrics():
    return "The very first line"


def lyrics():
    print("The very first line")

How to get the client IP address in PHP

I like this codesnippet:

function getClientIP() {

    if (isset($_SERVER)) {

        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
            return $_SERVER["HTTP_X_FORWARDED_FOR"];

        if (isset($_SERVER["HTTP_CLIENT_IP"]))
            return $_SERVER["HTTP_CLIENT_IP"];

        return $_SERVER["REMOTE_ADDR"];

    if (getenv('HTTP_X_FORWARDED_FOR'))
        return getenv('HTTP_X_FORWARDED_FOR');

    if (getenv('HTTP_CLIENT_IP'))
        return getenv('HTTP_CLIENT_IP');

    return getenv('REMOTE_ADDR');

JavaScript Array splice vs slice

splice & delete Array item by index

index = 2

//splice & will modify the origin array
const arr1 = [1,2,3,4,5];
//slice & won't modify the origin array
const arr2 = [1,2,3,4,5]

console.log(arr1.splice(2, 1));
console.log(arr2.slice(2, 1));


let log = console.log;_x000D_
//splice & will modify the origin array_x000D_
const arr1 = [1,2,3,4,5];_x000D_
//slice & won't modify the origin array_x000D_
const arr2 = [1,2,3,4,5]_x000D_
log(arr1.splice(2, 1));_x000D_
log(arr2.slice(2, 1));_x000D_

enter image description here

Getting an odd error, SQL Server query using `WITH` clause

    CteProductLookup(ProductId, oid) 

How can I make a ComboBox non-editable in .NET?

To continue displaying data in the input after selecting, do so:

Private Sub ComboBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ComboBox1.KeyPress
    e.Handled = True
End Sub

Private void ComboBox1_KeyPress(object sender, KeyPressEventArgs e)
    e.Handled = true;

No connection could be made because the target machine actively refused it

If you have config file transforms then ensure you have the correct config selected within your publish profile. (Publish > Settings > Configuration)

websocket.send() parameter

As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.

This is some pseudocodish JavaScript:


var websocket = new WebSocket("server address");

websocket.onmessage = function(str) {
  console.log("Someone sent: ", str);

// Tell the server this is client 1 (swap for client 2 of course)
  id: "client1"

// Tell the server we want to send something to the other client
  to: "client2",
  data: "foo"


var clients = {};

server.on("data", function(client, str) {
  var obj = JSON.parse(str);

  if("id" in obj) {
    // New client, add it to the id/client object
    clients[] = client;
  } else {
    // Send data to the client requested

How can I scale an image in a CSS sprite

You could use background-size, as its supported by most browsers (but not all

background-size : 150% 150%;


You can use a combo of zoom for webkit/ie and transform:scale for Firefox(-moz-) and Opera(-o-) for cross-browser desktop & mobile

    display: inline-block;
    background: url('../img/icons/icons.png') no-repeat;
    width: 64px;
    height: 51px;
    overflow: hidden;
    -moz-transform-origin: 0 0;

    -moz-transform-origin: 0 0;

    -moz-transform-origin: 0 0;

    -moz-transform-origin: 0 0;

Pass Arraylist as argument to function

The answer is already posted but note that this will pass the ArrayList by reference. So if you make any changes to the list in the function it will be affected to the original list also.

<access-modfier> <returnType> AnalyseArray(ArrayList<Integer> list)
//analyse the list
//return value

call it like this:


or pass a copy of ArrayList:


How can I verify if an AD account is locked?

If you want to check via command line , then use command "net user username /DOMAIN"

enter image description here

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

Do you need the second batch file to run asynchronously? Typically one batch file runs another synchronously with the call command, and the second one would share the first one's window.

You can use start /b second.bat to launch a second batch file asynchronously from your first that shares your first one's window. If both batch files write to the console simultaneously, the output will be overlapped and probably indecipherable. Also, you'll want to put an exit command at the end of your second batch file, or you'll be within a second cmd shell once everything is done.

0xC0000005: Access violation reading location 0x00000000

This line looks suspicious:

invaders[i] = inv;

You're never incrementing i, so you keep assigning to invaders[0]. If this is just an error you made when reducing your code to the example, check how you calculate i in the real code; you could be exceeding the size of invaders.

If as your comment suggests, you're creating 55 invaders, then check that invaders has been initialised correctly to handle this number.

Oracle: If Table Exists

The best and most efficient way is to catch the "table not found" exception: this avoids the overhead of checking if the table exists twice; and doesn't suffer from the problem that if the DROP fails for some other reason (that might be important) the exception is still raised to the caller:

      IF SQLCODE != -942 THEN
      END IF;

ADDENDUM For reference, here are the equivalent blocks for other object types:


    IF SQLCODE != -2289 THEN
    END IF;


    IF SQLCODE != -942 THEN
    END IF;


    IF SQLCODE != -4080 THEN
    END IF;


    IF SQLCODE != -1418 THEN
    END IF;


                || ' DROP COLUMN ' || column_name;
    IF SQLCODE != -904 AND SQLCODE != -942 THEN
    END IF;

Database Link

    IF SQLCODE != -2024 THEN
    END IF;

Materialized View

    IF SQLCODE != -12003 THEN
    END IF;


    IF SQLCODE != -4043 THEN
    END IF;


            || ' DROP CONSTRAINT ' || constraint_name;
    IF SQLCODE != -2443 AND SQLCODE != -942 THEN
    END IF;

Scheduler Job

    IF SQLCODE != -27475 THEN
    END IF;

User / Schema

  /* you may or may not want to add CASCADE */
    IF SQLCODE != -1918 THEN
    END IF;


    IF SQLCODE != -4043 THEN
    END IF;


    IF SQLCODE != -4043 THEN
    END IF;


    IF SQLCODE != -4043 THEN
    END IF;


    IF SQLCODE != -959 THEN
    END IF;


    IF SQLCODE != -1434 THEN
    END IF;

How do you run a command for each line of a file?

If you want to run your command in parallel for each line you can use GNU Parallel

parallel -a <your file> <program>

Each line of your file will be passed to program as an argument. By default parallel runs as many threads as your CPUs count. But you can specify it with -j

Liquibase lock - reasons?

Edit june 2020

Don't follow this advice. It's caused trouble to many people over the years. It worked for me a long time ago and I posted it in good faith, but it's clearly not the way to do it. The DATABASECHANGELOCK table needs to have stuff in it, so it's a bad idea to just delete everything from it without dropping the table.

Leos Literak, for instance, followed these instructions and the server failed to start.

Original answer

It's possibly due to a killed liquibase process not releasing its lock on the DATABASECHANGELOGLOCK table. Then,


might help you.

Edit: @Adrian Ber's answer provides a better solution than this. Only do this if you have any problems doing his solution.

How to make a programme continue to run after log out from ssh?

Assuming that you have a program running in the foreground, press ctrl-Z, then:

[1]+  Stopped                 myprogram
$ disown -h %1
$ bg 1
[1]+ myprogram &
$ logout

If there is only one job, then you don't need to specify the job number. Just use disown -h and bg.

Explanation of the above steps:

You press ctrl-Z. The system suspends the running program, displays a job number and a "Stopped" message and returns you to a bash prompt.

You type the disown -h %1 command (here, I've used a 1, but you'd use the job number that was displayed in the Stopped message) which marks the job so it ignores the SIGHUP signal (it will not be stopped by logging out).

Next, type the bg command using the same job number; this resumes the running of the program in the background and a message is displayed confirming that.

You can now log out and it will continue running..

Link to reload current page

<a href="/home" target="_self">Reload the page</a>

Create table using Javascript

Here is an example of drawing a table using raphael.js. We can draw tables directly to the canvas of the browser using Raphael.js Raphael.js is a javascript library designed specifically for artists and graphic designers.

<!DOCTYPE html>

        <div id='panel'></div>
    <script src=""> </script>
    <script src=""></script>

paper = new Raphael(0,0,500,500);// width:500px, height:500px

var x = 100;
var y = 50;
var height = 50
var width = 100;

WriteTableRow(x,y,width*2,height,paper,"TOP Title");// draw a table header as merged cell
y= y+height;
WriteTableRow(x,y,width,height,paper,"Score,Player");// draw table header as individual cells
y= y+height;
for (i=1;i<=4;i++)
var k;
k = Math.floor(Math.random() * (10 + 1 - 5) + 5);//prepare table contents as random data
WriteTableRow(x,y,width,height,paper,i+","+ k + "");// draw a row
y= y+height;

function WriteTableRow(x,y,width,height,paper,TDdata)
{ // width:cell width, height:cell height, paper: canvas, TDdata: texts for a row. Separated each cell content with a comma.

    var TD = TDdata.split(",");
    for (j=0;j<TD.length;j++)
        var rect = paper.rect(x,y,width,height).attr({"fill":"white","stroke":"red"});// draw outline
        paper.text(x+width/2, y+height/2, TD[j]) ;// draw cell text
        x = x + width;



Please check the preview image:

Intercept and override HTTP requests from WebView

It looks like API level 11 has support for what you need. See WebViewClient.shouldInterceptRequest().

Why isn't this code to plot a histogram on a continuous value Pandas column working?


After your comments this actually makes perfect sense why you don't get a histogram of each different value. There are 1.4 million rows, and ten discrete buckets. So apparently each bucket is exactly 10% (to within what you can see in the plot).

A quick rerun of your data:

In [25]: df.hist(column='Trip_distance')

enter image description here

Prints out absolutely fine.

The df.hist function comes with an optional keyword argument bins=10 which buckets the data into discrete bins. With only 10 discrete bins and a more or less homogeneous distribution of hundreds of thousands of rows, you might not be able to see the difference in the ten different bins in your low resolution plot:

In [34]: df.hist(column='Trip_distance', bins=50)

enter image description here

Gulp command not found after install

I realize that this is an old thread, but for Future-Me, and posterity, I figured I should add my two-cents around the "running npm as sudo" discussion. Disclaimer: I do not use Windows. These steps have only been proven on non-windows machines, both virtual and physical.

You can avoid the need to use sudo by changing the permission to npm's default directory.

How to: change permissions in order to run npm without sudo

Step 1: Find out where npm's default directory is.

  • To do this, open your terminal and run:
    npm config get prefix

Step 2: Proceed, based on the output of that command:

  • Scenario One: npm's default directory is /usr/local
    For most users, your output will show that npm's default directory is /usr/local, in which case you can skip to step 4 to update the permissions for the directory.
  • Scenario Two: npm's default directory is /usr or /Users/YOURUSERNAME/node_modules or /Something/Else/FishyLooking
    If you find that npm's default directory is not /usr/local, but is instead something you can't explain or looks fishy, you should go to step 3 to change the default directory for npm, or you risk messing up your permissions on a much larger scale.

Step 3: Change npm's default directory:

  • There are a couple of ways to go about this, including creating a directory specifically for global installations and then adding that directory to your $PATH, but since /usr/local is probably already in your path, I think it's simpler to just change npm's default directory to that. Like so: npm config set prefix /usr/local
    • For more info on the other approaches I mentioned, see the npm docs here.

Step 4: Update the permissions on npm's default directory:

  • Once you've verified that npm's default directory is in a sensible location, you can update the permissions on it using the command:
    sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}

Now you should be able to run npm <whatever> without sudo. Note: You may need to restart your terminal in order for these changes to take effect.

How to split a large text file into smaller files with equal number of lines?

split the file "file.txt" into 10000 lines files:

split -l 10000 file.txt

Javascript change Div style

function abc() {
    var color = document.getElementById("test").style.color;
    if (color === "red")

Split and join C# string

Well, here is my "answer". It uses the fact that String.Split can be told hold many items it should split to (which I found lacking in the other answers):

string theString = "Some Very Large String Here";
var array = theString.Split(new [] { ' ' }, 2); // return at most 2 parts
// note: be sure to check it's not an empty array
string firstElem = array[0];
// note: be sure to check length first
string restOfArray = array[1];

This is very similar to the Substring method, just by a different means.

Not showing placeholder for input type="date" field

I'm surprised there's only one answer with an approach similar to the one I used.
I got the inspiration from @Dtipson's comment on @Mumthezir VP's answer.

I use two inputs for this, one is a fake input with type="text" on which I set the placeholder, the other one is the real field with type="date".
On the mouseenter event on their container, I hide the fake input and show the real one, and I do the opposite on the mouseleave event. Obviously, I leave the real input visibile if it has a value set on it.
I wrote the code to use pure Javascript but if you use jQuery (I do) it's very easy to "convert" it.

// "isMobile" function taken from this reply:_x000D_
function isMobile() {_x000D_
  try { document.createEvent("TouchEvent"); return true; }_x000D_
  catch(e) { return false; }_x000D_
var deviceIsMobile = isMobile();_x000D_
function mouseEnterListener(event) {_x000D_
  var realDate = this.querySelector('.real-date');_x000D_
  // if it has a value it's already visible._x000D_
  if(!realDate.value) {_x000D_
    this.querySelector('.fake-date').style.display = 'none';_x000D_ = 'block';_x000D_
function mouseLeaveListener(event) {_x000D_
  var realDate = this.querySelector('.real-date');_x000D_
  // hide it if it doesn't have focus (except_x000D_
  // on mobile devices) and has no value._x000D_
  if((deviceIsMobile || document.activeElement !== realDate) && !realDate.value) {_x000D_ = 'none';_x000D_
    this.querySelector('.fake-date').style.display = 'block';_x000D_
function fakeFieldActionListener(event) {_x000D_
  this.parentElement.dispatchEvent(new Event('mouseenter'));_x000D_
  var realDate = this.parentElement.querySelector('.real-date');_x000D_
  // to open the datepicker on mobile devices_x000D_
  // I need to focus and then click on the field._x000D_
var containers = document.getElementsByClassName('date-container');_x000D_
for(var i = 0; i < containers.length; ++i) {_x000D_
  var container = containers[i];_x000D_
  container.addEventListener('mouseenter', mouseEnterListener);_x000D_
  container.addEventListener('mouseleave', mouseLeaveListener);_x000D_
  var fakeDate = container.querySelector('.fake-date');_x000D_
  // for mobile devices, clicking (tapping)_x000D_
  // on the fake input must show the real one._x000D_
  fakeDate.addEventListener('click', fakeFieldActionListener);_x000D_
  // let's also listen to the "focus" event_x000D_
  // in case it's selected using a keyboard._x000D_
  fakeDate.addEventListener('focus', fakeFieldActionListener);_x000D_
  var realDate = container.querySelector('.real-date');_x000D_
  // trigger the "mouseleave" event on the_x000D_
  // container when the value changes._x000D_
  realDate.addEventListener('change', function() {_x000D_
    container.dispatchEvent(new Event('mouseleave'));_x000D_
  // also trigger the "mouseleave" event on_x000D_
  // the container when the input loses focus._x000D_
  realDate.addEventListener('blur', function() {_x000D_
    container.dispatchEvent(new Event('mouseleave'));_x000D_
.real-date {_x000D_
  display: none;_x000D_
/* a simple example of css to make _x000D_
them look like it's the same element */_x000D_
.real-date, _x000D_
.fake-date {_x000D_
  width: 200px;_x000D_
  height: 20px;_x000D_
  padding: 0px;_x000D_
<div class="date-container">_x000D_
  <input type="text" class="fake-date" placeholder="Insert date">_x000D_
  <input type="date" class="real-date">_x000D_

I tested this also on an Android phone and it works, when the user taps on the field the datepicker is shown. The only thing is, if the real input had no value and the user closes the datepicker without choosing a date, the input will remain visible until they tap outside of it. There's no event to listen to to know when the datepicker closes so I don't know how to solve that.

I don't have an iOS device to test it on.

python: how to check if a line is an empty line

I think is more robust to use regular expressions:

import re

for i, line in enumerate(content):
    print line if not (re.match('\r?\n', line)) else pass

This would match in Windows/unix. In addition if you are not sure about lines containing only space char you could use '\s*\r?\n' as expression

Clearing an HTML file upload field via JavaScript

I know the FormData api is not so friendly for older browsers and such, but in many cases you are anyways using it (and hopefully testing for support) so this will work fine!

function clearFile(form) {_x000D_
  // make a copy of your form_x000D_
  var formData = new FormData(form);_x000D_
  // reset the form temporarily, your copy is safe!_x000D_
  for (var pair of formData.entries()) {_x000D_
    // if it's not the file, _x000D_
    if (pair[0] != "uploadNameAttributeFromForm") {_x000D_
      // refill form value_x000D_
      form[pair[0]].value = pair[1];_x000D_
  // make new copy for AJAX submission if you into that..._x000D_
  formData = new FormData(form);_x000D_

How can I install Python's pip3 on my Mac?

You could use Homebrew.

Then just run:

brew install python3

How do I get the height and width of the Android Navigation Bar programmatically?

Simple One-line Solution

As suggested in many of above answers, for example

Simply getting navigation bar height may not be enough. We need to consider whether 1. navigation bar exists, 2. is it on the bottom, or right or left, 3. is app open in multi-window mode.

Fortunately you can easily bypass all the long coding by simply setting android:fitsSystemWindows="true" in your root layout. Android system will automatically take care of adding necessary padding to the root layout to make sure that the child views don't get into the navigation bar or statusbar regions.

There is a simple one line solution


or programatically


you may also get root view by


For more details on getting root-view refer -

In excel how do I reference the current row but a specific column?

If you dont want to hard-code the cell addresses you can use the ROW() function.


Its probably not the best way to do it though! Using Auto-Fill and static columns like @JaiGovindani suggests would be much better.

Where to place JavaScript in an HTML file?

Like others have said, it should most likely go in an external file. I prefer to include such files at the end of the <head />. This method is more human friendly than machine friendly, but that way I always know where the JS is. It is just not as readable to include script files anywhere else (imho).

I you really need to squeeze out every last ms then you probably should do what Yahoo says.

Concatenate two NumPy arrays vertically

Because both a and b have only one axis, as their shape is (3), and the axis parameter specifically refers to the axis of the elements to concatenate.

this example should clarify what concatenate is doing with axis. Take two vectors with two axis, with shape (2,3):

a = np.array([[1,5,9], [2,6,10]])
b = np.array([[3,7,11], [4,8,12]])

concatenates along the 1st axis (rows of the 1st, then rows of the 2nd):

np.concatenate((a,b), axis=0)
array([[ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11],
       [ 4,  8, 12]])

concatenates along the 2nd axis (columns of the 1st, then columns of the 2nd):

np.concatenate((a, b), axis=1)
array([[ 1,  5,  9,  3,  7, 11],
       [ 2,  6, 10,  4,  8, 12]])

to obtain the output you presented, you can use vstack

a = np.array([1,2,3])
b = np.array([4,5,6])
np.vstack((a, b))
array([[1, 2, 3],
       [4, 5, 6]])

You can still do it with concatenate, but you need to reshape them first:

np.concatenate((a.reshape(1,3), b.reshape(1,3)))
array([[1, 2, 3],
       [4, 5, 6]])

Finally, as proposed in the comments, one way to reshape them is to use newaxis:

np.concatenate((a[np.newaxis,:], b[np.newaxis,:]))

Can I obtain method parameter name using Java reflection?

So you should be able to do:

        .find { == 'aMethod' }
        .collect { "$it.type : $" }

But you'll probably get a list like so:

["int : arg0"]

I believe this will be fixed in Groovy 2.5+

So currently, the answer is:

  • If it's a Groovy class, then no, you can't get the name, but you should be able to in the future.
  • If it's a Java class compiled under Java 8, you should be able to.

See also:

For every method, then something like:

        .findAll { !it.synthetic }
        .collect { method -> 
            println method
   + " -> " + method.parameters.collect { "[$it.type : $]" }.join(';')
        .each {
            println it

Using jQuery to center a DIV on the screen

It can be done with only CSS. But they asked with jQuery or JavaScript

Here, use CSS Flex box property to align the div center.{
  align-items:center; // Vertical alignment
  justify-content:center; // Horizontal alignment

align-items:center; - used to align vertically.

justify-content:center; - used to align horizontally.

body {
  margin : 0;
  background: #ccc;
  <div id="main"></div>

What do I use for a max-heap implementation in Python?

This is a simple MaxHeap implementation based on heapq. Though it only works with numeric values.

import heapq
from typing import List

class MaxHeap:
    def __init__(self): = []

    def top(self):

    def push(self, val):
        heapq.heappush(, -val)

    def pop(self):
        return -heapq.heappop(


max_heap = MaxHeap()
print(  # 5

How to search a list of tuples in Python

You can use a list comprehension:

>>> a = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]
>>> [x[0] for x in a]
[1, 22, 53, 44]
>>> [x[0] for x in a].index(53)

Concatenating strings doesn't work as expected

Your code, as written, works. You’re probably trying to achieve something unrelated, but similar:

std::string c = "hello" + "world";

This doesn’t work because for C++ this seems like you’re trying to add two char pointers. Instead, you need to convert at least one of the char* literals to a std::string. Either you can do what you’ve already posted in the question (as I said, this code will work) or you do the following:

std::string c = std::string("hello") + "world";

How can I use async/await at the top level?

Since main() runs asynchronously it returns a promise. You have to get the result in then() method. And because then() returns promise too, you have to call process.exit() to end the program.

      (text) => { console.log('outside: ' + text) },
      (err)  => { console.log(err) }
   .then(() => { process.exit() } )

Automatically deleting related rows in Laravel (Eloquent ORM)

yeah, but as @supersan stated upper in a comment, if you delete() on a QueryBuilder, the model event will not be fired, because we are not loading the model itself, then calling delete() on that model.

The events are fired only if we use the delete function on a Model Instance.

So, this beeing said:

if user->hasMany(post)
and if post->hasMany(tags)

in order to delete the post tags when deleting the user, we would have to iterate over $user->posts and calling $post->delete()

foreach($user->posts as $post) { $post->delete(); } -> this will fire the deleting event on Post


$user->posts()->delete() -> this will not fire the deleting event on post because we do not actually load the Post Model (we only run a SQL like: DELETE * from posts where user_id = $user->id and thus, the Post model is not even loaded)

Difference between signed / unsigned char

The same way -- e.g. if you have an 8-bit char, 7 bits can be used for magnitude and 1 for sign. So an unsigned char might range from 0 to 255, whilst a signed char might range from -128 to 127 (for example).

Angular 2 Checkbox Two Way Data Binding

A workaround to achieve the same specially if you want to use checkbox with for loop is to store the state of the checkbox inside an array and change it based on the index of the *ngFor loop. This way you can change the state of the checkbox in your component.


<div *ngFor="let item of items; index as i"> <input type="checkbox" [checked]="category[i]" (change)="checkChange(i)"> {{}} </div>


items = [

  category= []

    if (this.category[i]){  
      this.category[i] = !this.category[i];
      this.category[i] = true;

The easiest way to replace white spaces with (underscores) _ in bash

This is borderline programming, but look into using tr:

$ echo "this is just a test" | tr -s ' ' | tr ' ' '_'

Should do it. The first invocation squeezes the spaces down, the second replaces with underscore. You probably need to add TABs and other whitespace characters, this is for spaces only.

Open new Terminal Tab from command line (Mac OS X)

What about this simple snippet, based on a standard script command (echo):

# set mac osx's terminal title to "My Title"
echo -n -e "\033]0;My Title\007"

How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?

I have the same issue with windows10, apache 2.2.25, php 5.2 Im trying to add GD to a working PHP.

how I turn around and change between forward and backward slash, plus trailing or not, I get some variant of ;

PHP Warning: PHP Startup: Unable to load dynamic library 'C:/php\php_gd2.dll' - Det g\xe5r inte att hitta den angivna modulen.\r\n in Unknown on line 0

(swedish translated: 'It is not possible to find the module' )

in this perticular case, the php.ini was: extension_dir = "C:/php"

the dll is put in two places C:\php and C:\php\ext

IS it possible that there is and "error" in the error log entry ? I.e. that the .dll IS found (as a file) but not of the right format, or something like that ??

Animate a custom Dialog

I have created the Fade in and Fade Out animation for Dialogbox using ChrisJD code.

  1. Inside res/style.xml

    <style name="AppTheme" parent="android:Theme.Light" />
    <style name="PauseDialog" parent="@android:style/Theme.Dialog">
        <item name="android:windowAnimationStyle">@style/PauseDialogAnimation</item>
    <style name="PauseDialogAnimation">
        <item name="android:windowEnterAnimation">@anim/fadein</item>
        <item name="android:windowExitAnimation">@anim/fadeout</item>

  2. Inside anim/fadein.xml

    <alpha xmlns:android=""
        android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="500" />
  3. Inside anim/fadeout.xml

    <alpha xmlns:android=""
        android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="500" />
  4. MainActivity

    Dialog imageDiaglog= new Dialog(MainActivity.this,;

ThreeJS: Remove object from scene

clearScene: function() {
    var objsToRemove =, 1);
    _.each(objsToRemove, function( object ) {

this uses undescore.js to iterrate over all children (except the first) in a scene (it's part of code I use to clear a scene). just make sure you render the scene at least once after deleting, because otherwise the canvas does not change! There is no need for a "special" obj flag or anything like this.

Also you don't delete the object by name, just by the object itself, so calling


instead of scene.remove(; can be enough

PS: _.each is a function of underscore.js

Replace one substring for another string in shell script

Since I can't add a comment. @ruaka To make the example more readable write it like this

full_string="I love Suzy and Mary"

How to start Apache and MySQL automatically when Windows 8 comes up

  1. Window + R
  2. Type services.msc
  3. Search for your WAMP Apache and go to property and select Auto.
  4. Restart your computer.

As a service

You can set this one by:

Going first to your installation directory (in my case it’s c:\xampplite). It could be somewhere else depending on your installation. Have also my full version in c:\x2\xampp. Once your in the installation directory, find xampp-control.exe and click/double-click to launch it.

You should first stop all running instances of your apache2 and mysqld/mysql processes to do this.

Click the checkmark next to Apache and MySQL with the header name service. It will warn you that it’s installing as a service which of course is what we like it to do. Click Yes.

Also do step 5 with MySQL. We’re almost done.

Click Start ? Run

Type services.msc (it can also be done in the control panel under administrative tools which is a way lot of click than this one). Find the Apache 2 and MySQL services.

Double click each one and set the startup type to Automatic (you will be presented with three options: Automatic, Manual, and Disabled):

  • Automatic – will start it automatically at startup
  • Manual – users will have to start it up manually i.e. by issuing a command like net start apache2
  • Disabled – will disable it.

Be warned though that any change in the services just like the registry can cause your system to stall.

Click the start button to manually start it (just for the session though). At the next restart it’ll be automated.

Do the same with MySQL.

As a startup program

Find xampp_start.exe from your installation directory.

Press Ctrl + C to copy it or right-click the file and hit copy.

Go to C:\Documents and Settings\Administrator\Start Menu\Programs\Startup and right click on it and hit Paste Shortcut.

When you restart it’ll be starting also and you’ll see something like this:

You can stop it by issuing the xampp_stop.exe command in your installation directory.

Also worth mentioning is that if you right click again on the shortcut and hit properties, try to change the run option to minimized. This way the shortcut will be on your taskbar once started.

Emulator in Android Studio doesn't start

if you are finding difficult in opening Emulator in Android Studio you can also download genymotion in your android studio.

Bootstrap 3 select input form inline

This is how I made it without extra css or jquery:

<div class="form-group">
    <div class="input-group">
        <label class="sr-only" for="extra3">Extra name 3</label>
        <input type="text" id="extra3" class="form-control" placeholder="Extra name">
        <span class="input-group-addon">
            <label class="checkbox-inline">
               Mandatory? <input type="checkbox" id="inlineCheckbox5" value="option1">
        <span class="input-group-addon">
             <label class="checkbox-inline">
               Per person? <input type="checkbox" id="inlineCheckbox6" value="option2">
        <span class="input-group-addon">
            To be paid? 
                <option value="online">Online</option>
                <option value="on spot">On Spot</option>

What is the difference between JavaScript and jQuery?

jQuery is a JavaScript library.


wiki-jQuery, github, jQuery vs. javascript?


What is JQuery?

Before JQuery, developers would create their own small frameworks (the group of code) this would allow all the developers to work around all the bugs and give them more time to work on features, so the JavaScript frameworks were born. Then came the collaboration stage, groups of developers instead of writing their own code would give it away for free and creating JavaScript code sets that everyone could use. That is what JQuery is, a library of JavaScript code. The best way to explain JQuery and its mission is well stated on the front page of the JQuery website which says:

JQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.

As you can see all JQuery is JavaScript. There is more than one type of JavaScript set of code sets like MooTools it is just that JQuery is the most popular.

JavaScript vs JQuery

Which is the best JavaScript or JQuery is a contentious discussion, really the answer is neither is best. They both have their roles I have worked on online applications where JQuery was not the right tool and what the application needed was straight JavaScript development. But for most websites JQuery is all that is needed. What a web developer needs to do is make an informed decision on what tools are best for their client. Someone first coming into web development does need some exposure to both technologies just using JQuery all the time does not teach the nuances of JavaScript and how it affects the DOM. Using JavaScript all the time slows projects down and because of the JQuery library has ironed most of the issues that JavaScript will have between each web browser it makes the deployment safe as it is sure to work across all platforms.

JavaScript is a language. jQuery is a library built with JavaScript to help JavaScript programmers who are doing common web tasks.

See here.

How to configure socket connect timeout

There should be a ReceiveTimeout property in the Socket class.

Socket.ReceiveTimeout Property

C++: Rounding up to the nearest multiple of a number


int roundUp(int numToRound, int multiple)
  return (multiple ? (((numToRound+multiple-1) / multiple) * multiple) : numToRound);

and for your ~/.bashrc:

  echo $(( ${2} ? ((${1}+${2}-1)/${2})*${2} : ${1} ))

Create a zip file and download it

but the file i am getting from server after download it gives the size of 226 bytes

This is the size of a ZIP header. Apparently there is no data in the downloaded ZIP file. So, can you verify that the files to be added into the ZIP file are, indeed, there (relative to the path of the download PHP script)?

Consider adding a check on addFile too:

foreach($file_names as $file)
    $inputFile = $file_path . $file;
    if (!file_exists($inputFile))
        trigger_error("The input file $inputFile does not exist", E_USER_ERROR);
    if (!is_readable($inputFile))
        trigger_error("The input file $inputFile exists, but has wrong permissions or ownership", E_USER_ERROR);
    if (!$zip->addFile($inputFile, $file))
        trigger_error("Could not add $inputFile to ZIP file", E_USER_ERROR);

The observed behaviour is consistent with some problem (path error, permission problems, ...) preventing the files from being added to the ZIP file. On receiving an "empty" ZIP file, the client issues an error referring to the ZIP central directory missing (the actual error being that there is no directory, and no files).

Node.js heap out of memory

if you want to change the memory globally for node (windows) go to advanced system settings -> environment variables -> new user variable

variable name = NODE_OPTIONS
variable value = --max-old-space-size=4096

How to gracefully handle the SIGKILL signal in Java

There are ways to handle your own signals in certain JVMs -- see this article about the HotSpot JVM for example.

By using the Sun internal sun.misc.Signal.handle(Signal, SignalHandler) method call you are also able to register a signal handler, but probably not for signals like INT or TERM as they are used by the JVM.

To be able to handle any signal you would have to jump out of the JVM and into Operating System territory.

What I generally do to (for instance) detect abnormal termination is to launch my JVM inside a Perl script, but have the script wait for the JVM using the waitpid system call.

I am then informed whenever the JVM exits, and why it exited, and can take the necessary action.

Git "error: The branch 'x' is not fully merged"

I had this happen to me today, as I was merging my very first feature branch back into master. As some said in a thread elsewhere on SO, the trick was switching back to master before trying to delete the branch. Once in back in master, git was happy to delete the branch without any warnings.

Import-CSV and Foreach

$IP_Array = (Get-Content test2.csv)[0].split(",")
foreach ( $IP in $IP_Array){

Get-content Filename returns an array of strings for each line.

On the first string only, I split it based on ",". Dumping it into $IP_Array.

$IP_Array = (Get-Content test2.csv)[0].split(",")
foreach ( $IP in $IP_Array){
  if ($IP -eq "") {
    Write-Host "Found $IP"

PHP PDO returning single row

Just fetch. only gets one row. So no foreach loop needed :D

$row  = $STH -> fetch();

example (ty northkildonan):

$dbh = new PDO(" --- connection string --- "); 
$stmt = $dbh->prepare("SELECT name FROM mytable WHERE id=4 LIMIT 1"); 
$row = $stmt->fetch();

How to use Java property files?

There are many ways to create and read properties files:

  1. Store the file in the same package.
  2. Recommend .properties extension however you can choose your own.
  3. Use theses classes located at java.util package => Properties, ListResourceBundle, ResourceBundle classes.
  4. To read properties, use iterator or enumerator or direct methods of Properties or java.lang.System class.

ResourceBundle class:

 ResourceBundle rb = ResourceBundle.getBundle("prop"); //

Properties class:

Properties ps = new Properties();

javascript filter array multiple conditions

with the composition of some little helpers:

const filter = {address: 'England', name: 'Mark'};

function propMatches<T>(property: string, value: any) {
  return (item: T): boolean => item[property] === value

function map<T>(mapper: (key: string, value: any, obj: T) => (item:T) => any) {
  return (obj: T) => {
    return Object.keys(obj).map((key) => {
      return mapper(key, obj[key], obj)

export function and<T>(predicates: ((item: T) => boolean)[]) {
  return (item: T) =>
        (acc: boolean, predicate: (item: T) => boolean) => {
            if (acc === undefined) {
                return !!predicate(item);
            return !!predicate(item) && acc;
        undefined // initial accumulator value

Prevent Default on Form Submit jQuery

        return condition;

When increasing the size of VARCHAR column on a large table could there be any problems?

Changing to Varchar(1200) from Varchar(200) should cause you no issue as it is only a metadata change and as SQL server 2008 truncates excesive blank spaces you should see no performance differences either so in short there should be no issues with making the change.

How do I alias commands in git?

Follwing are the 4 git shortcuts or aliases youc an use to save time.

Open the commandline and type these below 4 commands and use the shortcuts after.

git config --global checkout  
git config --global commit    
git config --global status    
git config --global branch  

Now test them!

$ git co              # use git co instead of git checkout
$ git ci              # use git ci instead of git commit
$ git st              # use git st instead of git status
$ git br              # use git br instead of git branch

Unexpected token < in first line of HTML

Check your encoding, i got something similar once because of the BOM.

Make sure the core.js file is encoded in utf-8 without BOM

Go to next item in ForEach-Object

You just have to replace the break with a return statement.

Think of the code inside the Foreach-Object as an anonymous function. If you have loops inside the function, just use the control keywords applying to the construction (continue, break, ...).

How can I find the location of origin/master in git, and how do I change it?

I am struggling with this problem and none of the previous answers tackle the question as I see it. I have stripped the problem back down to its basics to see if I can make my problem clear.

I create a new repository (rep1), put one file in it and commit it.

mkdir rep1
cd rep1
git init
echo "Line1" > README
git add README
git commit -m "Commit 1"

I create a clone of rep1 and call it rep2. I look inside rep2 and see the file is correct.

cd ~
git clone ~/rep1 rep2
cat ~/rep2/README

In rep1 I make a single change to the file and commit it. Then in rep1 I create a remote to point to rep2 and push the changes.

cd ~/rep1
<change file and commit>
git remote add rep2 ~/rep2
git push rep2 master

Now when I go into rep2 and do a 'git status' I get told I am ahead of origin.

# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#   modified:   README

README in rep2 is as it was originally, before the second commit. The only modifications I have done are to rep1 and all I wanted to do was push them out to rep2. What is it I am not grasping?

Redirect to new Page in AngularJS using $location

The line

$location.absUrl() == '';

is wrong. First == makes a comparison, and what you are probably trying to do is an assignment, which is with simple = and not double ==.

And because absUrl() getter only. You can use url(), which can be used as a setter or as a getter if you want.

reference :$location

How to restart a node.js server

Using "kill -9 [PID]" or "killall -9 node" worked for me where "kill -2 [PID]" did not work.

How do ports work with IPv6?

They work almost the same as today. However, be sure you include [] around your IP.

For example : http://[1fff:0:a88:85a3::ac1f]:8001/index.html

Wikipedia has a pretty good article about IPv6:

How to select all rows which have same value in some column

select *
from Table1 as t1
    exists (
        select *
        from Table1 as t2 
        where t2.Phone = t1.Phone and <>

sql fiddle demo

How to replace part of string by position?

If you care about performance, then the thing you want to avoid here are allocations. And if you're on .Net Core 2.1+ (or the, as yet unreleased, .Net Standard 2.1), then you can, by using the string.Create method:

public static string ReplaceAt(this string str, int index, int length, string replace)
    return string.Create(str.Length - length + replace.Length, (str, index, length, replace),
        (span, state) =>
            state.str.AsSpan().Slice(0, state.index).CopyTo(span);
            state.str.AsSpan().Slice(state.index + state.length).CopyTo(span.Slice(state.index + state.replace.Length));

This approach is harder to understand than the alternatives, but it's the only one that will allocate only one object per call: the newly created string.

Angular 2 - Checking for server errors from subscribe

You can achieve with following way

        result => {
        error => {
            this.errors = error

if (!this.errors) {
    //route to new page

Update a submodule to the latest commit

Single line version

git submodule foreach "(git checkout master; git pull; cd ..; git add '$path'; git commit -m 'Submodule Sync')"

How to check if IEnumerable is null or empty?

I used simple if to check for it

check out my solution

foreach (Pet pet in v.Pets)
    if (pet == null)
        Console.WriteLine(" No pet");// enumerator is empty
    Console.WriteLine("  {0}", pet.Name);

How to use the 'replace' feature for custom AngularJS directives?

When you have replace: true you get the following piece of DOM:

<div ng-controller="Ctrl" class="ng-scope">
    <div class="ng-binding">hello</div>

whereas, with replace: false you get this:

<div ng-controller="Ctrl" class="ng-scope">
        <div class="ng-binding">hello</div>

So the replace property in directives refer to whether the element to which the directive is being applied (<my-dir> in that case) should remain (replace: false) and the directive's template should be appended as its child,


the element to which the directive is being applied should be replaced (replace: true) by the directive's template.

In both cases the element's (to which the directive is being applied) children will be lost. If you wanted to perserve the element's original content/children you would have to translude it. The following directive would do it:

.directive('myDir', function() {
    return {
        restrict: 'E',
        replace: false,
        transclude: true,
        template: '<div>{{title}}<div ng-transclude></div></div>'

In that case if in the directive's template you have an element (or elements) with attribute ng-transclude, its content will be replaced by the element's (to which the directive is being applied) original content.

See example of translusion

See this to read more about translusion.

C++ Get name of type in template

typeid(uint8_t).name() is nice, but it returns "unsigned char" while you may expect "uint8_t".

This piece of code will return you the appropriate type

#define DECLARE_SET_FORMAT_FOR(type) \
    if ( typeid(type) == typeid(T) ) \
        formatStr = #type;

template<typename T>
static std::string GetFormatName()
    std::string formatStr;

    DECLARE_SET_FORMAT_FOR( uint8_t ) 

    DECLARE_SET_FORMAT_FOR( uint16_t )

    DECLARE_SET_FORMAT_FOR( uint32_t )


    // .. to be exptended with other standard types you want to be displayed smartly

    if ( formatStr.empty() )
        assert( false );
        formatStr = typeid(T).name();

    return formatStr;

What do <o:p> elements do anyway?

Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.

The relevant paragraph:

Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.

This makes lots of sense.

For your specific question.. the o in the <o:p> means "Office namespace" so anything following the o: in a tag means "I'm part of Office namespace" - in case of <o:p> it just means paragraph, the equivalent of the ordinary <p> tag.

I assume that every HTML tag has its Office "equivalent" and they have more.

How to find tag with particular text with Beautiful Soup?

You could solve this with some simple gazpacho parsing:

from gazpacho import Soup

soup = Soup(html)
tds = soup.find("td", {"class": "pos"})

Which will output:

text I am looking for

Using GitLab token to clone without authentication

Inside a GitLab CI pipeline the CI_JOB_TOKEN environment variable works for me:

git clone https://gitlab-ci-token:${CI_JOB_TOKEN}

Source: Gitlab Docs

BTW, setting this variable in .gitlab-ci.yml helps to debug errors.

    CI_DEBUG_TRACE: "true"

Fastest Way to Find Distance Between Two Lat/Long Points

set @latitude=53.754842;
set @longitude=-2.708077;
set @radius=20;

set @lng_min = @longitude - @radius/abs(cos(radians(@latitude))*69);
set @lng_max = @longitude + @radius/abs(cos(radians(@latitude))*69);
set @lat_min = @latitude - (@radius/69);
set @lat_max = @latitude + (@radius/69);

SELECT * FROM postcode
WHERE (longitude BETWEEN @lng_min AND @lng_max)
AND (latitude BETWEEN @lat_min and @lat_max);


Return first N key:value pairs from dict

This depends on what is 'most efficient' in your case.

If you just want a semi-random sample of a huge dictionary foo, use foo.iteritems() and take as many values from it as you need, it's a lazy operation that avoids creation of an explicit list of keys or items.

If you need to sort keys first, there's no way around using something like keys = foo.keys(); keys.sort() or sorted(foo.iterkeys()), you'll have to build an explicit list of keys. Then slice or iterate through first N keys.

BTW why do you care about the 'efficient' way? Did you profile your program? If you did not, use the obvious and easy to understand way first. Chances are it will do pretty well without becoming a bottleneck.

Call removeView() on the child's parent first

In onCreate with activity or in onCreateView with fragment.

 if (view != null) {
    ViewGroup parent = (ViewGroup) view.getParent();
    if (parent != null) {
try {
    view = inflater.inflate(R.layout.fragment_main, container, false);
} catch (InflateException e) {


Where does PHP store the error log? (php5, apache, fastcgi, cpanel)

It appears that by default php does not log errors anywhere, the error_log key in php.ini is commented out in all the install's I've seen.

Generally I:

  1. look for php.ini files. locate php.ini.
  2. Search these files for the error_reporting value;

    Which should be set to whatever amalgamation of php log levels are enough for you.,


  3. Check the error_log value to make sure it points to an actual place and is not commented out.

    The default value doesn't give a full path, only a file name, I don't know where this path resolves to normally. Probably /var/log/.

http://localhost/ not working on Windows 7. What's the problem?

you have to install the service, go to wamp->Apache->Service->Install service, then a command prompt window will pop up, then press enter, and after a few seconds go to the same route Services-> and click Start/Resume service, and you ready

dpi value of default "large", "medium" and "small" text views android

See in the android sdk directory.

In \platforms\android-X\data\res\values\themes.xml:

    <item name="textAppearanceLarge">@android:style/TextAppearance.Large</item>
    <item name="textAppearanceMedium">@android:style/TextAppearance.Medium</item>
    <item name="textAppearanceSmall">@android:style/TextAppearance.Small</item>

In \platforms\android-X\data\res\values\styles.xml:

<style name="TextAppearance.Large">
    <item name="android:textSize">22sp</item>

<style name="TextAppearance.Medium">
    <item name="android:textSize">18sp</item>

<style name="TextAppearance.Small">
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">?textColorSecondary</item>

TextAppearance.Large means style is inheriting from TextAppearance style, you have to trace it also if you want to see full definition of a style.


CSS opacity only to background color, not the text on it?


background:url("location of image"); // Use an image with opacity

This method will work in all browsers.

What causes HttpHostConnectException?

In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to [] failed: Connection refused" End point and IP obviously changed to protect the network.

What does it mean: The serializable class does not declare a static final serialVersionUID field?

Any class that can be serialized (i.e. implements Serializable) should declare that UID and it must be changed whenever anything changes that affects the serialization (additional fields, removed fields, change of field order, ...). The field's value is checked during deserialization and if the value of the serialized object does not equal the value of the class in the current VM, an exception is thrown.

Note that this value is special in that it is serialized with the object even though it is static, for the reasons described above.

NodeJS w/Express Error: Cannot GET /

Where is your get method for "/"?

Also you cant serve static html directly in Express.First you need to configure it.

  app.set('port', process.env.PORT || 3000);  
  app.set("view options", {layout: false});  //This one does the trick for rendering static html
  app.engine('html', require('ejs').renderFile); 


Now add your get method.

app.get('/', function(req, res) {

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

How to time Java program execution speed

Using AOP/AspectJ and @Loggable annotation from jcabi-aspects you can do it easy and compact:

public String getSomeResult() {
  // return some value

Every call to this method will be sent to SLF4J logging facility with DEBUG logging level. And every log message will include execution time.