Programs & Examples On #Runnable

The Runnable interface defines a single method, run, meant to contain the code executed in the thread.

Runnable with a parameter?

Since Java 8, the best answer is to use Consumer<T>:

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

It's one of the functional interfaces, which means you can call it as a lambda expression:

void doSomething(Consumer<String> something) {
    something.accept("hello!");
}

...

doSomething( (something) -> System.out.println(something) )

...

Naming threads and thread-pools of ExecutorService

I use to do same like below (requires guava library) :

ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("SO-POOL-%d").build();
ExecutorService executorService = Executors.newFixedThreadPool(5,namedThreadFactory);

The difference between the Runnable and Callable interfaces in Java

See explanation here.

The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.

In a simple to understand explanation, what is Runnable in Java?

A Runnable is basically a type of class (Runnable is an Interface) that can be put into a thread, describing what the thread is supposed to do.

The Runnable Interface requires of the class to implement the method run() like so:

public class MyRunnableTask implements Runnable {
     public void run() {
         // do stuff here
     }
}

And then use it like this:

Thread t = new Thread(new MyRunnableTask());
t.start();

If you did not have the Runnable interface, the Thread class, which is responsible to execute your stuff in the other thread, would not have the promise to find a run() method in your class, so you could get errors. That is why you need to implement the interface.

Advanced: Anonymous Type

Note that you do not need to define a class as usual, you can do all of that inline:

Thread t = new Thread(new Runnable() {
    public void run() {
        // stuff here
    }
});
t.start();

This is similar to the above, only you don't create another named class.

"implements Runnable" vs "extends Thread" in Java

One reason you'd want to implement an interface rather than extend a base class is that you are already extending some other class. You can only extend one class, but you can implement any number of interfaces.

If you extend Thread, you're basically preventing your logic to be executed by any other thread than 'this'. If you only want some thread to execute your logic, it's better to just implement Runnable.

new Runnable() but no new thread?

If you want to create a new Thread...you can do something like this...

Thread t = new Thread(new Runnable() { public void run() { 
  // your code goes here... 
}});

What's the difference between Thread start() and Runnable run()

The difference is that when program calls start() method, a new thread is created and code inside run() is executed in the new thread: while if you call run() method directly, no new thread will be created and code inside run() will execute in the current thread directly.

Another difference between start() and run() in Java thread is that you cannot call start() twice. Once started, second start() call will throw IllegalStateException in Java while you can call run() method several times since it's just an ordinary method.

tkinter: how to use after method

I believe, the 500ms run in the background, while the rest of the code continues to execute and empties the list.

Then after 500ms nothing happens, as no function-call is implemented in the after-callup (same as frame.after(500, function=None))

Why can't I center with margin: 0 auto?

I don't know why the first answer is the best one, I tried it and not working in fact, as @kalys.osmonov said, you can give text-align:center to header, but you have to make ul as inline-block rather than inline, and also you have to notice that text-align can be inherited which is not good to some degree, so the better way (not working below IE 9) is using margin and transform. Just remove float right and margin;0 auto from ul, like below:

#header ul {
   /* float: right; */
   /* margin: 0 auto; */
   display: inline-block;
   margin-left: 50%; /* From parent width */
   transform: translateX(-50%); /* use self width which can be unknown */
  -ms-transform: translateX(-50%); /* For IE9 */
}

This way can fix the problem that making dynamic width of ul center if you don't care IE8 etc.

Choose File Dialog

Thanx schwiz for idea! Here is modified solution:

public class FileDialog {
    private static final String PARENT_DIR = "..";
    private final String TAG = getClass().getName();
    private String[] fileList;
    private File currentPath;
    public interface FileSelectedListener {
        void fileSelected(File file);
    }
    public interface DirectorySelectedListener {
        void directorySelected(File directory);
    }
    private ListenerList<FileSelectedListener> fileListenerList = new ListenerList<FileDialog.FileSelectedListener>();
    private ListenerList<DirectorySelectedListener> dirListenerList = new ListenerList<FileDialog.DirectorySelectedListener>();
    private final Activity activity;
    private boolean selectDirectoryOption;
    private String fileEndsWith;    

    /**
    * @param activity 
    * @param initialPath
    */
    public FileDialog(Activity activity, File initialPath) {
        this(activity, initialPath, null);
    }

    public FileDialog(Activity activity, File initialPath, String fileEndsWith) {
        this.activity = activity;
        setFileEndsWith(fileEndsWith);
        if (!initialPath.exists()) initialPath = Environment.getExternalStorageDirectory();
            loadFileList(initialPath);
    }

    /**
    * @return file dialog
    */
    public Dialog createFileDialog() {
        Dialog dialog = null;
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);

        builder.setTitle(currentPath.getPath());
        if (selectDirectoryOption) {
            builder.setPositiveButton("Select directory", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Log.d(TAG, currentPath.getPath());
                    fireDirectorySelectedEvent(currentPath);
                }
            });
        }

        builder.setItems(fileList, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String fileChosen = fileList[which];
                File chosenFile = getChosenFile(fileChosen);
                if (chosenFile.isDirectory()) {
                    loadFileList(chosenFile);
                    dialog.cancel();
                    dialog.dismiss();
                    showDialog();
                } else fireFileSelectedEvent(chosenFile);
            }
        });

        dialog = builder.show();
        return dialog;
    }


    public void addFileListener(FileSelectedListener listener) {
        fileListenerList.add(listener);
    }

    public void removeFileListener(FileSelectedListener listener) {
        fileListenerList.remove(listener);
    }

    public void setSelectDirectoryOption(boolean selectDirectoryOption) {
        this.selectDirectoryOption = selectDirectoryOption;
    }

    public void addDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.add(listener);
    }

    public void removeDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.remove(listener);
    }

    /**
    * Show file dialog
    */
    public void showDialog() {
        createFileDialog().show();
    }

    private void fireFileSelectedEvent(final File file) {
        fileListenerList.fireEvent(new FireHandler<FileDialog.FileSelectedListener>() {
            public void fireEvent(FileSelectedListener listener) {
                listener.fileSelected(file);
            }
        });
    }

    private void fireDirectorySelectedEvent(final File directory) {
        dirListenerList.fireEvent(new FireHandler<FileDialog.DirectorySelectedListener>() {
            public void fireEvent(DirectorySelectedListener listener) {
                listener.directorySelected(directory);
            }
        });
    }

    private void loadFileList(File path) {
        this.currentPath = path;
        List<String> r = new ArrayList<String>();
        if (path.exists()) {
            if (path.getParentFile() != null) r.add(PARENT_DIR);
            FilenameFilter filter = new FilenameFilter() {
                public boolean accept(File dir, String filename) {
                    File sel = new File(dir, filename);
                    if (!sel.canRead()) return false;
                    if (selectDirectoryOption) return sel.isDirectory();
                    else {
                        boolean endsWith = fileEndsWith != null ? filename.toLowerCase().endsWith(fileEndsWith) : true;
                        return endsWith || sel.isDirectory();
                    }
                }
            };
            String[] fileList1 = path.list(filter);
            for (String file : fileList1) {
                r.add(file);
            }
        }
        fileList = (String[]) r.toArray(new String[]{});
    }

    private File getChosenFile(String fileChosen) {
        if (fileChosen.equals(PARENT_DIR)) return currentPath.getParentFile();
        else return new File(currentPath, fileChosen);
    }

    private void setFileEndsWith(String fileEndsWith) {
        this.fileEndsWith = fileEndsWith != null ? fileEndsWith.toLowerCase() : fileEndsWith;
    }
}

class ListenerList<L> {
    private List<L> listenerList = new ArrayList<L>();

    public interface FireHandler<L> {
        void fireEvent(L listener);
    }

    public void add(L listener) {
        listenerList.add(listener);
    }

    public void fireEvent(FireHandler<L> fireHandler) {
        List<L> copy = new ArrayList<L>(listenerList);
        for (L l : copy) {
            fireHandler.fireEvent(l);
        }
    }

    public void remove(L listener) {
        listenerList.remove(listener);
    }

    public List<L> getListenerList() {
        return listenerList;
    }
}

Use it on activity onCreate (directory selection option is commented):

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    File mPath = new File(Environment.getExternalStorageDirectory() + "//DIR//");
    fileDialog = new FileDialog(this, mPath, ".txt");
    fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
        public void fileSelected(File file) {
            Log.d(getClass().getName(), "selected file " + file.toString());
        }
    });
    //fileDialog.addDirectoryListener(new FileDialog.DirectorySelectedListener() {
    //  public void directorySelected(File directory) {
    //      Log.d(getClass().getName(), "selected dir " + directory.toString());
    //  }
    //});
    //fileDialog.setSelectDirectoryOption(false);
    fileDialog.showDialog();
}

SASS and @font-face

In case anyone was wondering - it was probably my css...

@font-face
  font-family: "bingo"
  src: url('bingo.eot')
  src: local('bingo')
  src: url('bingo.svg#bingo') format('svg')
  src: url('bingo.otf') format('opentype')

will render as

@font-face {
  font-family: "bingo";
  src: url('bingo.eot');
  src: local('bingo');
  src: url('bingo.svg#bingo') format('svg');
  src: url('bingo.otf') format('opentype'); }

which seems to be close enough... just need to check the SVG rendering

Npm install cannot find module 'semver'

sudo rm -rf /usr/local/bin/npm /usr/local/share/man/man1/node* ~/.npm
sudo rm -rf /usr/local/lib/node*
sudo rm -rf /usr/local/bin/node*
sudo rm -rf /usr/local/include/node*

sudo apt-get purge nodejs npm
sudo apt autoremove

Then install node and npm

Create a Bitmap/Drawable from file path

you can't access your drawables via a path, so if you want a human readable interface with your drawables that you can build programatically.

declare a HashMap somewhere in your class:

private static HashMap<String, Integer> images = null;

//Then initialize it in your constructor:

public myClass() {
  if (images == null) {
    images = new HashMap<String, Integer>();
    images.put("Human1Arm", R.drawable.human_one_arm);
    // for all your images - don't worry, this is really fast and will only happen once
  }
}

Now for access -

String drawable = "wrench";
// fill in this value however you want, but in the end you want Human1Arm etc
// access is fast and easy:
Bitmap wrench = BitmapFactory.decodeResource(getResources(), images.get(drawable));
canvas.drawColor(Color .BLACK);
Log.d("OLOLOLO",Integer.toString(wrench.getHeight()));
canvas.drawBitmap(wrench, left, top, null);

How to unzip a list of tuples into individual lists?

Use zip(*list):

>>> l = [(1,2), (3,4), (8,9)]
>>> list(zip(*l))
[(1, 3, 8), (2, 4, 9)]

The zip() function pairs up the elements from all inputs, starting with the first values, then the second, etc. By using *l you apply all tuples in l as separate arguments to the zip() function, so zip() pairs up 1 with 3 with 8 first, then 2 with 4 and 9. Those happen to correspond nicely with the columns, or the transposition of l.

zip() produces tuples; if you must have mutable list objects, just map() the tuples to lists or use a list comprehension to produce a list of lists:

map(list, zip(*l))          # keep it a generator
[list(t) for t in zip(*l)]  # consume the zip generator into a list of lists

How do I change the language of moment.js?

Change the moment js language as per Version

Version: 2.8+

moment.locale('hi');

Version: 2.5.1

moment.lang('hi');

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

I encountered the same problem with:

Spring Boot version = 1.5.10
Spring Security version = 4.2.4


The problem occurred on the endpoints, where the ModelAndView viewName was defined with a preceding forward slash. Example:

ModelAndView mav = new ModelAndView("/your-view-here");

If I removed the slash it worked fine. Example:

ModelAndView mav = new ModelAndView("your-view-here");

I also did some tests with RedirectView and it seemed to work with a preceding forward slash.

Using jQuery UI sortable with HTML tables

You can call sortable on a <tbody> instead of on the individual rows.

<table>
    <tbody>
        <tr> 
            <td>1</td>
            <td>2</td>
        </tr>
        <tr>
            <td>3</td>
            <td>4</td> 
        </tr>
        <tr>
            <td>5</td>
            <td>6</td>
        </tr>  
    </tbody>    
</table>?

<script>
    $('tbody').sortable();
</script> 

_x000D_
_x000D_
$(function() {_x000D_
  $( "tbody" ).sortable();_x000D_
});
_x000D_
 _x000D_
table {_x000D_
    border-spacing: collapse;_x000D_
    border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
    width: 50px;_x000D_
    height: 25px;_x000D_
    border: 1px solid black;_x000D_
}
_x000D_
 _x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td>1</td>_x000D_
            <td>2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>3</td>_x000D_
            <td>4</td>_x000D_
        </tr>_x000D_
        <tr> _x000D_
            <td>5</td>_x000D_
            <td>6</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>7</td>_x000D_
            <td>8</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>9</td> _x000D_
            <td>10</td>_x000D_
        </tr>  _x000D_
    </tbody>    _x000D_
</table>
_x000D_
_x000D_
_x000D_

How can I format a nullable DateTime with ToString()?

You can use dt2.Value.ToString("format"), but of course that requires that dt2 != null, and that negates th use of a nullable type in the first place.

There are several solutions here, but the big question is: How do you want to format a null date?

How do I check if an array includes a value in JavaScript?

If you're working with ES6 You can use a set:

function arrayHas( array, element ) {
    const s = new Set(array);
    return s.has(element)
}

This should be more performant than just about any other method

How to add form validation pattern in Angular 2?

Since version 2.0.0-beta.8 (2016-03-02), Angular now includes a Validators.pattern regex validator.

See the CHANGELOG

Java output formatting for Strings

For decimal values you can use DecimalFormat

import java.text.*;

public class DecimalFormatDemo {

   static public void customFormat(String pattern, double value ) {
      DecimalFormat myFormatter = new DecimalFormat(pattern);
      String output = myFormatter.format(value);
      System.out.println(value + "  " + pattern + "  " + output);
   }

   static public void main(String[] args) {

      customFormat("###,###.###", 123456.789);
      customFormat("###.##", 123456.789);
      customFormat("000000.000", 123.78);
      customFormat("$###,###.###", 12345.67);  
   }
}

and output will be:

123456.789  ###,###.###   123,456.789
123456.789  ###.##        123456.79
123.78      000000.000    000123.780
12345.67    $###,###.###  $12,345.67

For more details look here:

http://docs.oracle.com/javase/tutorial/java/data/numberformat.html

How to toggle boolean state of react component?

Try:

<label><input type=checkbox" value="check" onChange = {(e) => this.setState({check: !this.state.check.value})}/> Checkbox </label>

Using check: !check.value means it is looking for the check object, which you haven't declared.

You need to specify that you want the opposite value of this.state.check.

Best solution to protect PHP code without encryption

You need to consider your objectives:

1) Are you trying to prevent people from reading/modifying your code? If yes, you'll need an obfuscation/encryption tool. I've used Zend Guard with good success.

2) Are you trying to prevent unauthorized redistribution of your code?? A EULA/proprietary license will give you the legal power to prevent that, but won't actually stop it. An key/activation scheme will allow you to actively monitor usage, but can be removed unless you also encrypt your code. Zend Guard also has capabilities to lock a particular script to a particular customer machine and/or create time limited versions of the code if that's what you want to do.

I'm not familiar with vBulletin and the like, but they'd either need to encrypt/obfuscate or trust their users to do the right thing. In the latter case they have the protection of having a EULA which prohibits the behaviors they find undesirable, and the legal system to back up breaches of the EULA.

If you're not prepared/able to take legal action to protect your software and you don't want to encrypt/obfuscate, your options are a) Release it with a EULA so you're have a legal option if you ever need it and hope for the best, or b) consider whether an open source license might be more appropriate and just allow redistribution.

Find where python is installed (if it isn't default dir)

On windows search python,then right click and click on "Open file location".That's how I did

How do I get the file name from a String containing the Absolute file path?

A method without any dependency and takes care of .. , . and duplicate separators.

public static String getFileName(String filePath) {
    if( filePath==null || filePath.length()==0 )
        return "";
    filePath = filePath.replaceAll("[/\\\\]+", "/");
    int len = filePath.length(),
        upCount = 0;
    while( len>0 ) {
        //remove trailing separator
        if( filePath.charAt(len-1)=='/' ) {
            len--;
            if( len==0 )
                return "";
        }
        int lastInd = filePath.lastIndexOf('/', len-1);
        String fileName = filePath.substring(lastInd+1, len);
        if( fileName.equals(".") ) {
            len--;
        }
        else if( fileName.equals("..") ) {
            len -= 2;
            upCount++;
        }
        else {
            if( upCount==0 )
                return fileName;
            upCount--;
            len -= fileName.length();
        }
    }
    return "";
}

Test case:

@Test
public void testGetFileName() {
    assertEquals("", getFileName("/"));
    assertEquals("", getFileName("////"));
    assertEquals("", getFileName("//C//.//../"));
    assertEquals("", getFileName("C//.//../"));
    assertEquals("C", getFileName("C"));
    assertEquals("C", getFileName("/C"));
    assertEquals("C", getFileName("/C/"));
    assertEquals("C", getFileName("//C//"));
    assertEquals("C", getFileName("/A/B/C/"));
    assertEquals("C", getFileName("/A/B/C"));
    assertEquals("C", getFileName("/C/./B/../"));
    assertEquals("C", getFileName("//C//./B//..///"));
    assertEquals("user", getFileName("/user/java/.."));
    assertEquals("C:", getFileName("C:"));
    assertEquals("C:", getFileName("/C:"));
    assertEquals("java", getFileName("C:\\Program Files (x86)\\java\\bin\\.."));
    assertEquals("C.ext", getFileName("/A/B/C.ext"));
    assertEquals("C.ext", getFileName("C.ext"));
}

Maybe getFileName is a bit confusing, because it returns directory names also. It returns the name of file or last directory in a path.

What is the string concatenation operator in Oracle?

There's also concat, but it doesn't get used much

select concat('a','b') from dual;

SQL Delete Records within a specific Range

If you write it as the following in SQL server then there would be no danger of wiping the database table unless all of the values in that table happen to actually be between those values:

DELETE FROM [dbo].[TableName] WHERE [TableName].[IdField] BETWEEN 79 AND 296 

Check image width and height before upload with Javascript

function uploadfile(ctrl) {
    var validate = validateimg(ctrl);

    if (validate) {
        if (window.FormData !== undefined) {
            ShowLoading();
            var fileUpload = $(ctrl).get(0);
            var files = fileUpload.files;


            var fileData = new FormData();


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


            fileData.append('username', 'Wishes');

            $.ajax({
                url: 'UploadWishesFiles',
                type: "POST",
                contentType: false,
                processData: false,
                data: fileData,
                success: function(result) {
                    var id = $(ctrl).attr('id');
                    $('#' + id.replace('txt', 'hdn')).val(result);

                    $('#imgPictureEn').attr('src', '../Data/Wishes/' + result).show();

                    HideLoading();
                },
                error: function(err) {
                    alert(err.statusText);
                    HideLoading();
                }
            });
        } else {
            alert("FormData is not supported.");
        }

    }

How to make ConstraintLayout work with percentage values?

For someone that might find useful, you can use layout_constraintDimensionRatio im any child view inside a ConstraintLayout and we can define the Height or Width a ratio of the other dimension( at least one must be 0dp either width or heigh) example

 <ImageView
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:src="@drawable/top_image"
        app:layout_constraintDimensionRatio="16:9"        
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

in this case the aspect ratio it's 16:9 app:layout_constraintDimensionRatio="16:9" you can find more info HERE

character count using jquery

For length including white-space:

$("#id").val().length

For length without white-space:

$("#id").val().replace(/ /g,'').length

For removing only beginning and trailing white-space:

$.trim($("#test").val()).length

For example, the string " t e s t " would evaluate as:

//" t e s t "
$("#id").val(); 

//Example 1
$("#id").val().length; //Returns 9
//Example 2
$("#id").val().replace(/ /g,'').length; //Returns 4
//Example 3
$.trim($("#test").val()).length; //Returns 7

Here is a demo using all of them.

How can I parse a string with a comma thousand separator to a number?

Yes remove the commas:

parseFloat(yournumber.replace(/,/g, ''));

Counting repeated elements in an integer array

public class DuplicationNoInArray {

    /**
     * @param args
     *            the command line arguments
     */
    public static void main(String[] args) throws Exception {
        int[] arr = { 1, 2, 3, 4, 5, 1, 2, 8 };
        int[] result = new int[10];
        int counter = 0, count = 0;
        for (int i = 0; i < arr.length; i++) {
            boolean isDistinct = false;
            for (int j = 0; j < i; j++) {
                if (arr[i] == arr[j]) {
                    isDistinct = true;
                    break;
                }
            }
            if (!isDistinct) {
                result[counter++] = arr[i];
            }
        }
        for (int i = 0; i < counter; i++) {
            count = 0;
            for (int j = 0; j < arr.length; j++) {
                if (result[i] == arr[j]) {
                    count++;
                }

            }
            System.out.println(result[i] + " = " + count);

        }
    }
}

.htaccess not working on localhost with XAMPP

Without seeing your system it's hard to tell what's wrong but try the following (comment answer if these didn't work WITH log error messages)

[STOP your Apache server instance. Ensure it's not running!]

1) move apache server/install to a folder that has no long file names and spaces

2) check httpd.conf in install\conf folder and look for AccessFileName. If it's .htaccess change it to a file name windows accepts (e.g. conf.htaccess)

3) double-check that your htaccess file gets read: add some uninterpretable garbage to it and start server: you should get an Error 500. If you don't, file is not getting read, re-visit httpd.conf file (if that looks OK, check if this is the only file which defines htaccess and it's location and it does at one place -within the file- only; also check if both httpd.conf and htaccess files are accessible: not encrypted, file access rights are not limited, drive/path available -and no long folder path and file names-)
STOP Apache again, then go on:
4) If you have IIS too on your system, stop it (uninstall it too if you can) from services.msc

5) Add the following to the top of your valid htaccess file:
RewriteEngine On
RewriteLog "/path/logs/rewrite.log" #make sure path is there!
RewriteLogLevel 9

6) Empty your [apache]\logs folder (if you use another folder, then that one :)

7) Check the following entries are set and correct:
Action application/x-httpd-php "c:/your-php5-path/php-cgi.exe"
LoadModule php5_module "c:/your-php5-path/php5apache2.dll"
LoadModule rewrite_module modules/mod_rewrite.so
Avoid long path names and spaces in folder names for phpX install too!

8) START apache server

You can do all the steps above or go one-by-one, your call. But at the end of the day make sure you tried everything above!
If system still blows up and you can't fix it, copy&paste error message(s) from log folder for further assistance

Unable to login to SQL Server + SQL Server Authentication + Error: 18456

You need to enable SQL Server Authentication:

  1. In the Object Explorer, right click on the server and click on "Properties"

DBMS Properties dialog

  1. In the "Server Properties" window click on "Security" in the list of pages on the left. Under "Server Authentication" choose the "SQL Server and Windows Authentication mode" radio option.

SQL Server Authentication dialog

  1. Restart the SQLEXPRESS service.

react-router go back a page how do you configure history?

This is a working BackButton component (React 0.14):

var React = require('react');
var Router = require('react-router');

var History = Router.History;

var BackButton = React.createClass({
  mixins: [ History ],
  render: function() {
    return (
      <button className="back" onClick={this.history.goBack}>{this.props.children}</button>
    );
  }
});

module.exports = BackButton;

You can off course do something like this if there is no history:

<button className="back" onClick={goBack}>{this.props.children}</button>

function goBack(e) {
  if (/* no history */) {
    e.preventDefault();
  } else {
    this.history.goBack();
  }
}

How to import Swagger APIs into Postman?

I work on PHP and have used Swagger 2.0 to document the APIs. The Swagger Document is created on the fly (at least that is what I use in PHP). The document is generated in the JSON format.

Sample document

{
    "swagger": "2.0",
    "info": {
    "title": "Company Admin Panel",
        "description": "Converting the Magento code into core PHP and RESTful APIs for increasing the performance of the website.",
        "contact": {
        "email": "[email protected]"
        },
        "version": "1.0.0"
    },
    "host": "localhost/cv_admin/api",
    "schemes": [
    "http"
],
    "paths": {
    "/getCustomerByEmail.php": {
        "post": {
            "summary": "List the details of customer by the email.",
                "consumes": [
                "string",
                "application/json",
                "application/x-www-form-urlencoded"
            ],
                "produces": [
                "application/json"
            ],
                "parameters": [
                    {
                        "name": "email",
                        "in": "body",
                        "description": "Customer email to ge the data",
                        "required": true,
                        "schema": {
                        "properties": {
                            "id": {
                                "properties": {
                                    "abc": {
                                        "properties": {
                                            "inner_abc": {
                                                "type": "number",
                                                    "default": 1,
                                                    "example": 123
                                                }
                                            },
                                            "type": "object"
                                        },
                                        "xyz": {
                                        "type": "string",
                                            "default": "xyz default value",
                                            "example": "xyz example value"
                                        }
                                    },
                                    "type": "object"
                                }
                            }
                        }
                    }
                ],
                "responses": {
                "200": {
                    "description": "Details of the customer"
                    },
                    "400": {
                    "description": "Email required"
                    },
                    "404": {
                    "description": "Customer does not exist"
                    },
                    "default": {
                    "description": "an \"unexpected\" error"
                    }
                }
            }
        },
        "/getCustomerById.php": {
        "get": {
            "summary": "List the details of customer by the ID",
                "parameters": [
                    {
                        "name": "id",
                        "in": "query",
                        "description": "Customer ID to get the data",
                        "required": true,
                        "type": "integer"
                    }
                ],
                "responses": {
                "200": {
                    "description": "Details of the customer"
                    },
                    "400": {
                    "description": "ID required"
                    },
                    "404": {
                    "description": "Customer does not exist"
                    },
                    "default": {
                    "description": "an \"unexpected\" error"
                    }
                }
            }
        },
        "/getShipmentById.php": {
        "get": {
            "summary": "List the details of shipment by the ID",
                "parameters": [
                    {
                        "name": "id",
                        "in": "query",
                        "description": "Shipment ID to get the data",
                        "required": true,
                        "type": "integer"
                    }
                ],
                "responses": {
                "200": {
                    "description": "Details of the shipment"
                    },
                    "404": {
                    "description": "Shipment does not exist"
                    },
                    "400": {
                    "description": "ID required"
                    },
                    "default": {
                    "description": "an \"unexpected\" error"
                    }
                }
            }
        }
    },
    "definitions": {

    }
}

This can be imported into Postman as follow.

  1. Click on the 'Import' button in the top left corner of Postman UI.
  2. You will see multiple options to import the API doc. Click on the 'Paste Raw Text'.
  3. Paste the JSON format in the text area and click import.
  4. You will see all your APIs as 'Postman Collection' and can use it from the Postman.

Importing the JSON into Postman

Imported APIs

You can also use 'Import From Link'. Here paste the URL which generates the JSON format of the APIs from the Swagger or any other API Document tool.

This is my Document (JSON) generation file. It's in PHP. I have no idea of JAVA along with Swagger.

<?php
require("vendor/autoload.php");
$swagger = \Swagger\scan('path_of_the_directory_to_scan');
header('Content-Type: application/json');
echo $swagger;

What is the Simplest Way to Reverse an ArrayList?

Not the simplest way but if you're a fan of recursion you might be interested in the following method to reverse an ArrayList:

public ArrayList<Object> reverse(ArrayList<Object> list) {
    if(list.size() > 1) {                   
        Object value = list.remove(0);
        reverse(list);
        list.add(value);
    }
    return list;
}

Or non-recursively:

public ArrayList<Object> reverse(ArrayList<Object> list) {
    for(int i = 0, j = list.size() - 1; i < j; i++) {
        list.add(i, list.remove(j));
    }
    return list;
}

How can I round a number in JavaScript? .toFixed() returns a string?

Because its primary use is displaying numbers? If you want to round numbers, use Math.round() with apropriate factors.

Using gradle to find dependency tree

In Android Studio (at least since v2.3.3) you can run the command directly from the UI:

Click on the Gradle tab and then double click on :yourmodule -> Tasks -> android -> androidDependencies

The tree will be displayed in the Gradle Console tab

An image is worth a thousand words

How do I use floating-point division in bash?

As others have indicated, bash does not have built-in floating-point operators.

You can implement floating-point in bash, even without using calculator programs like bc and awk, or any external programs for that matter.

I'm doing exactly this in my project, shellmath, in three basic steps:

  1. Break the numbers down into their integer and fractional parts
  2. Use the built-in integer operators to process the parts separately while being careful about place-value and carrying
  3. Recombine the results

As a teaser, I've added a demo script that calculates e using its Taylor series centered at x=0.

Please check it out if you have a moment. I welcome your feedback!

jQuery checkbox change and click event

Well .. just for the sake of saving a headache (its past midnight here), I could come up with:

$('#checkbox1').click(function() {
  if (!$(this).is(':checked')) {
    var ans = confirm("Are you sure?");
     $('#textbox1').val(ans);
  }
});

Hope it helps

Why doesn't TFS get latest get the latest?

In my case, Get specific version, even checking both check boxes and undoing all pending changes didn't work.

Checked the work spaces. Edit current workspace. Check all paths. The solution path was incorrect and was pointing to a deleted folder.

Fixed the path and get latest worked fine.

npm install doesn't create node_modules directory

As soon as you have run npm init and you start installing npm packages it'll create the node_moduals folder after that first install

e.g

npm init

(Asks you to set up your package.json file)

npm install <package name here> --save-dev

installs package & creates the node modules directory

java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

use maven it will download all the required jar files for you.

in this case you need the below jar files:

slf4j-log4j12-1.6.1.jar slf4j-api-1.6.1.jar

These jars will also depend on the cassandra version which you are running. There are dependencies with cassandra version , jar version and jdk version you use.

You can use : jdk1.6 with : cassandra 1.1.12 and the above jars.

How to remove leading and trailing zeros in a string? Python

What about a basic

your_string.strip("0")

to remove both trailing and leading zeros ? If you're only interested in removing trailing zeros, use .rstrip instead (and .lstrip for only the leading ones).

More info in the doc.

You could use some list comprehension to get the sequences you want like so:

trailing_removed = [s.rstrip("0") for s in listOfNum]
leading_removed = [s.lstrip("0") for s in listOfNum]
both_removed = [s.strip("0") for s in listOfNum]

Java constructor/method with optional parameters?

You can't have optional arguments that default to a certain value in Java. The nearest thing to what you are talking about is java varargs whereby you can pass an arbitrary number of arguments (of the same type) to a method.

Get int value from enum in C#

I have recently converted away from using enums in my code in favour of instead using classes with protected constructors and predefined static instances (thanks to Roelof - C# Ensure Valid Enum Values - Futureproof Method).

In light of that, below's how I'd now approach this issue (including implicit conversion to/from int).

public class Question
{
    // Attributes
    protected int index;
    protected string name;
    // Go with a dictionary to enforce unique index
    //protected static readonly ICollection<Question> values = new Collection<Question>();
    protected static readonly IDictionary<int,Question> values = new Dictionary<int,Question>();

    // Define the "enum" values
    public static readonly Question Role = new Question(2,"Role");
    public static readonly Question ProjectFunding = new Question(3, "Project Funding");
    public static readonly Question TotalEmployee = new Question(4, "Total Employee");
    public static readonly Question NumberOfServers = new Question(5, "Number of Servers");
    public static readonly Question TopBusinessConcern = new Question(6, "Top Business Concern");

    // Constructors
    protected Question(int index, string name)
    {
        this.index = index;
        this.name = name;
        values.Add(index, this);
    }

    // Easy int conversion
    public static implicit operator int(Question question) =>
        question.index; //nb: if question is null this will return a null pointer exception

    public static implicit operator Question(int index) =>        
        values.TryGetValue(index, out var question) ? question : null;

    // Easy string conversion (also update ToString for the same effect)
    public override string ToString() =>
        this.name;

    public static implicit operator string(Question question) =>
        question?.ToString();

    public static implicit operator Question(string name) =>
        name == null ? null : values.Values.FirstOrDefault(item => name.Equals(item.name, StringComparison.CurrentCultureIgnoreCase));


    // If you specifically want a Get(int x) function (though not required given the implicit converstion)
    public Question Get(int foo) =>
        foo; //(implicit conversion will take care of the conversion for you)
}

The advantage of this approach is you get everything you would have from the enum, but your code's now much more flexible, so should you need to perform different actions based on the value of Question, you can put logic into Question itself (i.e. in the preferred OO fashion) as opposed to putting lots of case statements throughout your code to tackle each scenario.


NB: Answer updated 2018-04-27 to make use of C# 6 features; i.e. declaration expressions and lambda expression body definitions. See revision history for original code. This has the benefit of making the definition a little less verbose; which had been one of the main complaints about this answer's approach.

What does template <unsigned int N> mean?

It's perfectly possible to template a class on an integer rather than a type. We can assign the templated value to a variable, or otherwise manipulate it in a way we might with any other integer literal:

unsigned int x = N;

In fact, we can create algorithms which evaluate at compile time (from Wikipedia):

template <int N>
struct Factorial 
{
     enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0> 
{
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}

How to compile Tensorflow with SSE4.2 and AVX instructions?

This is the simplest method. Only one step.

It has significant impact on speed. In my case, time taken for a training step almost halved.

Refer custom builds of tensorflow

python pandas dataframe columns convert to dict key and value

With pandas it can be done as:

If lakes is your DataFrame:

area_dict = lakes.to_dict('records')

Expected initializer before function name

You are missing a semicolon at the end of your 'struct' definition.

Also,

*sotrudnik

needs to be

sotrudnik*

How do I loop through children objects in javascript?

In the year 2020 / 2021 it is even easier with Array.from to 'convert' from a array-like nodes to an actual array, and then using .map to loop through the resulting array. The code is as simple as the follows:

Array.from(tableFields.children).map((child)=>console.log(child))

Creating a new column based on if-elif-else condition

When you have multiple if conditions, numpy.select is the way to go:

In [4102]: import numpy as np
In [4098]: conditions = [df.A.eq(df.B), df.A.gt(df.B), df.A.lt(df.B)]
In [4096]: choices = [0, 1, -1]

In [4100]: df['C'] = np.select(conditions, choices)

In [4101]: df
Out[4101]: 
   A  B  C
a  2  2  0
b  3  1  1
c  1  3 -1

Send and receive messages through NSNotificationCenter in Objective-C?

There is also the possibility of using blocks:

NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
[[NSNotificationCenter defaultCenter] 
     addObserverForName:@"notificationName" 
     object:nil
     queue:mainQueue
     usingBlock:^(NSNotification *notification)
     {
          NSLog(@"Notification received!");
          NSDictionary *userInfo = notification.userInfo;

          // ...
     }];

Apple's documentation

How to resize image automatically on browser width resize but keep same height?

The website you linked doesn't changes the image's width but it actually cuts it off. For that it needs to be set as a background-image.

For more info about background-image look it at http://www.w3schools.com/cssref/pr_background-image.asp

Usage:

#divID {
    background-image:url(image_url);
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Best TCP port number range for internal applications

I can't see why you would care. Other than the "don't use ports below 1024" privilege rule, you should be able to use any port because your clients should be configurable to talk to any IP address and port!

If they're not, then they haven't been done very well. Go back and do them properly :-)

In other words, run the server at IP address X and port Y then configure clients with that information. Then, if you find you must run a different server on X that conflicts with your Y, just re-configure your server and clients to use a new port. This is true whether your clients are code, or people typing URLs into a browser.

I, like you, wouldn't try to get numbers assigned by IANA since that's supposed to be for services so common that many, many environments will use them (think SSH or FTP or TELNET).

Your network is your network and, if you want your servers on port 1234 (or even the TELNET or FTP ports for that matter), that's your business. Case in point, in our mainframe development area, port 23 is used for the 3270 terminal server which is a vastly different beast to telnet. If you want to telnet to the UNIX side of the mainframe, you use port 1023. That's sometimes annoying if you use telnet clients without specifying port 1023 since it hooks you up to a server that knows nothing of the telnet protocol - we have to break out of the telnet client and do it properly:

telnet big_honking_mainframe_box.com 1023

If you really can't make the client side configurable, pick one in the second range, like 48042, and just use it, declaring that any other software on those boxes (including any added in the future) has to keep out of your way.

How to set <Text> text to upper case in react native

@Cherniv Thanks for the answer

<Text style={{}}> {'Test'.toUpperCase()} </Text>

how to fix Cannot call sendRedirect() after the response has been committed?

The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.

It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.

JAVA 7 OFFICIAL LINK

ADDITIONAL INFO

What is the meaning of prepended double colon "::"?

:: is used to link something ( a variable, a function, a class, a typedef etc...) to a namespace, or to a class.

if there is no left hand side before ::, then it underlines the fact you are using the global namespace.

e.g.:

::doMyGlobalFunction();

Changing the interval of SetInterval while it's running

This can be initiated however you want. timeout is the method i used to keep it on the top of the hour.

I had the need for every hour to begin a code block on the hour. So this would start at server startup and run the interval hourly. Basicaly the initial run is to begin the interval within the same minute. So in a second from init, run immediately then on every 5 seconds.

var interval = 1000;
var timing =function(){
    var timer = setInterval(function(){
        console.log(interval);
        if(interval == 1000){ /*interval you dont want anymore or increment/decrement */
            interval = 3600000; /* Increment you do want for timer */
            clearInterval(timer);
            timing();
        }
    },interval);
}
timing();

Alternately if you wanted to just have something happen at start and then forever at a specific interval you could just call it at the same time as the setInterval. For example:

var this = function(){
 //do
}
setInterval(function(){
  this()
},3600000)
this()

Here we have this run the first time and then every hour.

Beautiful way to remove GET-variables with PHP?

You can use the server variables for this, for example $_SERVER['REQUEST_URI'], or even better: $_SERVER['PHP_SELF'].

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

Here is a modification for the prev. answer. The main difference is when the user is not authenticated, it uses the original "HandleUnauthorizedRequest" method to redirect to login page:

   protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {

        if (filterContext.HttpContext.User.Identity.IsAuthenticated) {

            filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(
                            new
                            {
                                controller = "Account",
                                action = "Unauthorised"
                            })
                        );
        }
        else
        {
             base.HandleUnauthorizedRequest(filterContext);
        }
    }

PHP If Statement with Multiple Conditions

It will be good to use array and compare each value 1 by 1 in loop. Its give advantage to change the length of your tests array. Write a function taking 2 parameters, 1 is test array and other one is the value to be tested.

$test_array = ('test1','test2', 'test3','test4');
for($i = 0; $i < count($test_array); $i++){
   if($test_value == $test_array[$i]){
       $ret_val = true;
       break;
   }
   else{
       $ret_val = false;
   }
}

How to display activity indicator in middle of the iphone screen?

If you are using Swift, this is how you do it

let activityView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
activityView.center = self.view.center
activityView.startAnimating()

self.view.addSubview(activityView)

XSS prevention in JSP/Servlet web application

My personal opinion is that you should avoid using JSP/ASP/PHP/etc pages. Instead output to an API similar to SAX (only designed for calling rather than handling). That way there is a single layer that has to create well formed output.

How to use relative/absolute paths in css URLs?

The URL is relative to the location of the CSS file, so this should work for you:

url('../../images/image.jpg')

The relative URL goes two folders back, and then to the images folder - it should work for both cases, as long as the structure is the same.

From https://www.w3.org/TR/CSS1/#url:

Partial URLs are interpreted relative to the source of the style sheet, not relative to the document

How do I copy SQL Azure database to my local development server?

I always use Import/Export Feature which seems to be the easiest one among all.

Step 1:

Get the backup from the azure instance as follows, Select the database ? Right click ? Tasks ? Export Data Tier Application.

Step 2: Give a specific name for the backup file and save it in your desired location

Step 3: That's it you have taken a backup of the database from sql instance to your local. Lets restore it to the local. Copy the backed up database to your C drive. Now open the PowerShell with administrator rights and navigate to C drive

Step 4: Lets download the powershell script to remove the master keyRemoveMasterKey.ps1 have the script on the same drive in this case its C.

Step 5 : Run the script as follows, .\RemoveMasterKey.ps1 -bacpacPath "C:\identity.bacpac"

That's it, now you can restore it on MSSQL 2017 in your local environment.

Step 6: Connect to your local server, and click Databases ? Import-Data-Tier-Application

Step 7 : Give a name for your database to restore.

Now you will see everything in green!

Read my blog with diagrams.

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

Some basic differences can be written in short:

MVC:

Traditional MVC is where there is a

  1. Model: Acts as the model for data
  2. View : Deals with the view to the user which can be the UI
  3. Controller: Controls the interaction between Model and View, where view calls the controller to update model. View can call multiple controllers if needed.

MVP:

Similar to traditional MVC but Controller is replaced by Presenter. But the Presenter, unlike Controller is responsible for changing the view as well. The view usually does not call the presenter.

MVVM

The difference here is the presence of View Model. It is kind of an implementation of Observer Design Pattern, where changes in the model are represented in the view as well, by the VM. Eg: If a slider is changed, not only the model is updated but the data which may be a text, that is displayed in the view is updated as well. So there is a two-way data binding.

How do you specify table padding in CSS? ( table, not cell padding )

You could set a margin for the table. Alternatively, wrap the table in a div and use the div's padding.

Different ways of adding to Dictionary

One is assigning a value while the other is adding to the Dictionary a new Key and Value.

if block inside echo statement?

Use a ternary operator:

echo '<option value="'.$value.'"'.($value=='United States' ? 'selected="selected"' : '').'>'.$value.'</option>';

And while you're at it, you could use printf to make your code more readable/manageable:

printf('<option value="%s" %s>%s</option>',
    $value,
    $value == 'United States' ? 'selected="selected"' : ''
    $value);

How do write IF ELSE statement in a MySQL query

SELECT col1, col2, IF( action = 2 AND state = 0, 1, 0 ) AS state from tbl1;

OR

SELECT col1, col2, (case when (action = 2 and state = 0) then 1 else 0 end) as state from tbl1;

both results will same....

How to convert const char* to char* in C?

A const to a pointer indicates a "read-only" memory location. Whereas the ones without const are a read-write memory areas. So, you "cannot" convert a const(read-only location) to a normal(read-write) location.

The alternate is to copy the data to a different read-write location and pass this pointer to the required function. You may use strdup() to perform this action.

How to set image name in Dockerfile?

Here is another version if you have to reference a specific docker file:

version: "3"
services:
  nginx:
    container_name: nginx
    build:
      context: ../..
      dockerfile: ./docker/nginx/Dockerfile
    image: my_nginx:latest

Then you just run

docker-compose build

How do I get the IP address into a batch-file variable?

Below script will store the ip address to the variable ip_address

@echo off

call :get_ip_address
echo %ip_address%

goto :eof

REM
REM get the ip address
REM
:get_ip_address
FOR /f "tokens=1 delims=:" %%d IN ('ping %computername% -4 -n 1 ^| find /i "reply"') do (FOR /F "tokens=3 delims= " %%g IN ("%%d") DO set ip_address=%%g)

goto :eof

Ideas from this blog post.

BeautifulSoup getting href

You can use find_all in the following way to find every a element that has an href attribute, and print each one:

from BeautifulSoup import BeautifulSoup

html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''

soup = BeautifulSoup(html)

for a in soup.find_all('a', href=True):
    print "Found the URL:", a['href']

The output would be:

Found the URL: some_url
Found the URL: another_url

Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all instead.


If you want all tags with an href, you can omit the name parameter:

href_tags = soup.find_all(href=True)

Convert categorical data in pandas dataframe

What I do is, I replace values.

Like this-

df['col'].replace(to_replace=['category_1', 'category_2', 'category_3'], value=[1, 2, 3], inplace=True)

In this way, if the col column has categorical values, they get replaced by the numerical values.

Maximum number of threads per process in Linux?

For anyone looking at this now, on systemd systems (in my case, specifically Ubuntu 16.04) there is another limit enforced by the cgroup pids.max parameter.

This is set to 12,288 by default, and can be overriden in /etc/systemd/logind.conf

Other advice still applies including pids_max, threads-max, max_maps_count, ulimits, etc.

Loading state button in Bootstrap 3

You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.

$("button").click(function() {
    var $btn = $(this);
    $btn.button('loading');
    // simulating a timeout
    setTimeout(function () {
        $btn.button('reset');
    }, 1000);
});

Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.

JSFIDDLE

Official Documentation

How to validate IP address in Python?

I think this would do it...

def validIP(address):
    parts = address.split(".")
    if len(parts) != 4:
        return False
    for item in parts:
        if not 0 <= int(item) <= 255:
            return False
    return True

Reading multiple Scanner inputs

If every input asks the same question, you should use a for loop and an array of inputs:

Scanner dd = new Scanner(System.in);
int[] vars = new int[3];

for(int i = 0; i < vars.length; i++) {
  System.out.println("Enter next var: ");
  vars[i] = dd.nextInt();
}

Or as Chip suggested, you can parse the input from one line:

Scanner in = new Scanner(System.in);
int[] vars = new int[3];

System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
  vars[i] = in.nextInt();

You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.

How do I sort a table in Excel if it has cell references in it?

You have a couple options:

(1) There's no way around cell references getting messed up when sorting when not using static references. The most basic way to deal with this is to simply copy and paste as values before sorting, which could be automated via a simple VBA macro.

(2) You could also try utilizing named ranges if you're using a number of common ranges across your formulas. You could define 'Sheet2!B23:28' as 'Range1' and reference 'Range1' within your formulas. In that case, sorting obviously wouldn't affect the range being specified since it's defined elsewhere.

HTH

phonegap open link in browser

Like this :

<a href="#" onclick="window.open('https://www.nbatou.com', '_system'); return false;">https://www.nbatou.com</a>

Regex to check whether a string contains only numbers

On input, if you want to filter out other characters and only show numbers in the input field, you could replace the value of the field on keyup:

    var yourInput = jQuery('#input-field');
    yourInput.keyup(function() {
        yourInput.val((yourInput.val().replace(/[^\d]/g,'')))
    })   

jQuery Button.click() event is triggered twice

This can as well be triggered by having both input and label inside the element with click listener.

You click on the label, which triggers a click event and as well another click event on the input for the label. Both events bubble to your element.

See this pen of a fancy CSS-only toggle: https://codepen.io/stepanh/pen/WaYzzO

Note: This is not jQuery specific, native listener is triggered 2x as well as shown in the pen.

How to make layout with rounded corners..?

For API 21+, Use Clip Views

Rounded outline clipping was added to the View class in API 21. See this training doc or this reference for more info.

This in-built feature makes rounded corners very easy to implement. It works on any view or layout and supports proper clipping.

Here's What To Do:

  • Create a rounded shape drawable and set it as your view's background: android:background="@drawable/round_outline"
  • Clip to outline in code: setClipToOutline(true)

The documentation used to say that you can set android:clipToOutline="true" the XML, but this bug is now finally resolved and the documentation now correctly states that you can only do this in code.

What It Looks Like:

examples with and without clipToOutline

Special Note About ImageViews

setClipToOutline() only works when the View's background is set to a shape drawable. If this background shape exists, View treats the background's outline as the borders for clipping and shadowing purposes.

This means that if you want to round the corners on an ImageView with setClipToOutline(), your image must come from android:src instead of android:background (since background is used for the rounded shape). If you MUST use background to set your image instead of src, you can use this nested views workaround:

  • Create an outer layout with its background set to your shape drawable
  • Wrap that layout around your ImageView (with no padding)
  • The ImageView (including anything else in the layout) will now be clipped to the outer layout's rounded shape.

Can I use git diff on untracked files?

Assuming you do not have local commits,

git diff origin/master

How to align title at center of ActionBar in default theme(Theme.Holo.Light)

This actually works:

 getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
 getActionBar().setCustomView(R.layout.custom_actionbar);
  ActionBar.LayoutParams p = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        p.gravity = Gravity.CENTER;

You have to define custom_actionbar.xml layout which is as per your requirement e.g. :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="#2e2e2e"
    android:orientation="vertical"
    android:gravity="center"
    android:layout_gravity="center">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/top_banner"
        android:layout_gravity="center"
        />
</LinearLayout>

Func vs. Action vs. Predicate

The difference between Func and Action is simply whether you want the delegate to return a value (use Func) or not (use Action).

Func is probably most commonly used in LINQ - for example in projections:

 list.Select(x => x.SomeProperty)

or filtering:

 list.Where(x => x.SomeValue == someOtherValue)

or key selection:

 list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)

Action is more commonly used for things like List<T>.ForEach: execute the given action for each item in the list. I use this less often than Func, although I do sometimes use the parameterless version for things like Control.BeginInvoke and Dispatcher.BeginInvoke.

Predicate is just a special cased Func<T, bool> really, introduced before all of the Func and most of the Action delegates came along. I suspect that if we'd already had Func and Action in their various guises, Predicate wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func and Action are used for widely disparate purposes.

Predicate is mostly used in List<T> for methods like FindAll and RemoveAll.

What is the easiest way to remove the first character from a string?

I prefer this:

str = "[12,23,987,43"
puts str[1..-1]
>> 12,23,987,43

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

This could be solved without VBA by the following technique.

In this example I am counting all the threes (3) in the range A:A of the sheets Page M904, Page M905 and Page M906.

List all the sheet names in a single continuous range like in the following example. Here listed in the range D3:D5.

enter image description here

Then by having the lookup value in cell B2, the result can be found in cell B4 by using the following formula:

=SUMPRODUCT(COUNTIF(INDIRECT("'"&D3:D5&"'!A:A"), B2))

File Permissions and CHMOD: How to set 777 in PHP upon file creation?

You just need to manually set the desired permissions with chmod():

private function writeFileContent($file, $content){
    $fp = fopen($file, 'w');
    fwrite($fp, $content);
    fclose($fp);

    // Set perms with chmod()
    chmod($file, 0777);
    return true;
}

How do you change the launcher logo of an app in Android Studio?

To quickly create a new set of icons and change the launcher icon in Android Studio, you can:

  1. Use this tool: https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html to upload your preferred image or icon (your source file). The tool then automatically creates a set of icons in all the different resolutions for the ic_launcher.png.

  2. Download the zip-file created by the tool, extract everything (which will create a folder structure for all the different resolutions) and then replace all the icons inside your project res folder: <AndroidStudioProjectPath>\app\src\main\res

Logging with Retrofit 2

First Add dependency to build.gradle:

implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'

While using Kotlin you can add Logging Interceptor like this :

companion object {
    val okHttpClient = OkHttpClient().newBuilder()
            .addInterceptor(HttpLoggingInterceptor().apply {
                level = HttpLoggingInterceptor.Level.BODY
            })
            .build()


    fun getRetrofitInstance(): Retrofit {
        val retrofit = Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(ScanNShopConstants.BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build()

        return retrofit
    }
}

How to concatenate properties from multiple JavaScript objects

This should do it:

_x000D_
_x000D_
function collect() {_x000D_
  var ret = {};_x000D_
  var len = arguments.length;_x000D_
  for (var i = 0; i < len; i++) {_x000D_
    for (p in arguments[i]) {_x000D_
      if (arguments[i].hasOwnProperty(p)) {_x000D_
        ret[p] = arguments[i][p];_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  return ret;_x000D_
}_x000D_
_x000D_
let a = { "one" : 1, "two" : 2 };_x000D_
let b = { "three" : 3 };_x000D_
let c = { "four" : 4, "five" : 5 };_x000D_
_x000D_
let d = collect(a, b, c);_x000D_
console.log(d);
_x000D_
_x000D_
_x000D_

Output:

{
  "one": 1,
  "two": 2,
  "three": 3,
  "four": 4,
  "five": 5
}

How to listen state changes in react.js?

The following lifecycle methods will be called when state changes. You can use the provided arguments and the current state to determine if something meaningful changed.

componentWillUpdate(object nextProps, object nextState)
componentDidUpdate(object prevProps, object prevState)

URL encoding in Android

Also you can use this

private static final String ALLOWED_URI_CHARS = "@#&=*+-_.,:!?()/~'%";
String urlEncoded = Uri.encode(path, ALLOWED_URI_CHARS);

it's the most simple method

How to print variables in Perl

print "Number of lines: $nids\n";
print "Content: $ids\n";

How did Perl complain? print $ids should work, though you probably want a newline at the end, either explicitly with print as above or implicitly by using say or -l/$\.

If you want to interpolate a variable in a string and have something immediately after it that would looks like part of the variable but isn't, enclose the variable name in {}:

print "foo${ids}bar";

Merge development branch with master

If you are on Mac or Ubuntu, go to the working folder of the branch. In the terminal

suppose harisdev is the branchname.

git checkout master

if there are untracked or uncommitted files you will get an error and you have to commit or delete all the untracked or uncommitted files.

git merge harisdev 

git push origin master

One last command to delete the branch.

$ git branch -d harisdev

How to center a (background) image within a div?

Use background-position:

background-position: 50% 50%;

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

Here my solution including seconds:

function convert_to_24h(time_str) {
    // Convert a string like 10:05:23 PM to 24h format, returns like [22,5,23]
    var time = time_str.match(/(\d+):(\d+):(\d+) (\w)/);
    var hours = Number(time[1]);
    var minutes = Number(time[2]);
    var seconds = Number(time[3]);
    var meridian = time[4].toLowerCase();

    if (meridian == 'p' && hours < 12) {
      hours += 12;
    }
    else if (meridian == 'a' && hours == 12) {
      hours -= 12;
    }
    return [hours, minutes, seconds];
  };

An URL to a Windows shared folder

I think there are two issues:

  1. You need to escape the slashes.
  2. Browser security.

Explanation:

  1. I checked one of mine, I have the pattern:

    <a href="file://///server01\fshare\dir1\dir2\dir3">useful link </a>
    

    Please note that we ended up with 5 slashes after the protocol (file:)

  2. Firefox will try to prevent cross site scripting. My solution was to modify prefs.js in the profile directory. You will add two lines:

    user_pref("capability.policy.localfilelinks.checkloaduri.enabled", "allAccess");
    user_pref("capability.policy.localfilelinks.sites", "http://mysite.company.org");
    

What is the difference between Views and Materialized Views in Oracle?

Materialized views are disk based and are updated periodically based upon the query definition.

Views are virtual only and run the query definition each time they are accessed.

C# Convert a Base64 -> byte[]

Try

byte[] incomingByteArray = receive...; // This is your Base64-encoded bute[]

byte[] decodedByteArray =Convert.FromBase64String (Encoding.ASCII.GetString (incomingByteArray)); 
// This work because all Base64-encoding is done with pure ASCII characters

Angular 2 / 4 / 5 not working in IE11

I had the exact same issue and none of the solutions worked for me. Instead adding the following line in the (homepage).html under <head> fixed it.

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

compare differences between two tables in mysql

INTERSECT needs to be emulated in MySQL:

SELECT  'robot' AS `set`, r.*
FROM    robot r
WHERE   ROW(r.col1, r.col2, …) NOT IN
        (
        SELECT  col1, col2, ...
        FROM    tbd_robot
        )
UNION ALL
SELECT  'tbd_robot' AS `set`, t.*
FROM    tbd_robot t
WHERE   ROW(t.col1, t.col2, …) NOT IN
        (
        SELECT  col1, col2, ...
        FROM    robot
        )

How do I make an auto increment integer field in Django?

What I needed: A document number with a fixed number of integers that would also act like an AutoField.

My searches took me all over incl. this page.

Finally I did something like this:

I created a table with a DocuNumber field as an IntegerField with foll. attributes:

  • max_length=6
  • primary_key=True
  • unique=True
  • default=100000

The max_length value anything as required (and thus the corresponding default= value).

A warning is issued while creating the said model, which I could ignore.

Afterwards, created a document (dummy) whence as expected, the document had an integer field value of 100000.

Afterwards changed the model key field as:

  • Changed the field type as: AutoField
  • Got rid of the max_length And defaultattributes
  • Retained the primary_key = True attribute

The next (desired document) created had the value as 100001 with subsequent numbers getting incremented by 1.

So far so good.

What does "|=" mean? (pipe equal operator)

You have already got sufficient answer for your question. But may be my answer help you more about |= kind of binary operators.

I am writing table for bitwise operators:
Following are valid:

----------------------------------------------------------------------------------------
Operator   Description                                   Example
----------------------------------------------------------------------------------------
|=        bitwise inclusive OR and assignment operator   C |= 2 is same as C = C | 2
^=        bitwise exclusive OR and assignment operator   C ^= 2 is same as C = C ^ 2
&=        Bitwise AND assignment operator                C &= 2 is same as C = C & 2
<<=       Left shift AND assignment operator             C <<= 2 is same as C = C << 2
>>=       Right shift AND assignment operator            C >>= 2 is same as C = C >> 2  
----------------------------------------------------------------------------------------

note all operators are binary operators.

Also Note: (for below points I wanted to add my answer)

  • >>> is bitwise operator in Java that is called Unsigned shift
    but >>>= not an operator in Java. >>>= operator

  • ~ is bitwise complement bits, 0 to 1 and 1 to 0 (Unary operator) but ~= not an operator.

  • Additionally, ! Called Logical NOT Operator, but != Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. e.g. (A != B) is true. where as A=!B means if B is true then A become false (and if B is false then A become true).

side note: | is not called pipe, instead its called OR, pipe is shell terminology transfer one process out to next..

Using "If cell contains" in VBA excel

This does the same, enhanced with CONTAINS:

Function SingleCellExtract(LookupValue As String, LookupRange As Range, ColumnNumber As Integer, Char As String)
Dim I As Long
Dim xRet As String
For I = 1 To LookupRange.Columns(1).Cells.Count
     If InStr(1, LookupRange.Cells(I, 1), LookupValue) > 0 Then
        If xRet = "" Then
            xRet = LookupRange.Cells(I, ColumnNumber) & Char
        Else
            xRet = xRet & "" & LookupRange.Cells(I, ColumnNumber) & Char
        End If
    End If
Next
SingleCellExtract = Left(xRet, Len(xRet) - 1)
End Function

Vertical Align Center in Bootstrap 4

I did it this way with Bootstrap 4.3.1:

<div class="d-flex vh-100">
  <div class="d-flex w-100 justify-content-center align-self-center">
    I'm in the middle
  </div>
</div>

Force IE compatibility mode off using tags

The meta tag solution wasn't working for us but setting it in the response header did:

header('X-UA-Compatible: IE=edge,chrome=1');

Difference between | and || or & and && for comparison

The instance in which you're using a single character (i.e. | or &) is a bitwise comparison of the results. As long as your language evaluates these expressions to a binary value they should return the same results. As a best practice, however, you should use the logical operator as that's what you mean (I think).

initializing a Guava ImmutableMap

if the map is short you can do:

ImmutableMap.of(key, value, key2, value2); // ...up to five k-v pairs

If it is longer then:

ImmutableMap.builder()
   .put(key, value)
   .put(key2, value2)
   // ...
   .build();

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

I created a script to ignore differences in line endings:

It will display the files which are not added to the commit list and were modified (after ignoring differences in line endings). You can add the argument "add" to add those files to your commit.

#!/usr/bin/perl

# Usage: ./gitdiff.pl [add]
#    add : add modified files to git

use warnings;
use strict;

my ($auto_add) = @ARGV;
if(!defined $auto_add) {
    $auto_add = "";
}

my @mods = `git status --porcelain 2>/dev/null | grep '^ M ' | cut -c4-`;
chomp(@mods);
for my $mod (@mods) {
    my $diff = `git diff -b $mod 2>/dev/null`;
    if($diff) {
        print $mod."\n";
        if($auto_add eq "add") {
            `git add $mod 2>/dev/null`;
        }
    }
}

Source code: https://github.com/lepe/scripts/blob/master/gitdiff.pl

Updates:

  • fix by evandro777 : When the file has space in filename or directory

HTTP could not register URL http://+:8000/HelloWCF/. Your process does not have access rights to this namespace

While I was able to solve this problem in one computer following the other users solutions, the command netsh didn't solve the issue in one of my machines and even though the current user had administrator rights I was still getting the "HTTP could not register URL.... Your process does not have access rights to this namespace". So I'm sharing my solution in case you still don't get it to work with the other solutions too.

After also trying to give write permissions to the user in the physical directory of my website and getting no success, I finally decided trying to change IIS settings.

As the images below show, I configured the Physical Path Credentials of my website to connect as an specifc user, which was an admin account with DOMAIN\username and password, and this was enough to make the error disapear.

enter image description here

enter image description here

enter image description here

How do I get the logfile from an Android device?

Two steps:

  • Generate the log
  • Load Gmail to send the log

.

  1. Generate the log

    File generateLog() {
        File logFolder = new File(Environment.getExternalStorageDirectory(), "MyFolder");
        if (!logFolder.exists()) {
            logFolder.mkdir();
        }
        String filename = "myapp_log_" + new Date().getTime() + ".log";
    
        File logFile = new File(logFolder, filename);
    
        try {
            String[] cmd = new String[] { "logcat", "-f", logFile.getAbsolutePath(), "-v", "time", "ActivityManager:W", "myapp:D" };
            Runtime.getRuntime().exec(cmd);
            Toaster.shortDebug("Log generated to: " + filename);
            return logFile;
        }
        catch (IOException ioEx) {
            ioEx.printStackTrace();
        }
    
        return null;
    }
    
  2. Load Gmail to send the log

    File logFile = generateLog();
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(logFile));
    intent.setType("multipart/");
    startActivity(intent);
    

References for #1

~~

For #2 - there are many different answers out there for how to load the log file to view and send. Finally, the solution here actually worked to both:

  • load Gmail as an option
  • attaches the file successfully

Big thanks to https://stackoverflow.com/a/22367055/2162226 for the correctly working answer

How to change checkbox's border style in CSS?

I suggest using "outline" instead of "border". For example: outline: 1px solid #1e5180.

Javascript extends class

Take a look at Simple JavaScript Inheritance and Inheritance Patterns in JavaScript.

The simplest method is probably functional inheritance but there are pros and cons.

php REQUEST_URI

You can either use regex, or keep on using str_replace.

Eg.

$url = parse_url($_SERVER['REQUEST_URI']);

if ($url != '/') {
    parse_str($url['query']);
    echo $id;
    echo $othervar;
}

Output will be: http://www.testing.com/123/123

Automatically accept all SDK licences

please mind your sdk location, I change the default folder, so i cant find sdkmanager in " ~/Library/Android/sdk/tools/bin/"....

Compare if BigDecimal is greater than zero

It's as simple as:

if (value.compareTo(BigDecimal.ZERO) > 0)

The documentation for compareTo actually specifies that it will return -1, 0 or 1, but the more general Comparable<T>.compareTo method only guarantees less than zero, zero, or greater than zero for the appropriate three cases - so I typically just stick to that comparison.

Multiplying across in a numpy array

Yet another trick (as of v1.6)

A=np.arange(1,10).reshape(3,3)
b=np.arange(3)

np.einsum('ij,i->ij',A,b)

I'm proficient with the numpy broadcasting (newaxis), but I'm still finding my way around this new einsum tool. So I had play around a bit to find this solution.

Timings (using Ipython timeit):

einsum: 4.9 micro
transpose: 8.1 micro
newaxis: 8.35 micro
dot-diag: 10.5 micro

Incidentally, changing a i to j, np.einsum('ij,j->ij',A,b), produces the matrix that Alex does not want. And np.einsum('ji,j->ji',A,b) does, in effect, the double transpose.

javascript Unable to get property 'value' of undefined or null reference

The issue is how you're attempting to get the value. Things like...

if ( document.frm_new_user_request.u_isid.value == '' )

won't work. You need to find the element you want to get the value of first. It's not quite like a server side language where you can type in an object's reference name and a period to get or assign values.

document.getElementById('[id goes here]').value;

will work. Note: JavaScript is case-sensitive

I would recommend using:

var variablename = document.getElementById('[id goes here]');

or

var variablename = document.getElementById('[id goes here]').value;

CSS : center form in page horizontally and vertically

If you want to do a horizontal centering, just put the form inside a DIV tag and apply align="center" attribute to it. So even if the form width is changed, your centering will remain the same.

<div align="center"><form id="form_login"><!--form content here--></form></div>

UPDATE

@G-Cyr is right. align="center" attribute is now obsolete. You can use text-align attribute for this as following.

<div style="text-align:center"><form id="form_login"><!--form content here--></form></div>

This will center all the content inside the parent DIV. An optional way is to use margin: auto CSS attribute with predefined widths and heights. Please follow the following thread for more information.

How to horizontally center a in another ?

Vertical centering is little difficult than that. To do that, you can do the following stuff.

html

<body>
<div id="parent">
    <form id="form_login">
     <!--form content here-->
    </form>
</div>
</body>

Css

#parent {
   display: table;
   width: 100%;
}
#form_login {
   display: table-cell;
   text-align: center;
   vertical-align: middle;
}

Difference between Ctrl+Shift+F and Ctrl+I in Eclipse

Ctrl+Shift+F formats the selected line(s) or the whole source code if you haven't selected any line(s) as per the format specified in your Eclipse, while Ctrl+I gives proper indent to the selected line(s) or the current line if you haven't selected any line(s). try this. or more precisely

The Ant editor that ships with Eclipse can be used to reformat

XML/XHTML/HTML code (with a few configuration options in Window > Preferences > Ant > Editor).

You can right-click a file then

Open With... > Other... > Internal Editors > Ant Editor

Or add a file association between .html (or .xhtml) and that editor with

Window > Preferences > General > Editors > File Associations

Once open in the editor, hit ESC then CTRL-F to reformat.

Xpath: select div that contains class AND whose specific child element contains text

You can change your second condition to check only the span element:

...and contains(div/span, 'someText')]

If the span isn't always inside another div you can also use

...and contains(.//span, 'someText')]

This searches for the span anywhere inside the div.

how to check for special characters php

preg_match('/'.preg_quote('^\'£$%^&*()}{@#~?><,@|-=-_+-¬', '/').'/', $string);

How to Create an excel dropdown list that displays text with a numeric hidden value

There are two types of drop down lists available (I am not sure since which version).

ActiveX Drop Down
You can set the column widths, so your hidden column can be set to 0.

Form Drop Down
You could set the drop down range to a hidden sheet and reference the cell adjacent to the selected item. This would also work with the ActiveX type control.

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

you may need to check whether the settings.xml file is correct. such as user name, password, third party url.

Java Wait and Notify: IllegalMonitorStateException

You're calling both wait and notifyAll without using a synchronized block. In both cases the calling thread must own the lock on the monitor you call the method on.

From the docs for notify (wait and notifyAll have similar documentation but refer to notify for the fullest description):

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Only one thread will be able to actually exit wait at a time after notifyAll as they'll all have to acquire the same monitor again - but all will have been notified, so as soon as the first one then exits the synchronized block, the next will acquire the lock etc.

What is the difference between print and puts?

A big difference is if you are displaying arrays. Especially ones with NIL. For example:

print [nil, 1, 2]

gives

[nil, 1, 2]

but

puts [nil, 1, 2]

gives

1
2

Note, no appearing nil item (just a blank line) and each item on a different line.

C++/CLI Converting from System::String^ to std::string

This worked for me:

#include <stdlib.h>
#include <string.h>
#include <msclr\marshal_cppstd.h>
//..
using namespace msclr::interop;
//..
System::String^ clrString = (TextoDeBoton);
std::string stdString = marshal_as<std::string>(clrString); //String^ to std
//System::String^ myString = marshal_as<System::String^>(MyBasicStirng); //std to String^
prueba.CopyInfo(stdString); //MyMethod
//..
//Where: String^ = TextoDeBoton;
//and stdString is a "normal" string;

java: ArrayList - how can I check if an index exists?

Quick and dirty test for whether an index exists or not. in your implementation replace list With your list you are testing.

public boolean hasIndex(int index){
    if(index < list.size())
        return true;
    return false;
}

or for 2Dimensional ArrayLists...

public boolean hasRow(int row){
    if(row < _matrix.size())
        return true;
    return false;
}

using BETWEEN in WHERE condition

You might also encounter an error message. "Operand type clash: date is incompatible with int.

Use single quotes around the dates. E.g.: $this->db->where("$accommodation BETWEEN '$minvalue' AND '$maxvalue'");

Rounded corners for <input type='text' /> using border-radius.htc for IE

Oh lord, don't do it this way. HTC files are never a good idea for performance and clarity reasons, and you're using too many vendor-specific parameters for something that can easily be done cross-browser all the way back to IE6.

Apply a background image to your input field with the rounded corners and make the field's background colour transparent with border:none applied instead.

NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext

After exiting eclipse I moved .eclipse (found in the user's home directory) to .eclipse.old (just in case I may have had to undo). The error does not show up any more and my projects are working fine after restarting eclipse.

Caution: I have a simple setup and this may not be the best for environments with advanced settings.

I am posting this as a separate answer as previously listed methods did not work for me.

How to change Status Bar text color in iOS

I'm using Xcode 6 beta 5 on a Swift project, for an iOS 7 app.

Here is what I did, and it works:

info.plist:

Enter image description here

How to change the default docker registry from docker.io to my private registry?

It turns out this is actually possible, but not using the genuine Docker CE or EE version.

You can either use Red Hat's fork of docker with the '--add-registry' flag or you can build docker from source yourself with registry/config.go modified to use your own hard-coded default registry namespace/index.

Making sure at least one checkbox is checked

I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them. Let's begin with giving the checkboxes a class so we can round them up very nicely. I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.

HTML

    <input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
    <input type="checkbox" class="checkbox" value=ck2 /> ck2<br />

JavaScript

function atLeastOneCheckboxIsChecked(){
    const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
    return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}

When called, the function will return false if no checkbox has been checked and true if one or both is.

It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true. the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.

What is @RenderSection in asp.net MVC

Here the defination of Rendersection from MSDN

In layout pages, renders the content of a named section.MSDN

In _layout.cs page put

@RenderSection("Bottom",false)

Here render the content of bootom section and specifies false boolean property to specify whether the section is required or not.

@section Bottom{
       This message form bottom.
}

That meaning if you want to bottom section in all pages, then you must use false as the second parameter at Rendersection method.

CSS: create white glow around image

Works like a charm!

.imageClass {
  -webkit-filter: drop-shadow(12px 12px 7px rgba(0,0,0,0.5));
}

Voila! That's it! Obviously this won't work in ie, but who cares...

PostgreSQL, checking date relative to "today"

You could also check using the age() function

select * from mytable where age( mydate, now() ) > '1 year';

age() wil return an interval.

For example age( '2015-09-22', now() ) will return -1 years -7 days -10:56:18.274131

See postgresql documentation

How to get all values from python enum class?

You can use IntEnum:

from enum import IntEnum

class Color(IntEnum):
   RED = 1
   BLUE = 2


print(int(Color.RED))   # prints 1

To get list of the ints:

enum_list = list(map(int, Color))
print(enum_list) # prints [1, 2]

Change mysql user password using command line

As of MySQL 8.0.18 This works fine for me

_x000D_
_x000D_
mysql> SET PASSWORD FOR 'user'@'localhost' = 'userpassword';
_x000D_
_x000D_
_x000D_

How does "304 Not Modified" work exactly?

When the browser puts something in its cache, it also stores the Last-Modified or ETag header from the server.

The browser then sends a request with the If-Modified-Since or If-None-Match header, telling the server to send a 304 if the content still has that date or ETag.

The server needs some way of calculating a date-modified or ETag for each version of each resource; this typically comes from the filesystem or a separate database column.

How to automatically add user account AND password with a Bash script?

Here is a script that will do it for you .....

You can add a list of users (or just one user) if you want, all in one go and each will have a different password. As a bonus you are presented at the end of the script with a list of each users password. .... If you want you can add some user maintenance options

like:

chage -m 18 $user
chage -M 28 $user

to the script that will set the password age and so on.

=======

#!/bin/bash

# Checks if you have the right privileges
if [ "$USER" = "root" ]
then

# CHANGE THIS PARAMETERS FOR A PARTICULAR USE
PERS_HOME="/home/"
PERS_SH="/bin/bash"

   # Checks if there is an argument
   [ $# -eq 0 ] && { echo >&2 ERROR: You may enter as an argument a text file containing users, one per line. ; exit 1; }
   # checks if there a regular file
   [ -f "$1" ] || { echo >&2 ERROR: The input file does not exists. ; exit 1; }
   TMPIN=$(mktemp)
   # Remove blank lines and delete duplicates 
   sed '/^$/d' "$1"| sort -g | uniq > "$TMPIN"

   NOW=$(date +"%Y-%m-%d-%X")
   LOGFILE="AMU-log-$NOW.log"

   for user in $(more "$TMPIN"); do
      # Checks if the user already exists.
      cut -d: -f1 /etc/passwd | grep "$user" > /dev/null
      OUT=$?
      if [ $OUT -eq 0 ];then
         echo >&2 "ERROR: User account: \"$user\" already exists."
         echo >&2 "ERROR: User account: \"$user\" already exists." >> "$LOGFILE"
      else
         # Create a new user
         /usr/sbin/useradd -d "$PERS_HOME""$user" -s "$PERS_SH" -m "$user"
         # passwdgen must be installed
         pass=$(passwdgen -paq --length 8)
         echo $pass | passwd --stdin $user
         # save user and password in a file
         echo -e $user"\t"$pass >> "$LOGFILE"
         echo "The user \"$user\" has been created and has the password: $pass"
      fi
   done
   rm -f "$TMPIN"
   exit 0
else
   echo >&2 "ERROR: You must be a root user to execute this script."
   exit 1
fi

===========

Hope this helps.

Cheers, Carel

Using Node.js require vs. ES6 import/export

The main advantages are syntactic:

  • More declarative/compact syntax
  • ES6 modules will basically make UMD (Universal Module Definition) obsolete - essentially removes the schism between CommonJS and AMD (server vs browser).

You are unlikely to see any performance benefits with ES6 modules. You will still need an extra library to bundle the modules, even when there is full support for ES6 features in the browser.

What is the best way to add options to a select from a JavaScript object with jQuery?

This looks nicer, provides readability, but is slower than other methods.

$.each(selectData, function(i, option)
{
    $("<option/>").val(option.id).text(option.title).appendTo("#selectBox");
});

If you want speed, the fastest (tested!) way is this, using array, not string concatenation, and using only one append call.

auxArr = [];
$.each(selectData, function(i, option)
{
    auxArr[i] = "<option value='" + option.id + "'>" + option.title + "</option>";
});

$('#selectBox').append(auxArr.join(''));

Is there any way to wait for AJAX response and halt execution?

The simple answer is to turn off async. But that's the wrong thing to do. The correct answer is to re-think how you write the rest of your code.

Instead of writing this:

function functABC(){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: function(data) {
            return data;
        }
    });
}

function foo () {
    var response = functABC();
    some_result = bar(response);
    // and other stuff and
    return some_result;
}

You should write it like this:

function functABC(callback){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: callback
    });
}

function foo (callback) {
    functABC(function(data){
        var response = data;
        some_result = bar(response);
        // and other stuff and
        callback(some_result);
    })
}

That is, instead of returning result, pass in code of what needs to be done as callbacks. As I've shown, callbacks can be nested to as many levels as you have function calls.


A quick explanation of why I say it's wrong to turn off async:

Turning off async will freeze the browser while waiting for the ajax call. The user cannot click on anything, cannot scroll and in the worst case, if the user is low on memory, sometimes when the user drags the window off the screen and drags it in again he will see empty spaces because the browser is frozen and cannot redraw. For single threaded browsers like IE7 it's even worse: all websites freeze! Users who experience this may think you site is buggy. If you really don't want to do it asynchronously then just do your processing in the back end and refresh the whole page. It would at least feel not buggy.

How to position three divs in html horizontally?

You can use floating elements like so:

<div id="the whole thing" style="height:100%; width:100%; overflow: hidden;">
    <div id="leftThing" style="float: left; width:25%; background-color:blue;">Left Side Menu</div>
    <div id="content" style="float: left; width:50%; background-color:green;">Random Content</div>
    <div id="rightThing" style="float: left; width:25%; background-color:yellow;">Right Side Menu</div>
</div>

Note the overflow: hidden; on the parent container, this is to make the parent grow to have the same dimensions as the child elements (otherwise it will have a height of 0).

python numpy machine epsilon

Another easy way to get epsilon is:

In [1]: 7./3 - 4./3 -1
Out[1]: 2.220446049250313e-16

String.replaceAll single backslashes with double backslashes

The String#replaceAll() interprets the argument as a regular expression. The \ is an escape character in both String and regex. You need to double-escape it for regex:

string.replaceAll("\\\\", "\\\\\\\\");

But you don't necessarily need regex for this, simply because you want an exact character-by-character replacement and you don't need patterns here. So String#replace() should suffice:

string.replace("\\", "\\\\");

Update: as per the comments, you appear to want to use the string in JavaScript context. You'd perhaps better use StringEscapeUtils#escapeEcmaScript() instead to cover more characters.

What are the differences between "git commit" and "git push"?

Well, basically git commit puts your changes into your local repo, while git push sends your changes to the remote location.

Clear form after submission with jQuery

A quick reset of the form fields is possible with this jQuery reset function. $(selector)[0].reset();

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

I changed my project to use Androidx, so I used the migration tool but some files(many files), didn't change automatically. I opened each file (activities, enums, fragments) and I found so many errors. I corrected them but the compile still show me incomprehensible errors. After looking for a solution I found this answer that someone said:

go to Analyze >> Inspect code

enter image description here

Whole Project:

enter image description here

It took some time and then showed me the result below:

enter image description here

As I corrected the errors I thought were important, I was running the build until the remaining errors were no longer affecting the build.

My Android Studio details

enter image description here

Get URL of ASP.Net Page in code-behind

Use this:

Request.Url.AbsoluteUri

That will get you the full path (including http://...)

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

I also have the same error. I have updated the jackson library version and error has gone.

<!-- Jackson to convert Java object to Json -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.4</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.4</version>
        </dependency>
    </dependencies>

and also check your data classes that have you created getters and setters for all the properties.

How to SSH into Docker?

It is a short way but not permanent

first create a container

docker run  ..... -p 22022:2222 .....

port 22022 on your host machine will map on 2222, we change the ssh port on container later , then on your container executing the following commands

apt update && apt install  openssh-server # install ssh server
passwd #change root password

in file /etc/ssh/sshd_config change these : uncomment Port and change it to 2222

Port 2222

uncomment PermitRootLogin to

PermitRootLogin yes

and finally restart ssh server

/etc/init.d/ssh start

you can login to your container now

ssh -p 2022 root@HostIP

Remember : if you restart the container you need to restart ssh server again

How do we use runOnUiThread in Android?

Try this: getActivity().runOnUiThread(new Runnable...

It's because:

1) the implicit this in your call to runOnUiThread is referring to AsyncTask, not your fragment.

2) Fragment doesn't have runOnUiThread.

However, Activity does.

Note that Activity just executes the Runnable if you're already on the main thread, otherwise it uses a Handler. You can implement a Handler in your fragment if you don't want to worry about the context of this, it's actually very easy:

// A class instance

private Handler mHandler = new Handler(Looper.getMainLooper());

// anywhere else in your code

mHandler.post(<your runnable>);

// ^ this will always be run on the next run loop on the main thread.

Convert Go map to json

Since this question was asked/last answered, support for non string key types for maps for json Marshal/UnMarshal has been added through the use of TextMarshaler and TextUnmarshaler interfaces here. You could just implement these interfaces for your key types and then json.Marshal would work as expected.

package main

import (
    "encoding/json"
    "fmt"
    "strconv"
)

// Num wraps the int value so that we can implement the TextMarshaler and TextUnmarshaler 
type Num int

func (n *Num) UnmarshalText(text []byte) error {
    i, err := strconv.Atoi(string(text))
    if err != nil {
        return err
    }
    *n = Num(i)
    return nil
}

func (n Num) MarshalText() (text []byte, err error) {
    return []byte(strconv.Itoa(int(n))), nil
}

type Foo struct {
    Number Num    `json:"number"`
    Title  string `json:"title"`
}

func main() {
    datas := make(map[Num]Foo)

    for i := 0; i < 10; i++ {
        datas[Num(i)] = Foo{Number: 1, Title: "test"}
    }

    jsonString, err := json.Marshal(datas)
    if err != nil {
        panic(err)
    }

    fmt.Println(datas)
    fmt.Println(jsonString)

    m := make(map[Num]Foo)
    err = json.Unmarshal(jsonString, &m)
    if err != nil {
        panic(err)
    }

    fmt.Println(m)
}

Output:

map[1:{1 test} 2:{1 test} 4:{1 test} 7:{1 test} 8:{1 test} 9:{1 test} 0:{1 test} 3:{1 test} 5:{1 test} 6:{1 test}]
[123 34 48 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 49 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 50 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 51 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 52 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 53 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 54 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 55 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 56 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 57 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 125]
map[4:{1 test} 5:{1 test} 6:{1 test} 7:{1 test} 0:{1 test} 2:{1 test} 3:{1 test} 1:{1 test} 8:{1 test} 9:{1 test}]

Operator overloading on class templates

You need to say the following (since you befriend a whole template instead of just a specialization of it, in which case you would just need to add a <> after the operator<<):

template<typename T>
friend std::ostream& operator<<(std::ostream& out, const MyClass<T>& classObj);

Actually, there is no need to declare it as a friend unless it accesses private or protected members. Since you just get a warning, it appears your declaration of friendship is not a good idea. If you just want to declare a single specialization of it as a friend, you can do that like shown below, with a forward declaration of the template before your class, so that operator<< is regognized as a template.

// before class definition ...
template <class T>
class MyClass;

// note that this "T" is unrelated to the T of MyClass !
template<typename T>
std::ostream& operator<<(std::ostream& out, const MyClass<T>& classObj);

// in class definition ...
friend std::ostream& operator<< <>(std::ostream& out, const MyClass<T>& classObj);

Both the above and this way declare specializations of it as friends, but the first declares all specializations as friends, while the second only declares the specialization of operator<< as a friend whose T is equal to the T of the class granting friendship.

And in the other case, your declaration looks OK, but note that you cannot += a MyClass<T> to a MyClass<U> when T and U are different type with that declaration (unless you have an implicit conversion between those types). You can make your += a member template

// In MyClass.h
template<typename U>
MyClass<T>& operator+=(const MyClass<U>& classObj);


// In MyClass.cpp
template <class T> template<typename U>
MyClass<T>& MyClass<T>::operator+=(const MyClass<U>& classObj) {
  // ...
  return *this;
}

Where is the Docker daemon log?

Docker for Mac (Beta)

~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/log/d??ocker.log

In CSS how do you change font size of h1 and h2

h1 {
  font-weight: bold;
  color: #fff;
  font-size: 32px;
}

h2 {
  font-weight: bold;
  color: #fff;
  font-size: 24px;
}

Note that after color you can use a word (e.g. white), a hex code (e.g. #fff) or RGB (e.g. rgb(255,255,255)) or RGBA (e.g. rgba(255,255,255,0.3)).

Request redirect to /Account/Login?ReturnUrl=%2f since MVC 3 install on server

A solve this adding in the option defaultURL the path my application

<forms loginUrl="/Users/Login" protection="All" timeout="2880" name="001WVCookie" path="/" requireSSL="false" slidingExpiration="true" defaultUrl="/Home/Index" cookieless="UseCookies" enableCrossAppRedirects="false" />

LDAP Authentication using Java

This is my LDAP Java login test application supporting LDAP:// and LDAPS:// self-signed test certificate. Code is taken from few SO posts, simplified implementation and removed legacy sun.java.* imports.

Usage
I have run this in Windows7 and Linux machines against WinAD directory service. Application prints username and member groups.

$ java -cp classes test.LoginLDAP url=ldap://1.2.3.4:389 [email protected] password=mypwd

$ java -cp classes test.LoginLDAP url=ldaps://1.2.3.4:636 [email protected] password=mypwd

Test application supports temporary self-signed test certificates for ldaps:// protocol, this DummySSLFactory accepts any server cert so man-in-the-middle is possible. Real life installation should import server certificate to a local JKS keystore file and not using dummy factory.

Application uses enduser's username+password for initial context and ldap queries, it works for WinAD but don't know if can be used for all ldap server implementations. You could create context with internal username+pwd then run queries to see if given enduser is found.

LoginLDAP.java

package test;

import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;

public class LoginLDAP {

    public static void main(String[] args) throws Exception {
        Map<String,String> params = createParams(args);

        String url = params.get("url"); // ldap://1.2.3.4:389 or ldaps://1.2.3.4:636
        String principalName = params.get("username"); // [email protected]
        String domainName = params.get("domain"); // mydomain.com or empty

        if (domainName==null || "".equals(domainName)) {
            int delim = principalName.indexOf('@');
            domainName = principalName.substring(delim+1);
        }

        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, url); 
        props.put(Context.SECURITY_PRINCIPAL, principalName); 
        props.put(Context.SECURITY_CREDENTIALS, params.get("password")); // secretpwd
        if (url.toUpperCase().startsWith("LDAPS://")) {
            props.put(Context.SECURITY_PROTOCOL, "ssl");
            props.put(Context.SECURITY_AUTHENTICATION, "simple");
            props.put("java.naming.ldap.factory.socket", "test.DummySSLSocketFactory");         
        }

        InitialDirContext context = new InitialDirContext(props);
        try {
            SearchControls ctrls = new SearchControls();
            ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            NamingEnumeration<SearchResult> results = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", ctrls);
            if(!results.hasMore())
                throw new AuthenticationException("Principal name not found");

            SearchResult result = results.next();
            System.out.println("distinguisedName: " + result.getNameInNamespace() ); // CN=Firstname Lastname,OU=Mycity,DC=mydomain,DC=com

            Attribute memberOf = result.getAttributes().get("memberOf");
            if(memberOf!=null) {
                for(int idx=0; idx<memberOf.size(); idx++) {
                    System.out.println("memberOf: " + memberOf.get(idx).toString() ); // CN=Mygroup,CN=Users,DC=mydomain,DC=com
                    //Attribute att = context.getAttributes(memberOf.get(idx).toString(), new String[]{"CN"}).get("CN");
                    //System.out.println( att.get().toString() ); //  CN part of groupname
                }
            }
        } finally {
            try { context.close(); } catch(Exception ex) { }
        }       
    }

    /**
     * Create "DC=sub,DC=mydomain,DC=com" string
     * @param domainName    sub.mydomain.com
     * @return
     */
    private static String toDC(String domainName) {
        StringBuilder buf = new StringBuilder();
        for (String token : domainName.split("\\.")) {
            if(token.length()==0) continue;
            if(buf.length()>0)  buf.append(",");
            buf.append("DC=").append(token);
        }
        return buf.toString();
    }

    private static Map<String,String> createParams(String[] args) {
        Map<String,String> params = new HashMap<String,String>();  
        for(String str : args) {
            int delim = str.indexOf('=');
            if (delim>0) params.put(str.substring(0, delim).trim(), str.substring(delim+1).trim());
            else if (delim==0) params.put("", str.substring(1).trim());
            else params.put(str, null);
        }
        return params;
    }

}

And SSL helper class.

package test;

import java.io.*;
import java.net.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;    
import javax.net.*;
import javax.net.ssl.*;

public class DummySSLSocketFactory extends SSLSocketFactory {
    private SSLSocketFactory socketFactory;
    public DummySSLSocketFactory() {
        try {
          SSLContext ctx = SSLContext.getInstance("TLS");
          ctx.init(null, new TrustManager[]{ new DummyTrustManager()}, new SecureRandom());
          socketFactory = ctx.getSocketFactory();
        } catch ( Exception ex ){ throw new IllegalArgumentException(ex); }
    }

      public static SocketFactory getDefault() { return new DummySSLSocketFactory(); }

      @Override public String[] getDefaultCipherSuites() { return socketFactory.getDefaultCipherSuites(); }
      @Override public String[] getSupportedCipherSuites() { return socketFactory.getSupportedCipherSuites(); }

      @Override public Socket createSocket(Socket socket, String string, int i, boolean bln) throws IOException {
        return socketFactory.createSocket(socket, string, i, bln);
      }
      @Override public Socket createSocket(String string, int i) throws IOException, UnknownHostException {
        return socketFactory.createSocket(string, i);
      }
      @Override public Socket createSocket(String string, int i, InetAddress ia, int i1) throws IOException, UnknownHostException {
        return socketFactory.createSocket(string, i, ia, i1);
      }
      @Override public Socket createSocket(InetAddress ia, int i) throws IOException {
        return socketFactory.createSocket(ia, i);
      }
      @Override public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException {
        return socketFactory.createSocket(ia, i, ia1, i1);
      }
}

class DummyTrustManager implements X509TrustManager {
    @Override public void checkClientTrusted(X509Certificate[] xcs, String str) {
        // do nothing
    }
    @Override public void checkServerTrusted(X509Certificate[] xcs, String str) {
        /*System.out.println("checkServerTrusted for authType: " + str); // RSA
        for(int idx=0; idx<xcs.length; idx++) {
            X509Certificate cert = xcs[idx];
            System.out.println("X500Principal: " + cert.getSubjectX500Principal().getName());
        }*/
    }
    @Override public X509Certificate[] getAcceptedIssuers() {
        return new java.security.cert.X509Certificate[0];
    }
}

Named capturing groups in JavaScript regex?

ECMAScript 2018 introduces named capturing groups into JavaScript regexes.

Example:

  const auth = 'Bearer AUTHORIZATION_TOKEN'
  const { groups: { token } } = /Bearer (?<token>[^ $]*)/.exec(auth)
  console.log(token) // "Prints AUTHORIZATION_TOKEN"

If you need to support older browsers, you can do everything with normal (numbered) capturing groups that you can do with named capturing groups, you just need to keep track of the numbers - which may be cumbersome if the order of capturing group in your regex changes.

There are only two "structural" advantages of named capturing groups I can think of:

  1. In some regex flavors (.NET and JGSoft, as far as I know), you can use the same name for different groups in your regex (see here for an example where this matters). But most regex flavors do not support this functionality anyway.

  2. If you need to refer to numbered capturing groups in a situation where they are surrounded by digits, you can get a problem. Let's say you want to add a zero to a digit and therefore want to replace (\d) with $10. In JavaScript, this will work (as long as you have fewer than 10 capturing group in your regex), but Perl will think you're looking for backreference number 10 instead of number 1, followed by a 0. In Perl, you can use ${1}0 in this case.

Other than that, named capturing groups are just "syntactic sugar". It helps to use capturing groups only when you really need them and to use non-capturing groups (?:...) in all other circumstances.

The bigger problem (in my opinion) with JavaScript is that it does not support verbose regexes which would make the creation of readable, complex regular expressions a lot easier.

Steve Levithan's XRegExp library solves these problems.

Simplest way to read json from a URL in java

I have found this to be the easiest way by far.

Use this method:

public static String getJSON(String url) {
        HttpsURLConnection con = null;
        try {
            URL u = new URL(url);
            con = (HttpsURLConnection) u.openConnection();

            con.connect();


            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            return sb.toString();


        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (con != null) {
                try {
                    con.disconnect();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return null;
    }

And use it like this:

String json = getJSON(url);
JSONObject obj;
   try {
         obj = new JSONObject(json);
         JSONArray results_arr = obj.getJSONArray("results");
         final int n = results_arr.length();
            for (int i = 0; i < n; ++i) {
                // get the place id of each object in JSON (Google Search API)
                String place_id = results_arr.getJSONObject(i).getString("place_id");
            }


   }

Form Google Maps URL that searches for a specific places near specific coordinates

additional info:

http://maps.google.com/maps?q=loc: put in latitude and longitude after, example:

http://maps.google.com/maps?q=loc:51.03841,-114.01679

this will show pointer on map, but will suppress geocoding of the address, best for a location without an address, or for a location where google maps shows the incorrect address.

CSS3 scrollbar styling on a div

You're setting overflow: hidden. This will hide anything that's too large for the <div>, meaning scrollbars won't be shown. Give your <div> an explicit width and/or height, and change overflow to auto:

.scroll {
   width: 200px;
   height: 400px;
   overflow: scroll;
}

If you only want to show a scrollbar if the content is longer than the <div>, change overflow to overflow: auto. You can also only show one scrollbar by using overflow-y or overflow-x.

How to use git merge --squash?

You can use tool I've created to make this process easier: git-squash. For example to squash all commits on feature branch that has been branched from master branch, write:

git squash master
git push --force

How do I find the duplicates in a list and create another list with them?

Use the sort() function. Duplicates can be identified by looping over it and checking l1[i] == l1[i+1].

After installation of Gulp: “no command 'gulp' found”

I'm on lubuntu 19.10

I've used combination of previous answers, and didn't tweak the $PATH.

  1. npm uninstall --global gulp gulp-cli This removes any package if they are already there.
  2. sudo npm install --global gulp-cli Reinstall it as root user.

If you want to do copy and paste

npm uninstall --global gulp gulp-cli && sudo npm install --global gulp-cli 

should work

I guess --global is unnecessary here as it's installed using sudo, but I've used it just in case.

mysql delete under safe mode

Googling around, the popular answer seems to be "just turn off safe mode":

SET SQL_SAFE_UPDATES = 0;
DELETE FROM instructor WHERE salary BETWEEN 13000 AND 15000;
SET SQL_SAFE_UPDATES = 1;

If I'm honest, I can't say I've ever made a habit of running in safe mode. Still, I'm not entirely comfortable with this answer since it just assumes you should go change your database config every time you run into a problem.

So, your second query is closer to the mark, but hits another problem: MySQL applies a few restrictions to subqueries, and one of them is that you can't modify a table while selecting from it in a subquery.

Quoting from the MySQL manual, Restrictions on Subqueries:

In general, you cannot modify a table and select from the same table in a subquery. For example, this limitation applies to statements of the following forms:

DELETE FROM t WHERE ... (SELECT ... FROM t ...);
UPDATE t ... WHERE col = (SELECT ... FROM t ...);
{INSERT|REPLACE} INTO t (SELECT ... FROM t ...);

Exception: The preceding prohibition does not apply if you are using a subquery for the modified table in the FROM clause. Example:

UPDATE t ... WHERE col = (SELECT * FROM (SELECT ... FROM t...) AS _t ...);

Here the result from the subquery in the FROM clause is stored as a temporary table, so the relevant rows in t have already been selected by the time the update to t takes place.

That last bit is your answer. Select target IDs in a temporary table, then delete by referencing the IDs in that table:

DELETE FROM instructor WHERE id IN (
  SELECT temp.id FROM (
    SELECT id FROM instructor WHERE salary BETWEEN 13000 AND 15000
  ) AS temp
);

SQLFiddle demo.

SQL Error: 0, SQLState: 08S01 Communications link failure

I'm answering on specific to this error code(08s01).

usually, MySql close socket connections are some interval of time that is wait_timeout defined on MySQL server-side which by default is 8hours. so if a connection will timeout after this time and the socket will throw an exception which SQLState is "08s01".

1.use connection pool to execute Query, make sure the pool class has a function to make an inspection of the connection members before it goes time_out.

2.give a value of <wait_timeout> greater than the default, but the largest value is 24 days

3.use another parameter in your connection URL, but this method is not recommended, and maybe deprecated.

PHP mkdir: Permission denied problem

This error occurs if you are using the wrong path.

For e.g:

I'm using ubuntu system and my project folder name is 'myproject'

Suppose I have myproject/public/report directory exist and want to create a new folder called orders

Then I need a whole path where my project exists. You can get the path by PWD command

So my root path will be = '/home/htdocs/myproject/'

$dir = '/home/htdocs/myproject/public/report/Orders';

if (!is_dir($dir)) {
   mkdir($dir, 0775, true);
}

It will work for you !! Enjoy !!

How to add a "confirm delete" option in ASP.Net Gridview?

This code is working fine for me.

jQuery("a").filter(function () {
        return this.innerHTML.indexOf("Delete") == 0;
        }).click(function () { return confirm("Are you sure you want to delete this record?"); 
});

LoDash: Get an array of values from an array of object properties

If you are using native javascript then you can use this code -

let ids = users.map(function(obj, index) {

    return obj.id;
})

console.log(ids); //[12, 14, 16, 18]

How do I add a library project to Android Studio?

Add this in your build gradle file:

 dependencies {
     implementation 'com.jakewharton:butterknife:9.0.0'
}

Convert PEM traditional private key to PKCS8 private key

To convert the private key from PKCS#1 to PKCS#8 with openssl:

# openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in pkcs1.key -out pkcs8.key

That will work as long as you have the PKCS#1 key in PEM (text format) as described in the question.

Code to loop through all records in MS Access

In "References", import DAO 3.6 object reference.

private sub showTableData

dim db as dao.database
dim rs as dao.recordset

set db = currentDb
set rs = db.OpenRecordSet("myTable") 'myTable is a MS-Access table created previously

'populate the table
rs.movelast
rs.movefirst

do while not rs.EOF
   debug.print(rs!myField) 'myField is a field name in table myTable
   rs.movenext             'press Ctrl+G to see debuG window beneath
loop

msgbox("End of Table")

end sub

You can interate data objects like queries and filtered tables in different ways:

Trhough query:

private sub showQueryData

dim db as dao.database
dim rs as dao.recordset
dim sqlStr as string

sqlStr = "SELECT * FROM customers as c WHERE c.country='Brazil'"

set db = currentDb
set rs = db.openRecordset(sqlStr)

rs.movefirst

do while not rs.EOF
  debug.print("cust ID: " & rs!id & " cust name: " & rs!name)
  rs.movenext
loop

msgbox("End of customers from Brazil")

end sub

You should also look for "Filter" property of the recordset object to filter only the desired records and then interact with them in the same way (see VB6 Help in MS-Access code window), or create a "QueryDef" object to run a query and use it as a recordset too (a little bit more tricky). Tell me if you want another aproach.

I hope I've helped.

View more than one project/solution in Visual Studio

Don't know whether this is useful but if you want to work with multiple projects without navigating through projects tree {like multi window} you can try opening VS in another virtual desktop (at least it's possible for Windows 10) by holding Ctrl+win+D. Then open another VS studio and open your other project there. You can switch between projects by Ctrl+win+arrow key {left/right}.

How to remove list elements in a for loop in Python?

As other answers have said, the best way to do this involves making a new list - either iterate over a copy, or construct a list with only the elements you want and assign it back to the same variable. The difference between these depends on your use case, since they affect other variables for the original list differently (or, rather, the first affects them, the second doesn't).

If a copy isn't an option for some reason, you do have one other option that relies on an understanding of why modifying a list you're iterating breaks. List iteration works by keeping track of an index, incrementing it each time around the loop until it falls off the end of the list. So, if you remove at (or before) the current index, everything from that point until the end shifts one spot to the left. But the iterator doesn't know about this, and effectively skips the next element since it is now at the current index rather than the next one. However, removing things that are after the current index doesn't affect things.

This implies that if you iterate the list back to front, if you remove an item at the current index, everything to it's right shifts left - but that doesn't matter, since you've already dealt with all the elements to the right of the current position, and you're moving left - the next element to the left is unaffected by the change, and so the iterator gives you the element you expect.

TL;DR:

>>> a = list(range(5))
>>> for b in reversed(a):
    if b == 3:
        a.remove(b)
>>> a
[0, 1, 2, 4]

However, making a copy is usually better in terms of making your code easy to read. I only mention this possibility for sake of completeness.

What is MVC and what are the advantages of it?

Separation of concerns is the biggy.

Being able to tease these components apart makes the code easier to re-use and independently test. If you don't actually know what MVC is, be careful about trying to understand people's opinions as there is still some contention about what the "Model" is (whether it is the business objects/DataSets/DataTables or if it represents the underlying service layer).

I've seen all sorts of implementations that call themselves MVC but aren't exactly and as the comments in Jeff's article show MVC is a contentious point that I don't think developers will ever fully agree upon.

A good round up of all of the different MVC types is available here.

How do you change library location in R?

This post is just to mention an additional option. In case you need to set custom R libs in your Linux shell script you may easily do so by

export R_LIBS="~/R/lib"

See R admin guide on complete list of options.

On Windows, running "import tensorflow" generates No module named "_pywrap_tensorflow" error

For each Tensorflow's version, it requires different version of CuDnn. On www.tensorflow.org, they did not mentioned about that in installation guide!

My case use tensorflow version 1.3 which uses cuDNN 6. https://github.com/tensorflow/tensorflow/releases.

Please check your tensorfow version and cuDNN version if they are match together.

And please set path environment for cuDNN, if it still does not work, please check the answer from @Chris Han.

How do I alias commands in git?

It is given here Aliases.Even there are great answers here, I added this because it differs in windows and linux

How do I get the name of a Ruby class?

Here's the correct answer, extracted from comments by Daniel Rikowski and pseidemann. I'm tired of having to weed through comments to find the right answer...

If you use Rails (ActiveSupport):

result.class.name.demodulize

If you use POR (plain-ol-Ruby):

result.class.name.split('::').last

Return array from function

Your BlockID function uses the undefined variable images, which will lead to an error. Also, you should not use an Array here - JavaScripts key-value-maps are plain objects:

function BlockID() {
    return {
        "s": "Images/Block_01.png",
        "g": "Images/Block_02.png",
        "C": "Images/Block_03.png",
        "d": "Images/Block_04.png"
    };
}

Set width of a "Position: fixed" div relative to parent div

Fixed positioning is supposed to define everything in relation to the viewport, so position:fixed is always going to do that. Try using position:relative on the child div instead. (I realize you might need the fixed positioning for other reasons, but if so - you can't really make the width match it's parent with out JS without inherit)

Using prepared statements with JDBCTemplate

I've tried a select statement now with a PreparedStatement, but it turned out that it was not faster than the Jdbc template. Maybe, as mezmo suggested, it automatically creates prepared statements.

Anyway, the reason for my sql SELECTs being so slow was another one. In the WHERE clause I always used the operator LIKE, when all I wanted to do was finding an exact match. As I've found out LIKE searches for a pattern and therefore is pretty slow.

I'm using the operator = now and it's much faster.

Getting a union of two arrays in JavaScript

Adapted from: https://stackoverflow.com/a/4026828/1830259

Array.prototype.union = function(a) 
{
    var r = this.slice(0);
    a.forEach(function(i) { if (r.indexOf(i) < 0) r.push(i); });
    return r;
};

Array.prototype.diff = function(a)
{
    return this.filter(function(i) {return a.indexOf(i) < 0;});
};

var s1 = [1, 2, 3, 4];
var s2 = [3, 4, 5, 6];

console.log("s1: " + s1);
console.log("s2: " + s2);
console.log("s1.union(s2): " + s1.union(s2));
console.log("s2.union(s1): " + s2.union(s1));
console.log("s1.diff(s2): " + s1.diff(s2));
console.log("s2.diff(s1): " + s2.diff(s1));

// Output:
// s1: 1,2,3,4
// s2: 3,4,5,6
// s1.union(s2): 1,2,3,4,5,6
// s2.union(s1): 3,4,5,6,1,2
// s1.diff(s2): 1,2
// s2.diff(s1): 5,6 

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'

You said it worked fine when you were using SQL Express edition. By default express editions create a named instance & run in NT Authority\Network Service.

SQL Server STD by default install a default instance & run in NT Authority\SYSTEM.

Do you have both the full SQL edition & Express edition installed on the same machine?

  1. It could be that somewhere the connection string still refers to the Named instance 'SQLEXPRESS' rather than the default instance created by the full version.

  2. Also where is the connection string defined? In IIS or your code? Make sure that if defined in many places, all point to same SQL instance & database.

  3. Also try looking at the detailed error present in the SQL Server error logs. The error logged in event log are not complete for secuirty reasons. This will also help you to know if the connection was made to the correct SQL Server.

  4. Also make sure that the machine on which SQL is installed is accessible & IIS is trying to access the same machine. In my company sometimes due to wrong name resolution, the query fails since most of our computers have SQL installed & the query lands in the wrong SQL Server.

  5. Make sure that the database exists in the SQL Server. The name displayed under databases in SQL Management Studio should match that in the connection string.

run program in Python shell

If you want to avoid writing all of this everytime, you can define a function :

def run(filename):
    exec(open(filename).read())

and then call it

run('filename.py')

How to define dimens.xml for every different screen size in android?

I've uploaded a simple java program which takes your project location and the dimension file you want as input. Based on that, it would output the corresponding dimension file in the console. Here's the link to it:

https://github.com/akeshwar/Dimens-for-different-screens-in-Android/blob/master/Main.java

Here's the full code for the reference:

public class Main {


    /**
     * You can change your factors here. The current factors are in accordance with the official documentation.
     */
    private static final double LDPI_FACTOR = 0.375;
    private static final double MDPI_FACTOR = 0.5;
    private static final double HDPI_FACTOR = 0.75;
    private static final double XHDPI_FACTOR = 1.0;
    private static final double XXHDPI_FACTOR = 1.5;
    private static final double XXXHDPI_FACTOR = 2.0;

    private static double factor;

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


        Scanner in = new Scanner(System.in);
        System.out.println("Enter the location of the project/module");
        String projectPath = in.nextLine();

        System.out.println("Which of the following dimension file do you want?\n1. ldpi \n2. mdpi \n3. hdpi \n4. xhdpi \n5. xxhdpi \n6. xxxhdpi");

        int dimenType = in.nextInt();

        switch (dimenType) {
            case 1: factor = LDPI_FACTOR;
                break;
            case 2: factor = MDPI_FACTOR;
                break;
            case 3: factor = HDPI_FACTOR;
                break;
            case 4: factor = XHDPI_FACTOR;
                break;
            case 5: factor = XXHDPI_FACTOR;
                break;
            case 6: factor = XXXHDPI_FACTOR;
                break;
            default:
                factor = 1.0;
        }

        //full path = "/home/akeshwar/android-sat-bothIncluded-notintegrated/code/tpr-5-5-9/princetonReview/src/main/res/values/dimens.xml"
        //location of the project or module = "/home/akeshwar/android-sat-bothIncluded-notintegrated/code/tpr-5-5-9/princetonReview/"


        /**
         * In case there is some I/O exception with the file, you can directly copy-paste the full path to the file here:
         */
        String fullPath = projectPath + "/src/main/res/values/dimens.xml";

        FileInputStream fstream = new FileInputStream(fullPath);
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

        String strLine;

        while ((strLine = br.readLine()) != null)   {
            modifyLine(strLine);
        }
        br.close();

    }

    private static void modifyLine(String line) {

        /**
         * Well, this is how I'm detecting if the line has some dimension value or not.
         */
        if(line.contains("p</")) {
            int endIndex = line.indexOf("p</");

            //since indexOf returns the first instance of the occurring string. And, the actual dimension would follow after the first ">" in the screen
            int begIndex = line.indexOf(">");

            String prefix = line.substring(0, begIndex+1);
            String root = line.substring(begIndex+1, endIndex-1);
            String suffix = line.substring(endIndex-1,line.length());


            /**
             * Now, we have the root. We can use it to create different dimensions. Root is simply the dimension number.
             */

            double dimens = Double.parseDouble(root);
            dimens = dimens*factor*1000;
            dimens = (double)((int)dimens);
            dimens = dimens/1000;
            root = dimens + "";

            System.out.println(prefix + " " +  root + " " + suffix );

        }

        System.out.println(line);
    }
}

Get today date in google appScript

function myFunction() {
  var sheetname = "DateEntry";//Sheet where you want to put the date
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetname);
    // You could use now Date(); on its own but it will not look nice.
  var date = Utilities.formatDate(new Date(), "GMT+5:30", "yyyy-MM-dd");
    //var endDate = date;
    sheet.getRange(sheet.getLastRow() + 1,1).setValue(date); //Gets the last row which had value, and goes to the next empty row to put new values.
}

How to jquery alert confirm box "yes" & "no"

I won't write your code but what you looking for is something like a jquery dialog

take a look here

jQuery modal-confirmation

$(function() {
    $( "#dialog-confirm" ).dialog({
      resizable: false,
      height:140,
      modal: true,
      buttons: {
        "Delete all items": function() {
          $( this ).dialog( "close" );
        },
        Cancel: function() {
          $( this ).dialog( "close" );
        }
      }
    });
  });

<div id="dialog-confirm" title="Empty the recycle bin?">
  <p>
    <span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>
    These items will be permanently deleted and cannot be recovered. Are you sure?
  </p>
</div>

OS X Bash, 'watch' command

Use MacPorts:

$ sudo port install watch

Delete entire row if cell contains the string X

  1. Delete rows 1 and 2 so that your headings are on row 1
  2. Put this in a macro (IT WILL CHECK THROUGH ROW 75000, YOU CAN LOWER THE NUMBER IF YOU WOULD LIKE

    Columns("E:E").Select Selection.AutoFilter ActiveSheet.Range("$E$1:$E$75000").AutoFilter Field:=1, Criteria1:="none" Range("E2:E75000").SpecialCells(xlCellTypeVisible).Select Selection.EntireRow.Delete ActiveSheet.Cells.EntireRow.Hidden = False ActiveSheet.Range("$E$1:$E$75000").AutoFilter Field:=1 Columns("E:E").Select Selection.AutoFilter Range("E2").Select Range("A1").Select

How does the FetchMode work in Spring Data JPA

According to Vlad Mihalcea (see https://vladmihalcea.com/hibernate-facts-the-importance-of-fetch-strategy/):

JPQL queries may override the default fetching strategy. If we don’t explicitly declare what we want to fetch using inner or left join fetch directives, the default select fetch policy is applied.

It seems that JPQL query might override your declared fetching strategy so you'll have to use join fetch in order to eagerly load some referenced entity or simply load by id with EntityManager (which will obey your fetching strategy but might not be a solution for your use case).

How to get the GL library/headers?

If you're on Windows, they are installed with the platform SDK (or Visual Studio). However the header files are only compatible with OpenGL 1.1. You need to create function pointers for new functionality it later versions. Can you please clarify what version of OpenGL you're trying to use.

Make function wait until element exists

A more modern approach to waiting for elements:

while(!document.querySelector(".my-selector")) {
  await new Promise(r => setTimeout(r, 500));
}
// now the element is loaded

Note that this code would need to be wrapped in an async function.

Converting JSONarray to ArrayList

Generic variant

public static <T> List<T> getList(JSONArray jsonArray) throws Exception {

    List<T> list = new ArrayList<>(jsonArray.length());

    for (int i = 0; i < jsonArray.length(); i++) {

        list.add((T)jsonArray.get(i));
    }

    return list;

}

//Usage

List<String> listKeyString = getList(dataJsonObject.getJSONArray("keyString"));

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

I'm probably a bit late to the party, but I wrote the junitcategorizer for my thesis project at TOPdesk. Earlier versions indeed used a company internal Parent POM. So your problems are caused by the Parent POM not being resolvable, since it is not available to the outside world.

You can either:

  • Remove the <parent> block, but then have to configure the Surefire, Compiler and other plugins yourself
  • (Only applicable to this specific case!) Change it to point to our Open Source Parent POM by setting:
<parent>
    <groupId>com.topdesk</groupId>
    <artifactId>open-source-parent</artifactId>
    <version>1.2.0</version>
</parent>