Programs & Examples On #Accessorytype

The type of standard accessory view the cell should use (normal state). The accessory view appears in the right side of the cell in the table view’s normal (default) state. The standard accessory views include the disclosure chevron. The default is UITableViewCellAccessoryNone.

Add swipe to delete UITableViewCell

func tableView(_ tableView: UITableView, editActionsForRowAt: IndexPath) -> [UITableViewRowAction]? {

  let share = UITableViewRowAction(style: .normal, title: "Share") { action, index in
    //handle like delete button
    print("share button tapped")

  share.backgroundColor = .lightGray

  let delete = UITableViewRowAction(style: .normal, title: "Delete") { action, index in
    self.nameArray.remove(at: editActionsForRowAt.row)
    self.swipeTable.deleteRows(at: [editActionsForRowAt], with: .right)

    print("delete button tapped")

  delete.backgroundColor = .orange
  return [share,delete]

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
  return true

Difference between HashSet and HashMap?

HashMap is a implementation of Map interface HashSet is an implementation of Set Interface

HashMap Stores data in form of key value pair HashSet Store only objects

Put method is used to add element in map Add method is used to add element is Set

In hash map hashcode value is calculated using key object Here member object is used for calculating hashcode value which can be same for two objects so equal () method is used to check for equality if it returns false that means two objects are different.

HashMap is faster than hashset because unique key is used to access object HashSet is slower than Hashmap

Android widget: How to change the text of a button

This is very easy

Button btn = (Button) findViewById(;

trying to align html button at the center of the my page

Here's your solution: JsFiddle

Basically, place your button into a div with centred text:

<div class="wrapper">
    <button class="button">Button</button>

With the following styles:

.wrapper {
    text-align: center;

.button {
    position: absolute;
    top: 50%;

There are many ways to skin a cat, and this is just one.

Why does ASP.NET webforms need the Runat="Server" attribute?

I usually don't like to guess, but I'm going to on this one...

If you remember Microsoft's .NET marketing hype back in the day (2001?), it was hard to tell what .NET even was. Was it a server? a programming platform? a language? something new entirely? Given the ads, it was ambiguously anything you wanted it to be - it just solved any problem you might have.

So, my guess is there was a hidden grand vision that ASP.NET code could run anywhere - server side OR client side, in a copy of Internet Explorer tied to the .NET runtime. runat="server" is just a vestigial remnant, left behind because it's client-side equivalent never made it to production.

Remember those weird ads?

Related: Article from The Register with some .NET history.

How to Identify Microsoft Edge browser via CSS?

More accurate for Edge (do not include latest IE 15) is:

@supports (display:-ms-grid) { ... }

@supports (-ms-ime-align:auto) { ... } works for all Edge versions (currently up to IE15).

Returning JSON from PHP to JavaScript?

Here are a couple of things missing in the previous answers:

  1. Set header in your PHP:

    header('Content-type: application/json');
    echo json_encode($array);
  2. json_encode() can return a JavaScript array instead of JavaScript object, see:
    Returning JSON from a PHP Script
    This could be important to know in some cases as arrays and objects are not the same.

How can I get the behavior of GNU's readlink -f on a Mac?

The answer from @Keith Smith gives an infinite loop.

Here is my answer, which i use only on SunOS (SunOS miss so much POSIX and GNU commands).

It's a script file you have to put in one of your $PATH directories:

! (($#)) && echo -e "ERROR: readlink <link to analyze>" 1>&2 && exit 99

while [ -L "$link" ]; do
  link=$(/bin/ls -ldq "$link")
  link="${link##* -> }"
  link=$(realpath "$link")
  [ "$link" == "$lastlink" ] && echo -e "ERROR: link loop detected on $link" 1>&2 && break

echo "$link"

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

Here is another simple implementation -

 * Date range
 * @param $first
 * @param $last
 * @param string $step
 * @param string $format
 * @return array
function dateRange( $first, $last, $step = '+1 day', $format = 'Y-m-d' ) {
    $dates = [];
    $current = strtotime( $first );
    $last = strtotime( $last );

    while( $current <= $last ) {

        $dates[] = date( $format, $current );
        $current = strtotime( $step, $current );

    return $dates;


print_r( dateRange( '2010-07-26', '2010-08-05') );

Array (
    [0] => 2010-07-26
    [1] => 2010-07-27
    [2] => 2010-07-28
    [3] => 2010-07-29
    [4] => 2010-07-30
    [5] => 2010-07-31
    [6] => 2010-08-01
    [7] => 2010-08-02
    [8] => 2010-08-03
    [9] => 2010-08-04
    [10] => 2010-08-05

What is difference between Axios and Fetch?

In addition... I was playing around with various libs in my test and noticed their different handling of 4xx requests. In this case my test returns a json object with a 400 response. This is how 3 popular libs handle the response:

// request-promise-native
const body = request({ url: url, json: true })
const res = await t.throws(body);

// node-fetch
const body = await fetch(url)
console.log(await body.json())

// Axios
const body = axios.get(url)
const res = await t.throws(body);

Of interest is that request-promise-native and axios throw on 4xx response while node-fetch doesn't. Also fetch uses a promise for json parsing.

Storing files in SQL Server

There's still no simple answer. It depends on your scenario. MSDN has documentation to help you decide.

There are other options covered here. Instead of storing in the file system directly or in a BLOB, you can use the FileStream or File Table in SQL Server 2012. The advantages to File Table seem like a no-brainier (but admittedly I have no personal first-hand experience with them.)

The article is definitely worth a read.

How do I bottom-align grid elements in bootstrap fluid layout

You can use flex:

@media (min-width: 768px) {
  .row-fluid {
    display: flex;
    align-items: flex-end;

Django - after login, redirect user to his custom page -->

Got into django recently and been looking into a solution to that and found a method that might be useful.

So for example, if using allouth the default redirect is accounts/profile. Make a view that solely redirects to a location of choice using the username field like so:

def profile(request):
    return redirect('-----choose where-----' + name + '/')

Then create a view that captures it in one of your apps, for example:

def profile(request, name):
    user = get_object_or_404(User, username=name)
    return render(request, 'myproject/user.html', {'profile': user})

Where the urlpatterns capture would look like this:

url(r'^(?P<name>.+)/$', views.profile, name='user')

Works well for me.

How do I pass command-line arguments to a WinForms application?

static void Main(string[] args)
  // For the sake of this example, we're just printing the arguments to the console.
  for (int i = 0; i < args.Length; i++) {
    Console.WriteLine("args[{0}] == {1}", i, args[i]);

The arguments will then be stored in the args string array:

$ AppB.exe firstArg secondArg thirdArg
args[0] == firstArg
args[1] == secondArg
args[2] == thirdArg

How to change the text on the action bar

Update: Latest ActionBar (Title) pattern:

FYI, ActionBar was introduced in API Level 11. ActionBar is a window feature at the top of the Activity that may display the activity title, navigation modes, and other interactive items like search.

I exactly remember about customizing title bar and making it consistent through the application. So I can make a comparison with the earlier days and can list some of the advantages of using ActionBar:

  1. It offers your users a familiar interface across applications that the system gracefully adapts for different screen configurations.
  2. Developers don't need to write much code for displaying the Activity Title, icons and navigation modes because ActionBar is already ready with top level abstraction.

For example:

enter image description here

enter image description here

=> Normal way,

getActionBar().setTitle("Hello world App");   
getSupportActionBar().setTitle("Hello world App");  // provide compatibility to all the versions

=> Customizing Action Bar,

For example:

public void setActionBar(String heading) {
    // TODO Auto-generated method stub actionBar = getSupportActionBar();
    actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.title_bar_gray)));


Styling the Action Bar:

The ActionBar provides you with basic and familiar looks, navigation modes and other quick actions to perform. But that doesn't mean it looks the same in every app. You can customize it as per your UI and design requirements. You just have to define and write styles and themes.

Read more at: Styling the Action Bar

And if you want to generate styles for ActionBar then this Style Generator tool can help you out.


Old: Earlier days:

=> Normal way,

you can Change the Title of each screen (i.e. Activity) by setting their Android:label

   <activity android:name=".Hello_World"
                  android:label="This is the Hello World Application">

=> Custom - Title - bar

But if you want to Customize title-bar in your own way, i.e. Want to put Image icon and custom-text, then the following code works for me:


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


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

<ImageView android:id="@+id/ImageView01" 


  android:text="This is my new title" 

public class TitleBar extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        final boolean customTitleSupported = 
        if (customTitleSupported) {
        final TextView myTitleText = (TextView) findViewById(;
        if (myTitleText != null) {
            myTitleText.setText("NEW TITLE");
            // user can also set color using "Color" and then
            // "Color value constant"
            // myTitleText.setBackgroundColor(Color.GREEN);


The strings.xml file is defined under the values folder.

<?xml version="1.0" encoding="utf-8"?>
    <string name="hello">Hello World, Set_Text_TitleBar!</string>
    <string name="app_name">Set_Text_TitleBar</string>
    <color name="titlebackgroundcolor">#3232CD</color>
    <color name="titletextcolor">#FFFF00</color>

Why does typeof array with objects return "object" and not "array"?

Quoting the spec

15.4 Array Objects

Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^32-1. A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 2^32. The value of the length property is numerically greater than the name of every property whose name is an array index; whenever a property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index; and whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted. This constraint applies only to own properties of an Array object and is unaffected by length or array index properties that may be inherited from its prototypes.

And here's a table for typeof

enter image description here

To add some background, there are two data types in JavaScript:

  1. Primitive Data types - This includes null, undefined, string, boolean, number and object.
  2. Derived data types/Special Objects - These include functions, arrays and regular expressions. And yes, these are all derived from "Object" in JavaScript.

An object in JavaScript is similar in structure to the associative array/dictionary seen in most object oriented languages - i.e., it has a set of key-value pairs.

An array can be considered to be an object with the following properties/keys:

  1. Length - This can be 0 or above (non-negative).
  2. The array indices. By this, I mean "0", "1", "2", etc are all properties of array object.

Hope this helped shed more light on why typeof Array returns an object. Cheers!

How to efficiently build a tree from a flat structure?

one elegant way to do this is to represent items in the list as string holding a dot separated list of parents, and finally a value:


When assembling a tree, you would end up with something like:

  port: 90
  hostname: localhost
    port: 1234
    host: localhost

I have a configuration library that implements this override configuration (tree) from command line arguments (list). The algorithm to add a single item to the list to a tree is here.

TCPDF not render all CSS properties

I found this:

// Remove tag bottom and top margins

$tagvs = array( 'p' => array( 
                              0 => array('h' => 0, 'n' => 0), 
                              1 => array('h' => 0, 'n' => 0)

in here:

Use it to remove 'p' tags properties (bottom and top), then position the 'p' text inside a cell.

how to destroy bootstrap modal window completely?

I had a same scenario where I would open a new modal on a button click. Once done, I want to completely remove it from my page... I use remove to delete the modal.. On button click I would check if modal exists , and if true I would destroy it and create a new modal ..

$("#wizard").click(function() {
    /* find if wizard is already open */
    if($('.wizard-modal').length) {

Oracle SQL Developer: Unable to find a JVM

Probably this is you are looking for (from this post):

Oracle SQL developer is NOT support on 64 bits JDK. To solve it, install a 32 bits / x86 JDK and update your SQL developer config file, so that it points to the 32 bits JDK.

Fix it! Edit the “sqldeveloper.conf“, which can be found under “{ORACLE_HOME}\sqldeveloper\sqldeveloper\bin\sqldeveloper.conf“, make sure “SetJavaHome” is point to your 32 bits JDK.

Update: Based on @FGreg answer below, in the Sql Developer version 4.XXX you can do it in user-specific config file:

  • Go to Properties -> Help -> About
  • Add / Change SetJavaHome to your path (for example - C:\Program Files (x86)\Java\jdk1.7.0_03) - this will override the setting in sqldeveloper.conf

Update 2: Based on @krm answer below, if your SQL Developer and JDK "bits" versions are not same, you can try to set the value of SetJavaHome property in product.conf

SetJavaHome C:\Program Files\Java\jdk1.7.0_80

The product.conf file is in my case located in the following directory:


Understanding PIVOT function in T-SQL

A pivot is used to convert one of the columns in your data set from rows into columns (this is typically referred to as the spreading column). In the example you have given, this means converting the PhaseID rows into a set of columns, where there is one column for each distinct value that PhaseID can contain - 1, 5 and 6 in this case.

These pivoted values are grouped via the ElementID column in the example that you have given.

Typically you also then need to provide some form of aggregation that gives you the values referenced by the intersection of the spreading value (PhaseID) and the grouping value (ElementID). Although in the example given the aggregation that will be used is unclear, but involves the Effort column.

Once this pivoting is done, the grouping and spreading columns are used to find an aggregation value. Or in your case, ElementID and PhaseIDX lookup Effort.

Using the grouping, spreading, aggregation terminology you will typically see example syntax for a pivot as:

WITH PivotData AS
    SELECT <grouping column>
        , <spreading column>
        , <aggregation column>
    FROM <source table>
SELECT <grouping column>, <distinct spreading values>
FROM PivotData
    PIVOT (<aggregation function>(<aggregation column>)
        FOR <spreading column> IN <distinct spreading values>));

This gives a graphical explanation of how the grouping, spreading and aggregation columns convert from the source to pivoted tables if that helps further.

How to use ConfigurationManager

Go to tools >> nuget >> console and type:

Install-Package System.Configuration.ConfigurationManager 

If you want a specific version:

Install-Package System.Configuration.ConfigurationManager -Version 4.5.0

Your ConfigurationManager dll will now be imported and the code will begin to work.

How to completely remove borders from HTML table

This is what resolved the problem for me:

In your HTML tr tag, add this:

style="border-collapse: collapse; border: none;"

That removed all the borders that were showing on the table row.

AWS S3 CLI - Could not connect to the endpoint URL

Assuming that your profile in ~/aws/config is using the region (instead of AZ as per your original question); the other cause is your client's inability to connect to In my case, I was unable to resolve that DNS name due to an error in my network configuration. Fixing the DNS issue solved my problem.

jQuery how to bind onclick event to dynamically added HTML element

How about the Live method?

$('.add_to_this a').live('click', function() {
    alert('hello from binded function call');

Still, what you did about looks like it should work. There's another post that looks pretty similar.

Execute command on all files in a directory

How about this:

find /some/directory -maxdepth 1 -type f -exec cmd option {} \; > results.out
  • -maxdepth 1 argument prevents find from recursively descending into any subdirectories. (If you want such nested directories to get processed, you can omit this.)
  • -type -f specifies that only plain files will be processed.
  • -exec cmd option {} tells it to run cmd with the specified option for each file found, with the filename substituted for {}
  • \; denotes the end of the command.
  • Finally, the output from all the individual cmd executions is redirected to results.out

However, if you care about the order in which the files are processed, you might be better off writing a loop. I think find processes the files in inode order (though I could be wrong about that), which may not be what you want.

Why is vertical-align:text-top; not working in CSS

The all above not work for me, I have just checked this and its work :

vertical-align: super;

 <div id="lbk_mng_rdooption" style="float: left;">
     <span class="bold" style="vertical-align: super;">View:</span>

I know by padding or margin will work, but that is last choise I prefer.

javax.naming.NoInitialContextException - Java

We need to specify the INITIAL_CONTEXT_FACTORY, PROVIDER_URL, USERNAME, PASSWORD etc. of JNDI to create an InitialContext.

In a standalone application, you can specify that as below

Hashtable env = new Hashtable();
env.put(Context.PROVIDER_URL, "ldap://");
env.put(Context.SECURITY_PRINCIPAL, "joeuser");
env.put(Context.SECURITY_CREDENTIALS, "joepassword");

Context ctx = new InitialContext(env);

But if you are running your code in a Java EE container, these values will be fetched by the container and used to create an InitialContext as below



these values will be set while starting the container as JVM arguments. So if you are running the code in a container, the following will work

InitialContext ctx = new InitialContext();

Abort trap 6 error in C

Try this:

void drawInitialNim(int num1, int num2, int num3){
    int board[3][50] = {0}; // This is a local variable. It is not possible to use it after returning from this function. 

    int i, j, k;

    for(i=0; i<num1; i++)
        board[0][i] = 'O';
    for(i=0; i<num2; i++)
        board[1][i] = 'O';
    for(i=0; i<num3; i++)
        board[2][i] = 'O';

    for (j=0; j<3;j++) {
        for (k=0; k<50; k++) {
            if(board[j][k] != 0)
                printf("%c", board[j][k]);

How can I create a correlation matrix in R?

Have a look at qtlcharts. It allows you to create interactive correlation matrices:

iris$Species <- NULL
iplotCorr(iris, reorder=TRUE)

enter image description here

It's more impressive when you correlate more variables, like in the package's vignette: enter image description here

Disable all Database related auto configuration in Spring Boot

I was getting this error even if I did all the solutions mentioned above.

 by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfig ...

At some point when i look up the POM there was this dependency in it


And the Pojo class had the following imports

import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id;

Which clearly shows the application was expecting a datasource.

What I did was I removed the JPA dependency from pom and replaced the imports for the pojo with the following once

import; import;

Finally I got SUCCESSFUL build. Check it out you might have run into the same problem

What does it mean by command cd /d %~dp0 in Windows

Let's dissect it. There are three parts:

  1. cd -- This is change directory command.
  2. /d -- This switch makes cd change both drive and directory at once. Without it you would have to do cd %~d0 & cd %~p0. (%~d0 Changs active drive, cd %~p0 change the directory).
  3. %~dp0 -- This can be dissected further into three parts:
    1. %0 -- This represents zeroth parameter of your batch script. It expands into the name of the batch file itself.
    2. %~0 -- The ~ there strips double quotes (") around the expanded argument.
    3. %dp0 -- The d and p there are modifiers of the expansion. The d forces addition of a drive letter and the p adds full path.

How can I specify a [DllImport] path at runtime?

Even better than Ran's suggestion of using GetProcAddress, simply make the call to LoadLibrary before any calls to the DllImport functions (with only a filename without a path) and they'll use the loaded module automatically.

I've used this method to choose at runtime whether to load a 32-bit or 64-bit native DLL without having to modify a bunch of P/Invoke-d functions. Stick the loading code in a static constructor for the type that has the imported functions and it'll all work fine.

What is a unix command for deleting the first N characters of a line?

sed 's/^.\{5\}//' logfile 

and you replace 5 by the number you should do the trick...

EDIT if for each line sed 's/^.\{5\}//g' logfile

Get the date (a day before current time) in Bash

Advanced Bash-scripting Guide

date +%Y:%m:%d -d "yesterday"

For details about the date format see the man page for date

date --date='-1 day'

Error: stray '\240' in program

As mentioned in a previous reply, this generally comes when compiling copy pasted code. If you have a bash shell, the following command generally works:

iconv -f utf-8 -t ascii//translit input.c > output.c

Import Error: No module named numpy

You should try to install numpy using one of those:

pip install numpy
pip2 install numpy
pip3 install numpy

For some reason in my case pip2 solved the problem

How to emulate a do-while loop in Python?

Here's a very simple way to emulate a do-while loop:

condition = True
while condition:
    # loop body here
    condition = test_loop_condition()
# end of loop

The key features of a do-while loop are that the loop body always executes at least once, and that the condition is evaluated at the bottom of the loop body. The control structure show here accomplishes both of these with no need for exceptions or break statements. It does introduce one extra Boolean variable.

Pandas sort by group aggregate and column

Groupby A:

In [0]: grp = df.groupby('A')

Within each group, sum over B and broadcast the values using transform. Then sort by B:

In [1]: grp[['B']].transform(sum).sort('B')
2 -2.829710
5 -2.829710
1  0.253651
4  0.253651
0  0.551377
3  0.551377

Index the original df by passing the index from above. This will re-order the A values by the aggregate sum of the B values:

In [2]: sort1 = df.ix[grp[['B']].transform(sum).sort('B').index]

In [3]: sort1
     A         B      C
2  baz -0.528172  False
5  baz -2.301539   True
1  bar -0.611756   True
4  bar  0.865408  False
0  foo  1.624345  False
3  foo -1.072969   True

Finally, sort the 'C' values within groups of 'A' using the sort=False option to preserve the A sort order from step 1:

In [4]: f = lambda x: x.sort('C', ascending=False)

In [5]: sort2 = sort1.groupby('A', sort=False).apply(f)

In [6]: sort2
         A         B      C
baz 5  baz -2.301539   True
    2  baz -0.528172  False
bar 1  bar -0.611756   True
    4  bar  0.865408  False
foo 3  foo -1.072969   True
    0  foo  1.624345  False

Clean up the df index by using reset_index with drop=True:

In [7]: sort2.reset_index(0, drop=True)
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

View array in Visual Studio debugger?

If you have a large array and only want to see a subsection of the array you can type this into the watch window;


to show a list of the 10 elements starting at ptr[100]. Beware that the displayed array subscripts will start at [0], so you will have to remember that ptr[0] is really ptr[100] and ptr[1] is ptr[101] etc.

How do I deal with corrupted Git object files?

You can use "find" for remove all files in the /objects directory with 0 in size with the command:

find .git/objects/ -size 0 -delete

Backup is recommended.

jQuery event is triggered twice

in my case, i was using the change command like this way

$(document).on('change', '.select-brand', function () { codes...});

and then i changed the way to

$('.select-brand').on('change', function () { codes...});

and it solved my problem.

Fully change package name including company domain

1) Open the project folder in Android Studio.
2) Select app folder -> Right click, and select refactor.
3) Click on move. It will ask to which package name type you own full package name and it will ask to create a new package yes create new automatically it ask for gradle to sync.

Chrome, Javascript, in new tab

Clear mini-solution $('<form action="" target="_blank"></form>').submit()

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

To get ride of all Unnamed columns, you can also use regex such as df.drop(df.filter(regex="Unname"),axis=1, inplace=True)

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

There is none. Alas, you have to type out the full type name.

Edit: 7 years after being posted, type inference for local variables (with var) was added in Java 10.

Edit: 6 years after being posted, to collect some of the comments from below:

  • The reason C# has the var keyword is because it's possible to have Types that have no name in .NET. Eg:

    var myData = new { a = 1, b = "2" };

    In this case, it would be impossible to give a proper type to myData. 6 years ago, this was impossible in Java (all Types had names, even if they were extremely verbose and unweildy). I do not know if this has changed in the mean time.

  • var is not the same as dynamic. variables are still 100% statically typed. This will not compile:

    var myString = "foo";
    myString = 3;
  • var is also useful when the type is obvious from context. For example:

    var currentUser = User.GetCurrent();

    I can say that in any code that I am responsible for, currentUser has a User or derived class in it. Obviously, if your implementation of User.GetCurrent return an int, then maybe this is a detriment to you.

  • This has nothing to do with var, but if you have weird inheritance hierarchies where you shadow methods with other methods (eg new public void DoAThing()), don't forget that non-virtual methods are affected by the Type they are cast as.

    I can't imagine a real world scenario where this is indicative of good design, but this may not work as you expect:

    class Foo {
        public void Non() {}
        public virtual void Virt() {}
    class Bar : Foo {
        public new void Non() {}
        public override void Virt() {}
    class Baz {
        public static Foo GetFoo() {
            return new Bar();
    var foo = Baz.GetFoo();
    foo.Non();  // <- Foo.Non, not Bar.Non
    foo.Virt(); // <- Bar.Virt
    var bar = (Bar)foo;
    bar.Non();  // <- Bar.Non, not Foo.Non
    bar.Virt(); // <- Still Bar.Virt

    As indicated, virtual methods are not affected by this.

  • No, there is no non-clumsy way to initialize a var without an actual variable.

    var foo1 = "bar";        //good
    var foo2;                //bad, what type?
    var foo3 = null;         //bad, null doesn't have a type
    var foo4 = default(var); //what?
    var foo5 = (object)null; //legal, but go home, you're drunk

    In this case, just do it the old fashioned way:

    object foo6;

PHP: How to use array_filter() to filter array keys?

Naive and ugly (but seems to be faster) solution?

Only tried this in php 7.3.11 but an ugly loop seems to execute in about a third of the time. Similar results on an array with a few hundred keys. Micro-optimization, probably not useful in RW, but found it surprising and interesting:

$time = microtime(true);
$i = 100000;
while($i) {
    $my_array = ['foo' => 1, 'hello' => 'world'];
    $allowed  = ['foo', 'bar'];
    $filtered = array_filter(
        function ($key) use ($allowed) {
            return in_array($key, $allowed);
echo microtime(true) - $time . ' on array_filter';

// 0.40600109100342 on array_filter
$time2 = microtime(true);
$i2 = 100000;
while($i2) {
    $my_array2 = ['foo' => 1, 'hello' => 'world'];
    $allowed2  = ['foo', 'bar'];
    $filtered2 = [];
    foreach ($my_array2 as $k => $v) {
        if (in_array($k, $allowed2)) $filtered2[$k] = $v;
echo microtime(true) - $time2 . ' on ugly loop';
// 0.15677785873413 on ugly loop

String formatting: % vs. .format vs. string literal

As a side note, you don't have to take a performance hit to use new style formatting with logging. You can pass any object to logging.debug,, etc. that implements the __str__ magic method. When the logging module has decided that it must emit your message object (whatever it is), it calls str(message_object) before doing so. So you could do something like this:

import logging

class NewStyleLogMessage(object):
    def __init__(self, message, *args, **kwargs):
        self.message = message
        self.args = args
        self.kwargs = kwargs

    def __str__(self):
        args = (i() if callable(i) else i for i in self.args)
        kwargs = dict((k, v() if callable(v) else v) for k, v in self.kwargs.items())

        return self.message.format(*args, **kwargs)

N = NewStyleLogMessage

# Neither one of these messages are formatted (or calculated) until they're
# needed

# Emits "Lazily formatted log entry: 123 foo" in log
logging.debug(N('Lazily formatted log entry: {0} {keyword}', 123, keyword='foo'))

def expensive_func():
    # Do something that takes a long time...
    return 'foo'

# Emits "Expensive log entry: foo" in log
logging.debug(N('Expensive log entry: {keyword}', keyword=expensive_func))

This is all described in the Python 3 documentation ( However, it will work with Python 2.6 as well (

One of the advantages of using this technique, other than the fact that it's formatting-style agnostic, is that it allows for lazy values e.g. the function expensive_func above. This provides a more elegant alternative to the advice being given in the Python docs here:

Why are primes important in cryptography?

To be a little more concrete about how RSA uses properties of prime numbers, the RSA algorithm depends critically upon Euler's Theorem, which states that for relatively prime numbers "a" and "N", a^e is congruent to 1 modulo N, where e is the Euler's totient function of N.

Where do primes come into that? To compute the Euler's totient function of N efficiently requires knowing the prime factorization of N. In the case of the RSA algorithm, where N = pq for some primes "p" and "q", then e = (p - 1)(q - 1) = N - p - q + 1. But without knowing p and q, computation of e is very difficult.

More abstractly, many crypotgraphic protocols use various trapdoor functions, functions which are easy to compute but difficult to invert. Number theory is a rich source of such trapdoor functions (such as multiplication of large prime numbers), and prime numbers are absolutely central to number theory.

Sort a two dimensional array based on one column

  1. install java8 jdk+jre

  2. use lamda expression to sort 2D array.


import java.util.Arrays;
import java.util.Comparator;

class SortString {

    public static void main(final String[] args) {
        final String[][] data = new String[][] {
                new String[] { "2009.07.25 20:24", "Message A" },
                new String[] { "2009.07.25 20:17", "Message G" },
                new String[] { "2009.07.25 20:25", "Message B" },
                new String[] { "2009.07.25 20:30", "Message D" },
                new String[] { "2009.07.25 20:01", "Message F" },
                new String[] { "2009.07.25 21:08", "Message E" },
                new String[] { "2009.07.25 19:54", "Message R" } 
        // this is applicable only in java 8 version.
        Arrays.sort(data, (String[] s1, String[] s2) -> s1[0].compareTo(s2[0]));

        // we can also use Comparator.comparing and point to Comparable value we want to use        
        // Arrays.sort(data, Comparator.comparing(row->row[0]));

        for (final String[] s : data) {
            System.out.println(s[0] + " " + s[1]);


2009.07.25 19:54 Message R
2009.07.25 20:01 Message F
2009.07.25 20:17 Message G
2009.07.25 20:24 Message A
2009.07.25 20:25 Message B
2009.07.25 20:30 Message D
2009.07.25 21:08 Message E

Escape curly brace '{' in String.Format

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

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

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

HTML Button : Navigate to Other Page - Different Approaches

I make a link. A link is a link. A link navigates to another page. That is what links are for and everybody understands that. So Method 3 is the only correct method in my book.

I wouldn't want my link to look like a button at all, and when I do, I still think functionality is more important than looks.

Buttons are less accessible, not only due to the need of Javascript, but also because tools for the visually impaired may not understand this Javascript enhanced button well.

Method 4 would work as well, but it is more a trick than a real functionality. You abuse a form to post 'nothing' to this other page. It's not clean.

Prevent overwriting a file using cmd if exist

Use the FULL path to the folder in your If Not Exist code. Then you won't even have to CD anymore:

If Not Exist "C:\Documents and Settings\John\Start Menu\Programs\SoftWareFolder\"

Find size and free space of the filesystem containing a given file

import os

def get_mount_point(pathname):
    "Get the mount point of the filesystem containing pathname"
    pathname= os.path.normcase(os.path.realpath(pathname))
    parent_device= path_device= os.stat(pathname).st_dev
    while parent_device == path_device:
        mount_point= pathname
        pathname= os.path.dirname(pathname)
        if pathname == mount_point: break
        parent_device= os.stat(pathname).st_dev
    return mount_point

def get_mounted_device(pathname):
    "Get the device mounted at pathname"
    # uses "/proc/mounts"
    pathname= os.path.normcase(pathname) # might be unnecessary here
        with open("/proc/mounts", "r") as ifp:
            for line in ifp:
                fields= line.rstrip('\n').split()
                # note that line above assumes that
                # no mount points contain whitespace
                if fields[1] == pathname:
                    return fields[0]
    except EnvironmentError:
    return None # explicit

def get_fs_freespace(pathname):
    "Get the free space of the filesystem containing pathname"
    stat= os.statvfs(pathname)
    # use f_bfree for superuser, or f_bavail if filesystem
    # has reserved space for superuser
    return stat.f_bfree*stat.f_bsize

Some sample pathnames on my computer:

path 'trash':
  mp /home /dev/sda4
  free 6413754368
path 'smov':
  mp /mnt/S /dev/sde
  free 86761562112
path '/usr/local/lib':
  mp / rootfs
  free 2184364032
path '/proc/self/cmdline':
  mp /proc proc
  free 0


if on Python =3.3, there's shutil.disk_usage(path) which returns a named tuple of (total, used, free) expressed in bytes.

Android: how to convert whole ImageView to Bitmap?

Just thinking out loud here (with admittedly little expertise working with graphics in Java) maybe something like this would work?:

ImageView iv = (ImageView)findViewById(;
Bitmap bitmap = Bitmap.createBitmap(iv.getWidth(), iv.getHeight(), Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);

Out of curiosity, what are you trying to accomplish? There may be a better way to achieve your goal than what you have in mind.

Unix command to find lines common in two files

rm file3.txt

cat file1.out | while read line1
        cat file2.out | while read line2
                if [[ $line1 == $line2 ]]; then
                        echo $line1 >>file3.out

This should do it.

How to compile without warnings being treated as errors?


CFLAGS=-Wno-error ./configure

Pass connection string to code-first DbContext

After reading the docs, I have to pass the name of the connection string instead:

var db = new NerdDinners("NerdDinnerDb");

How can I change the default credentials used to connect to Visual Studio Online (TFSPreview) when loading Visual Studio up?

You need to remove TFS credentials from Windows Vault to clear and force to ask new TFS credentials in Visual Studio

  1. Go to Control Panel (Start -> Control Panel).

  2. Click User Accounts ( or User Accounts and Family Safety->User Accounts in Windows 7 Machine)

  3. Click Credential Manager (or Manage your credentials)

  4. In Credential Manager page, you can see the two type of credentials

       i. Windows Credentials
       ii. Generic Credentials

5.Click on two credentials modify link, click the link Remove from vault to remove stored TFS credentials.

Now, When you login into Visual Studio you will be asked to give credentials to connect TFS.

Note: Don't forgot to uncheck the option Remember my credentials to force to ask credentials for every TFS connections.

Sample settings.xml

A standard Maven settings.xml file is as follows:

<settings xmlns="" xmlns:xsi=""







To access a proxy, you can find detailed information on the official Maven page here:

Maven-Settings - Settings

I hope it helps for someone.

How to start color picker on Mac OS?

You can call up the color picker from any Cocoa application (TextEdit, Mail, Keynote, Pages, etc.) by hitting Shift-Command-C

The following article explains more about using Mac OS's Color Picker.

eslint: error Parsing error: The keyword 'const' is reserved

I had this same problem with this part of my code:

const newComment = {
    dishId: dishId,
    rating: rating,
    author: author,
    comment: comment
}; = new Date().toISOString();

Same error, const is a reserved word.

The thing is, I made the .eslintrc.js from the link you gave in the update and still got the same error. Also, I get an parsing error in the .eslintrc.js: Unexpected token ':'.

Right in this part:

"env": {
"browser": true,
"node": true,
"es6": true


Android layout replacing a view with another view on run time

You could replace any view at any time.

int optionId = someExpression ? R.layout.option1 : R.layout.option2;

View C = findViewById(;
ViewGroup parent = (ViewGroup) C.getParent();
int index = parent.indexOfChild(C);
C = getLayoutInflater().inflate(optionId, parent, false);
parent.addView(C, index);

If you don't want to replace already existing View, but choose between option1/option2 at initialization time, then you could do this easier: set android:id for parent layout and then:

ViewGroup parent = (ViewGroup) findViewById(;
View C = getLayoutInflater().inflate(optionId, parent, false);
parent.addView(C, index);

You will have to set "index" to proper value depending on views structure. You could also use a ViewStub: add your C view as ViewStub and then:

ViewStub C = (ViewStub) findViewById(;

That way you won't have to worry about above "index" value if you will want to restructure your XML layout.

Append Char To String in C?

The Original poster didn't mean to write:

  char* str = "blablabla";


  char str[128] = "blablabla";

Now, adding a single character would seem more efficient than adding a whole string with strcat. Going the strcat way, you could:

  char tmpstr[2];
  tmpstr[0] = c;
  tmpstr[1] = 0;
  strcat (str, tmpstr);

but you can also easily write your own function (as several have done before me):

  void strcat_c (char *str, char c)
    for (;*str;str++); // note the terminating semicolon here. 
    *str++ = c; 
    *str++ = 0;

Generating 8-character only UUIDs

This is a similar way I'm using here to generate an unique error code, based on Anton Purin answer, but relying on the more appropriate org.apache.commons.text.RandomStringGenerator instead of the (once, not anymore) deprecated org.apache.commons.lang3.RandomStringUtils:

public class ErrorCodeGenerator implements Supplier<String> {

    private RandomStringGenerator errorCodeGenerator;

    public ErrorCodeGenerator() {
        errorCodeGenerator = new RandomStringGenerator.Builder()
                .withinRange('0', 'z')
                .filteredBy(t -> t >= '0' && t <= '9', t -> t >= 'A' && t <= 'Z', t -> t >= 'a' && t <= 'z')

    public String get() {
        return errorCodeGenerator.generate(8);


All advices about collision still apply, please be aware of them.

select count(*) from table of mysql in php

$result = mysql_query("SELECT COUNT(*) AS `count` FROM `Students`");
$row = mysql_fetch_assoc($result);
$count = $row['count'];

Try this code.

Difference between SurfaceView and View?

One of the main differences between surfaceview and view is that to refresh the screen for a normal view we have to call invalidate method from the same thread where the view is defined. But even if we call invalidate, the refreshing does not happen immediately. It occurs only after the next arrival of the VSYNC signal. VSYNC signal is a kernel generated signal which happens every 16.6 ms or this is also known as 60 frame per second. So if we want more control over the refreshing of the screen (for example for very fast moving animation), we should not use normal view class.

On the other hand in case of surfaceview, we can refresh the screen as fast as we want and we can do it from a background thread. So refreshing of the surfaceview really does not depend upon VSYNC, and this is very useful if we want to do high speed animation. I have few training videos and example application which explain all these things nicely. Please have a look at the following training videos.

How do I find the difference between two values without knowing which is larger?

This does not address the original question, but I thought I would expand on the answer zinturs gave. If you would like to determine the appropriately-signed distance between any two numbers, you could use a custom function like this:

import math

def distance(a, b):
    if (a == b):
        return 0
    elif (a < 0) and (b < 0) or (a > 0) and (b > 0):
        if (a < b):
            return (abs(abs(a) - abs(b)))
            return -(abs(abs(a) - abs(b)))
        return math.copysign((abs(a) + abs(b)),b)

print(distance(3,-5))  # -8

print(distance(-3,5))  #  8

print(distance(-3,-5)) #  2

print(distance(5,3))   # -2

print(distance(5,5))   #  0

print(distance(-5,3))  #  8

print(distance(5,-3))  # -8

Please share simpler or more pythonic approaches, if you have one.

javascript windows alert with redirect function

Alert will block the program flow so you can just write the following.

echo ("<script LANGUAGE='JavaScript'>
    window.alert('Succesfully Updated');

How can I view a git log of just one user's commits?

You can use either = or "space". For instance following two commands return the same

git log --author="Developer1"

git log --author "Developer1"

Python read in string from file and split it into values

Something like this - for each line read into string variable a:

>>> a = "123,456"
>>> b = a.split(",")
>>> b
['123', '456']
>>> c = [int(e) for e in b]
>>> c
[123, 456]
>>> x, y = c
>>> x
>>> y

Now you can do what is necessary with x and y as assigned, which are integers.

Converting strings to floats in a DataFrame

Here is an example

                            GHI             Temp  Power Day_Type
2016-03-15 06:00:00 -7.99999952505459e-7    18.3    0   NaN
2016-03-15 06:01:00 -7.99999952505459e-7    18.2    0   NaN
2016-03-15 06:02:00 -7.99999952505459e-7    18.3    0   NaN
2016-03-15 06:03:00 -7.99999952505459e-7    18.3    0   NaN
2016-03-15 06:04:00 -7.99999952505459e-7    18.3    0   NaN

but if this is all string was in my case... Convert the desired columns to floats:

df_inv_29['GHI'] = df_inv_29.GHI.astype(float)
df_inv_29['Temp'] = df_inv_29.Temp.astype(float)
df_inv_29['Power'] = df_inv_29.Power.astype(float)

Your dataframe will now have float values :-)

Getting content/message from HttpResponseMessage

You can use the GetStringAsync method:

var uri = new Uri("http://yoururlhere");
var response = await client.GetStringAsync(uri);

How can I change the date format in Java?

This is just Christopher Parker's answer adapted to use the new1 classes from Java 8:

final DateTimeFormatter OLD_FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy");
final DateTimeFormatter NEW_FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM/dd");

String oldString = "26/07/2017";
LocalDate date = LocalDate.parse(oldString, OLD_FORMATTER);
String newString = date.format(NEW_FORMATTER);

1 well, not that new anymore, Java 9 should be released soon.

Get loop count inside a Python FOR loop

Try using itertools.count([n])

How do you get the width and height of a multi-dimensional array?

// Two-dimensional GetLength example.
int[,] two = new int[5, 10];
Console.WriteLine(two.GetLength(0)); // Writes 5
Console.WriteLine(two.GetLength(1)); // Writes 10

How to disable manual input for JQuery UI Datepicker field?

I think you should add style="background:white;" to make looks like it is writable

<input type="text" size="23" name="dateMonthly" id="dateMonthly" readonly="readonly"   style="background:white;"/>

Import Google Play Services library in Android Studio






Linux Command History with date and time

Try this:

> HISTTIMEFORMAT="%d/%m/%y %T "

> history

You can adjust the format to your liking, of course.

How to merge every two lines into one from the command line?

There are more ways to kill a dog than hanging. [1]

awk '{key=$0; getline; print key ", " $0;}'

Put whatever delimiter you like inside the quotes.


  1. Originally "Plenty of ways to skin the cat", reverted to an older, potentially originating expression that also has nothing to do with pets.

How do I add images in laravel view?

You should store your images, css and JS files in a public directory. To create a link to any of them, use asset() helper:

{{ asset('img/myimage.png') }}

As alternative, you could use amazing Laravel Collective package for building forms and HTML elements, so your code will look like this:

{{ HTML::image('img/myimage.png', 'a picture') }}

sort files by date in PHP

This would get all files in path/to/files with an .swf extension into an array and then sort that array by the file's mtime

$files = glob('path/to/files/*.swf');
usort($files, function($a, $b) {
    return filemtime($b) - filemtime($a);

The above uses an Lambda function and requires PHP 5.3. Prior to 5.3, you would do

usort($files, create_function('$a,$b', 'return filemtime($b)-filemtime($a);'));

If you don't want to use an anonymous function, you can just as well define the callback as a regular function and pass the function name to usort instead.

With the resulting array, you would then iterate over the files like this:

foreach($files as $file){
    printf('<tr><td><input type="checkbox" name="box[]"></td>
            <td><a href="%1$s" target="_blank">%1$s</a></td>
            $file, // or basename($file) for just the filename w\out path
            date('F d Y, H:i:s', filemtime($file)));

Note that because you already called filemtime when sorting the files, there is no additional cost when calling it again in the foreach loop due to the stat cache.

Presto SQL - Converting a date string to date format

Converted DateID having date in Int format to date format: Presto Query

Select CAST(date_format(date_parse(cast(dateid as varchar(10)), '%Y%m%d'), '%Y/%m-%d') AS DATE)
limit 10;

How to change Toolbar Navigation and Overflow Menu icons (appcompat v7)?

if you want to change menu item icons, arrow icon (back/up), and 3 dots icon you can use android:tint

  <style name="ToolbarTheme" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:tint">@color/your_color</item>

How to get the cursor to change to the hand when hovering a <button> tag

Just add this style:

cursor: pointer;

The reason it's not happening by default is because most browsers reserve the pointer for links only (and maybe a couple other things I'm forgetting, but typically not <button>s).

More on the cursor property:

I usually apply this to <button> and <label> by default.

NOTE: I just caught this:

the button tags have an id of #more

It's very important that each element has it's own unique id, you cannot have duplicates. Use the class attribute instead, and change your selector from #more to .more. This is actually quite a common mistake that is the cause of many problems and questions asked here. The earlier you learn how to use id, the better.

Convert int (number) to string with leading zeros? (4 digits)

Use String.PadLeft like this:

var result = input.ToString().PadLeft(length, '0');

Is there a Google Voice API?

Well... These are PHP. There is an sms one from google here.

And github has one here.

Another sms one is here. However, this one has a lot more code, so it may take up more space.

C non-blocking keyboard input

The curses library can be used for this purpose. Of course, select() and signal handlers can be used too to a certain extent.

jQuery UI Dialog - missing close icon

I was facing same issue , In my case JQuery-ui.js version was 1.10.3, After referring jquery-ui-1.12.1.min.js close button started to visible.

How do I concatenate or merge arrays in Swift?

Swift 3.0

You can create a new array by adding together two existing arrays with compatible types with the addition operator (+). The new array's type is inferred from the type of the two array you add together,

let arr0 = Array(repeating: 1, count: 3) // [1, 1, 1]
let arr1 = Array(repeating: 2, count: 6)//[2, 2, 2, 2, 2, 2]
let arr2 = arr0 + arr1 //[1, 1, 1, 2, 2, 2, 2, 2, 2]

this is the right results of above codes.

Async always WaitingForActivation

this code seems to have address the issue for me. it comes for a streaming class, ergo some of the nomenclature.

''' <summary> Reference to the awaiting task. </summary>
''' <value> The awaiting task. </value>
Protected ReadOnly Property AwaitingTask As Threading.Tasks.Task

''' <summary> Reference to the Action task; this task status undergoes changes. </summary>
Protected ReadOnly Property ActionTask As Threading.Tasks.Task

''' <summary> Reference to the cancellation source. </summary>
Protected ReadOnly Property TaskCancellationSource As Threading.CancellationTokenSource

''' <summary> Starts the action task. </summary>
''' <param name="taskAction"> The action to stream the entities, which calls
'''                           <see cref="StreamEvents(Of T)(IEnumerable(Of T), IEnumerable(Of Date), Integer, String)"/>. </param>
''' <returns> The awaiting task. </returns>
Private Async Function AsyncAwaitTask(ByVal taskAction As Action) As Task
    Me._ActionTask = Task.Run(taskAction)
    Await Me.ActionTask '  Task.Run(streamEntitiesAction)
        Me.OnStreamTaskEnded(If(Me.ActionTask Is Nothing, TaskStatus.RanToCompletion, Me.ActionTask.Status))
    Catch ex As AggregateException
    End Try
End Function

''' <summary> Starts Streaming the events. </summary>
''' <exception cref="InvalidOperationException"> Thrown when the requested operation is invalid. </exception>
''' <param name="bucketKey">            The bucket key. </param>
''' <param name="timeout">              The timeout. </param>
''' <param name="streamEntitiesAction"> The action to stream the entities, which calls
'''                                     <see cref="StreamEvents(Of T)(IEnumerable(Of T), IEnumerable(Of Date), Integer, String)"/>. </param>
Public Overridable Sub StartStreamEvents(ByVal bucketKey As String, ByVal timeout As TimeSpan, ByVal streamEntitiesAction As Action)
    If Me.IsTaskActive Then
        Throw New InvalidOperationException($"Stream task is {Me.ActionTask.Status}")
        Me._TaskCancellationSource = New Threading.CancellationTokenSource
        Me.TaskCancellationSource.Token.Register(AddressOf Me.StreamTaskCanceled)
        ' the action class is created withing the Async/Await function
        Me._AwaitingTask = Me.AsyncAwaitTask(streamEntitiesAction)
    End If
End Sub

Excel VBA - select a dynamic cell range

If you want to select a variable range containing all headers cells:

Dim sht as WorkSheet
Set sht = This Workbook.Sheets("Data")

'Range(Cells(1,1),Cells(1,Columns.Count).End(xlToLeft)).Select '<<< NOT ROBUST

sht.Range(sht.Cells(1,1),sht.Cells(1,Columns.Count).End(xlToLeft)).Select long as there's no other content on that row.

EDIT: updated to stress that when using Range(Cells(...), Cells(...)) it's good practice to qualify both Range and Cells with a worksheet reference.

converting multiple columns from character to numeric format in r

If you're already using the tidyverse, there are a few solution depending on the exact situation.

Basic if you know it's all numbers and doesn't have NAs


# solution
dataset %>% mutate_if(is.character,as.numeric)

Test cases

df <- data.frame(
  x1 = c('1','2','3'),
  x2 = c('4','5','6'),
  x3 = c('1','a','x'), # vector with alpha characters
  x4 = c('1',NA,'6'), # numeric and NA
  x5 = c('1',NA,'x'), # alpha and NA
  stringsAsFactors = F)

# display starting structure
df %>% str()

Convert all character vectors to numeric (could fail if not numeric)

df %>%
  select(-x3) %>% # this removes the alpha column if all your character columns need converted to numeric
  mutate_if(is.character,as.numeric) %>%

Check if each column can be converted. This can be an anonymous function. It returns FALSE if there is a non-numeric or non-NA character somewhere. It also checks if it's a character vector to ignore factors. na.omit removes original NAs before creating "bad" NAs.

is_all_numeric <- function(x) {
  !any( & is.character(x)
df %>% 
  mutate_if(is_all_numeric,as.numeric) %>%

If you want to convert specific named columns, then mutate_at is better.

df %>% mutate_at('x1', as.numeric) %>% str()

top nav bar blocking top content of the page

Adding a padding like that is not enough if you're using responsive bootstrap. In this case when you resize your window you'll get a gap between top of the page and navbar. A proper solution looks like this:

body {
  padding-top: 60px;
@media (max-width: 979px) {
  body {
    padding-top: 0px;

How to convert JSON to a Ruby hash

I'm surprised nobody pointed out JSON's [] method, which makes it very easy and transparent to decode and encode from/to JSON.

If object is string-like, parse the string and return the parsed result as a Ruby data structure. Otherwise generate a JSON text from the Ruby data structure object and return it.

Consider this:

require 'json'

hash = {"val":"test","val1":"test1","val2":"test2"} # => {:val=>"test", :val1=>"test1", :val2=>"test2"}
str = JSON[hash] # => "{\"val\":\"test\",\"val1\":\"test1\",\"val2\":\"test2\"}"

str now contains the JSON encoded hash.

It's easy to reverse it using:

JSON[str] # => {"val"=>"test", "val1"=>"test1", "val2"=>"test2"}

Custom objects need to_s defined for the class, and inside it convert the object to a Hash then use to_json on it.

How can I use Html.Action?

You should look at the documentation for the Action method; it's explained well. For your case, this should work:

@Html.Action("GetOptions", new { pk="00", rk="00" });

The controllerName parameter will default to the controller from which Html.Action is being invoked. So if you're trying to invoke an action from another controller, you'll have to specify the controller name like so:

@Html.Action("GetOptions", "ControllerName", new { pk="00", rk="00" });

How do I extract Month and Year in a MySQL date and compare them?

There should also be a YEAR().

As for comparing, you could compare dates that are the first days of those years and months, or you could convert the year/month pair into a number suitable for comparison (i.e. bigger = later). (Exercise left to the reader. For hints, read about the ISO date format.)

Or you could use multiple comparisons (i.e. years first, then months).

How to take character input in java

I had the same struggle and I this is what I used:

} public static void main(String[] args) {

Scanner scan = new Scanner(;
System.out.print("Please enter the string: ");
String input =;
System.out.print("Please enter the required symbol: ");
String symbol =;        
char symbolChar = symbol.charAt(0);

This works just fine. The idea is to get from the string the only char in it.

Getting the folder name from a path

I used this code snippet to get the directory for a path when no filename is in the path:

for example "c:\tmp\test\visual";

string dir = @"c:\tmp\test\visual";
Console.WriteLine(dir.Replace(Path.GetDirectoryName(dir) + Path.DirectorySeparatorChar, ""));



How do I escape a reserved word in Oracle?

Oracle normally requires double-quotes to delimit the name of identifiers in SQL statements, e.g.

SELECT "MyColumn" AS "MyColAlias"
FROM "MyTable" "Alias"
WHERE "ThisCol" = 'That Value';

However, it graciously allows omitting the double-quotes, in which case it quietly converts the identifier to uppercase:

SELECT MyColumn AS MyColAlias
FROM MyTable Alias
WHERE ThisCol = 'That Value';

gets internally converted to something like:

WHERE "ALIAS" . "THISCOL" = 'That Value';

LINQ's Distinct() on a particular property


List<Person> pList = new List<Person>();
/* Fill list */

var result = pList.Where(p => p.Name != null).GroupBy(p => p.Id).Select(grp => grp.FirstOrDefault());

The where helps you filter the entries (could be more complex) and the groupby and select perform the distinct function.

Using Application context everywhere?

It is a good approach. I use it myself as well. I would only suggest to override onCreate to set the singleton instead of using a constructor.

And since you mentioned SQLiteOpenHelper: In onCreate () you can open the database as well.

Personally I think the documentation got it wrong in saying that There is normally no need to subclass Application. I think the opposite is true: You should always subclass Application.

socket.error:[errno 99] cannot assign requested address and namespace in python

Stripping things down to basics this is what you would want to test with:

import socket
server = socket.socket() 
server.bind(("", 6677)) 
client_socket, client_address = server.accept()
print(client_address, "has connected")
while 1==1:
    recvieved_data = client_socket.recv(1024)

This works assuming a few things:

  1. Your local IP address (on the server) is (This video shows you how)
  2. No other software is listening on port 6677

Also note the basic concept of IP addresses:

Try the following, open the start menu, in the "search" field type cmd and press enter. Once the black console opens up type ping and this should give you and IP address for google. This address is googles local IP and they bind to that and obviously you can not bind to an IP address owned by google.

With that in mind, you own your own set of IP addresses. First you have the local IP of the server, but then you have the local IP of your house. In the below picture is the local IP of the server which you can bind to. You still own but the problem is that it's owned by the Router and not your server. So even if you visit and that tells you that your IP is that is not the case because it can only see where you're coming from.. and you're accessing your internet from a router.

enter image description here

In order for your friends to access your server (which is bound to you need to forward port 6677 to and this is done in your router. Assuming you are behind one.

If you're in school there's other dilemmas and routers in the way most likely.

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

Compiling answers given by @adurdin and @User

Add followings to your info.plist & change with your corresponding domain name, you can add multiple domains as well:


You info.plist must looks like this:

enter image description here

Vue-router redirect on page not found (404)

I think you should be able to use a default route handler and redirect from there to a page outside the app, as detailed below:

const ROUTER_INSTANCE = new VueRouter({
    mode: "history",
    routes: [
        { path: "/", component: HomeComponent },
        // ... other routes ...
        // and finally the default route, when none of the above matches:
        { path: "*", component: PageNotFound }

In the above PageNotFound component definition, you can specify the actual redirect, that will take you out of the app entirely:

Vue.component("page-not-found", {
    template: "",
    created: function() {
        // Redirect outside the app using plain old javascript
        window.location.href = "/my-new-404-page.html";

You may do it either on created hook as shown above, or mounted hook also.

Please note:

  1. I have not verified the above. You need to build a production version of app, ensure that the above redirect happens. You cannot test this in vue-cli as it requires server side handling.

  2. Usually in single page apps, server sends out the same index.html along with app scripts for all route requests, especially if you have set <base href="/">. This will fail for your /404-page.html unless your server treats it as a special case and serves the static page.

Let me know if it works!

Update for Vue 3 onward:

You'll need to replace the '*' path property with '/:pathMatch(.*)*' if you're using Vue 3 as the old catch-all path of '*' is no longer supported. The route would then look something like this:

{ path: '/:pathMatch(.*)*', component: PathNotFound },

See the docs for more info on this update.

CodeIgniter Select Query

$query= $this->m_general->get('users' , array('id'=> $id ));
echo $query[''];

is ok ;)

How to do IF NOT EXISTS in SQLite

If you want to ignore the insertion of existing value, there must be a Key field in your Table. Just create a table With Primary Key Field Like:

CREATE TABLE IF NOT EXISTS TblUsers (UserId INTEGER PRIMARY KEY, UserName varchar(100), ContactName varchar(100),Password varchar(100));

And Then Insert Or Replace / Insert Or Ignore Query on the Table Like:

INSERT OR REPLACE INTO TblUsers (UserId, UserName, ContactName ,Password) VALUES('1','UserName','ContactName','Password');

It Will Not Let it Re-Enter The Existing Primary key Value... This Is how you can Check Whether a Value exists in the table or not.

getting the X/Y coordinates of a mouse click on an image with jQuery

note! there is a difference between e.clientX & e.clientY and e.pageX and e.pageY

try them both out and make sure you are using the proper one. clientX and clientY change based on scrolling position

How to send a POST request in Go?

You have mostly the right idea, it's just the sending of the form that is wrong. The form belongs in the body of the request.

req, err := http.NewRequest("POST", url, strings.NewReader(form.Encode()))

The name does not exist in the namespace error in XAML

VB.NET does not automatically add the Namespace information based on the folder structure as it does in C#. I think I am going through the same tutorial as you (Teach Yourself WPF in 24 Hours), and doing the same conversion to VB.

I found you have to manually add the Namespace information to Both the XAML Class and the XAML.VB code behind to be able to use the Namespaces as described in the book. Even then, VB doesn't automatically Assign the Namespace to the Assembly as it does in VB.

There is another article here that shows how to include this in your project templates so it does build the Namespace information automatically - Automatically add namespace when adding new item

How to set UICollectionViewCell Width and Height programmatically

Swift 5, Programmatic UICollectionView setting Cell width and height

// MARK: MyViewController

final class MyViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    private lazy var collectionViewLayout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        let spacing: CGFloat = 1
        let numOfColumns: CGFloat = 3
        let itemSize: CGFloat = (UIScreen.main.bounds.width - (numOfColumns - spacing) - 2) / 3
        layout.itemSize = CGSize(width: itemSize, height: itemSize)
        layout.minimumInteritemSpacing = spacing
        layout.minimumLineSpacing = spacing
        layout.sectionInset = UIEdgeInsets(top: spacing, left: spacing, bottom: spacing, right: spacing)
        return layout
    private lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: collectionViewLayout)
        collectionView.backgroundColor = .white
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        return collectionView
    override func viewDidLoad() {
    private func configureCollectionView() {
            collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
            collectionView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
            collectionView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)
        collectionView.register(PhotoCell.self, forCellWithReuseIdentifier: "PhotoCell")
    // MARK: UICollectionViewDataSource

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell
        cell.backgroundColor = .red
        return cell

// MARK: PhotoCell

final class PhotoCell: UICollectionViewCell {
    lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.layer.masksToBounds = true
        return imageView
    override init(frame: CGRect) {
        super.init(frame: frame)
    required init?(coder aDecoder: NSCoder) {
        fatalError("init?(coder:) not implemented")
    func setupViews() {
            topAnchor.constraint(equalTo: topAnchor),
            bottomAnchor.constraint(equalTo: bottomAnchor),
            leadingAnchor.constraint(equalTo: leadingAnchor),
            trailingAnchor.constraint(equalTo: trailingAnchor)

Classes vs. Functions

Before answering your question:

If you do not have a Person class, first you must consider whether you want to create a Person class. Do you plan to reuse the concept of a Person very often? If so, you should create a Person class. (You have access to this data in the form of a passed-in variable and you don't care about being messy and sloppy.)

To answer your question:

You have access to their birthyear, so in that case you likely have a Person class with a someperson.birthdate field. In that case, you have to ask yourself, is someperson.age a value that is reusable?

The answer is yes. We often care about age more than the birthdate, so if the birthdate is a field, age should definitely be a derived field. (A case where we would not do this: if we were calculating values like someperson.chanceIsFemale or someperson.positionToDisplayInGrid or other irrelevant values, we would not extend the Person class; you just ask yourself, "Would another program care about the fields I am thinking of extending the class with?" The answer to that question will determine if you extend the original class, or make a function (or your own class like PersonAnalysisData or something).)

Differences between Oracle JDK and OpenJDK

The Oracle and OpenJDK JVMs are the same and have the same GC features (as of the latest versions 10+). Prior to Oracle managing the OpenJDK JVM there were concrete differences that made that old Openjdk JVM almost unusable in many environments. The JVMs are now the same.

The JDKs which include the JVM as part of the Kit, differ by licensing, release and maintenance schedule, and the software libraries included in the JDK. Crucial differences to me also mean things that would make code not run if not present. Not only licensing.

diff --brief -r openjdk oraclejdk

Crucially the following files are missing in addition to a bunch of others on the linux JDK (So if you 'claimed' that code didn't work on OpenJDK and did so on OracleJDK while you were using javafx then you were correct):

Only in jdk-10.0.1/bin: javapackager
Only in jdk-10.0.1/bin: javaws
Only in jdk-10.0.1/bin: jcontrol
Only in jdk-10.0.1/bin: jmc
Only in jdk-10.0.1/bin: jweblauncher
Only in jdk-10.0.1/lib: ant-javafx.jar
Only in jdk-10.0.1/lib: deploy
Only in jdk-10.0.1/lib: deploy.jar
Only in jdk-10.0.1/lib: desktop
Only in jdk-10.0.1/lib: fontconfig.bfc
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib: fontconfig.RedHat.6.bfc
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib: fontconfig.SuSE.11.bfc
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib: fonts
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib: javafx-swt.jar
Only in jdk-10.0.1/lib: java.jnlp.jar
Only in jdk-10.0.1/lib: javaws.jar
Only in jdk-10.0.1/lib: jdk.deploy.jar
Only in jdk-10.0.1/lib: jdk.javaws.jar
Only in jdk-10.0.1/lib: jdk.plugin.jar
Only in jdk-10.0.1/lib: jfr
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib:
Only in jdk-10.0.1/lib: locale
Only in jdk-10.0.1/lib: missioncontrol
Only in jdk-10.0.1/lib: oblique-fonts
Only in jdk-10.0.1/lib: plugin.jar
Only in jdk-10.0.1/lib: plugin-legacy.jar
Only in jdk-10.0.1/lib/security: blacklist
Only in jdk-10.0.1/lib/security: public_suffix_list.dat
Only in jdk-10.0.1/lib/security: trusted.libraries
Only in openjdk-10.0.1: man`

How to monitor SQL Server table changes by using c#?

Generally, you'd use Service Broker

That is trigger -> queue -> application(s)

Edit, after seeing other answers:

FYI: "Query Notifications" is built on Service broker


More links

Get Time from Getdate()

You will be able to get the time using below query:

select left((convert(time(0), GETDATE ())),5)

Generate Controller and Model

Thank you @user1909426, I can found solution by php artisan list it will list all command that was used on L4. It can create controller only not Model. I follow this command to generate controller.

php artisan controller:make [Name]Controller

On Laravel 5, the command has changed:

php artisan make:controller [Name]Controller

Note: [Name] name of controller

installing apache: no VCRUNTIME140.dll

Be sure you have C++ Redistributable for Visual Studio 2015 RC. Try to download the last version:

Obs: Credit to parsecer

how to add button click event in android studio

Start your OnClickListener, but when you get to the first set up parenthesis, type new, then View, and press enter. Should look like this when you're done:

Button btn1 = (Button)findViewById(;

btn1.setOnClickListener(new View.OnClickListener() {            
    public void onClick(View v) {
//your stuff here.

How to order citations by appearance using BibTeX?

with unsrt the problem is the format. use \bibliographystyle{ieeetr} to get refences in order of citation in document.

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

your issue will be resolved by properly defining cascading depedencies or by saving the referenced entities before saving the entity that references. Defining cascading is really tricky to get right because of all the subtle variations in how they are used.

Here is how you can define cascades:

public class Userrole implements Serializable {

    private static final long serialVersionUID = 1L;

    private long userroleid;

    private Timestamp createddate;

    private Timestamp deleteddate;

    private String isactive;

    //bi-directional many-to-one association to Role
    @ManyToOne(cascade = CascadeType.ALL)
    private Role role;

    //bi-directional many-to-one association to User
    @ManyToOne(cascade = CascadeType.ALL)
    private User user;


In this scenario, every time you save, update, delete, etc Userrole, the assocaited Role and User will also be saved, updated...

Again, if your use case demands that you do not modify User or Role when updating Userrole, then simply save User or Role before modifying Userrole

Additionally, bidirectional relationships have a one-way ownership. In this case, User owns Bloodgroup. Therefore, cascades will only proceed from User -> Bloodgroup. Again, you need to save User into the database (attach it or make it non-transient) in order to associate it with Bloodgroup.

HTML5 Canvas Resize (Downscale) Image High Quality?

context.scale(xScale, yScale)

<canvas id="c"></canvas>
<img id="i" />

var i = document.getElementById('i');

i.onload = function(){
    var width = this.naturalWidth,
        height = this.naturalHeight,
        canvas = document.getElementById('c'),
        ctx = canvas.getContext('2d');

    canvas.width = Math.floor(width / 2);
    canvas.height = Math.floor(height / 2);

    ctx.scale(0.5, 0.5);
    ctx.drawImage(this, 0, 0);

    // restore original 1x1 scale
    ctx.scale(2, 2);

i.src = '';

Select multiple elements from a list

mylist[c(5,7,9)] should do it.

You want the sublists returned as sublists of the result list; you don't use [[]] (or rather, the function is [[) for that -- as Dason mentions in comments, [[ grabs the element.

How many socket connections can a web server handle?

To add my two cents to the conversation a process can have simultaneously open a number of sockets connected equal to this number (in Linux type sytems) /proc/sys/net/core/somaxconn

cat /proc/sys/net/core/somaxconn

This number can be modified on the fly (only by root user of course)

echo 1024 > /proc/sys/net/core/somaxconn

But entirely depends on the server process, the hardware of the machine and the network, the real number of sockets that can be connected before crashing the system

get one item from an array of name,value JSON

Arrays are normally accessed via numeric indexes, so in your example arr[0] == {name:"k1", value:"abc"}. If you know that the name property of each object will be unique you can store them in an object instead of an array, as follows:

var obj = {};
obj["k1"] = "abc";
obj["k2"] = "hi";
obj["k3"] = "oa";

alert(obj["k2"]); // displays "hi"

If you actually want an array of objects like in your post you can loop through the array and return when you find an element with an object having the property you want:

function findElement(arr, propName, propValue) {
  for (var i=0; i < arr.length; i++)
    if (arr[i][propName] == propValue)
      return arr[i];

  // will return undefined if not found; you could return a default instead

// Using the array from the question
var x = findElement(arr, "name", "k2"); // x is {"name":"k2", "value":"hi"}
alert(x["value"]); // displays "hi"

var y = findElement(arr, "name", "k9"); // y is undefined
alert(y["value"]); // error because y is undefined

alert(findElement(arr, "name", "k2")["value"]); // displays "hi";

alert(findElement(arr, "name", "zzz")["value"]); // gives an error because the function returned undefined which won't have a "value" property

What is the difference between typeof and instanceof and when should one be used vs. the other?


typeof is faster than instanceof in situations where both are applicable.

Depending on your engine, the performance difference in favor of typeof could be around 20%. (Your mileage may vary)

Here is a benchmark testing for Array:

var subject = new Array();
var iterations = 10000000;

var goBenchmark = function(callback, iterations) {
    var start =;
    for (i=0; i < iterations; i++) { var foo = callback(); }
    var end =;
    var seconds = parseFloat((end-start)/1000).toFixed(2);
    console.log(" took: "+ seconds +" seconds.");
    return seconds;

// Testing instanceof
var iot = goBenchmark(function instanceofTest(){
     (subject instanceof Array);
}, iterations);

// Testing typeof
var tot = goBenchmark(function typeofTest(){
     (typeof subject == "object");
}, iterations);

var r = new Array(iot,tot).sort();
console.log("Performance ratio is: "+ parseFloat(r[1]/r[0]).toFixed(3));


instanceofTest took: 9.98 seconds.
typeofTest took: 8.33 seconds.
Performance ratio is: 1.198

Anaconda Installed but Cannot Launch Navigator

activate the virtual env with command:

 conda activate base

run anacond anavigator


npm install private github repositories by dependency in package.json

Since Git uses curl under the hood, you can use ~/.netrc file with the credentials. For GitHub it would look something like this:

  login <github username>
  password <password OR github access token>

If you choose to use access tokens, it can be generated from:

Settings -> Developer settings -> Personal access tokens

This should also work if you are using Github Enterprise in your own corporation. just put your enterprise github url in the machine field.

Update Top 1 record in table sql server

It also works well ...

Update t
Set t.TIMESTAMP2 = '2013-12-12 15:40:31.593'
    Select Top 1 TIMESTAMP2
    From TX_Master_PCBA
    Where SERIAL_NO IN ('0500030309')
) t

POST request not allowed - 405 Not Allowed - nginx, even with headers included

I had similiar issue but only with Chrome, Firefox was working. I noticed that Chrome was adding an Origin parameter in the header request.

So in my nginx.conf I added the parameter to avoid it under location/ block

proxy_set_header Origin "";

Difference between links and depends_on in docker_compose.yml

The post needs an update after the links option is deprecated.

Basically, links is no longer needed because its main purpose, making container reachable by another by adding environment variable, is included implicitly with network. When containers are placed in the same network, they are reachable by each other using their container name and other alias as host.

For docker run, --link is also deprecated and should be replaced by a custom network.

docker network create mynet
docker run -d --net mynet --name container1 my_image
docker run -it --net mynet --name container1 another_image

depends_on expresses start order (and implicitly image pulling order), which was a good side effect of links.

How to use onBlur event on Angular2?

you can use directly (blur) event in input tag.

   <input [value] = "" (blur) = "result = $" placeholder="Type Something">

and you will get output in "result"

CSS body background image fixed to full screen even when zooming in/out

I've used these techniques before and they both work well. If you read the pros/cons of each you can decide which is right for your site.

Alternatively you could use the full size background image jQuery plugin if you want to get away from the bugs in the above.

How to view file history in Git?

Use git log to view the commit history. Each commit has an associated revision specifier that is a hash key (e.g. 14b8d0982044b0c49f7a855e396206ee65c0e787 and b410ad4619d296f9d37f0db3d0ff5b9066838b39). To view the difference between two different commits, use git diff with the first few characters of the revision specifiers of both commits, like so:

# diff between commits 14b8... and b410...
git diff 14b8..b410
# only include diff of specified files
git diff 14b8..b410 path/to/file/a path/to/file/b

If you want to get an overview over all the differences that happened from commit to commit, use git log or git whatchanged with the patch option:

# include patch displays in the commit history
git log -p
git whatchanged -p
# only get history of those commits that touch specified paths
git log path/a path/b
git whatchanged path/c path/d

Disabling Chrome Autofill

Finally I think I came with a decent solution. Understanding better how the dropdown works with Chrome helped :) Basically, the dropdown will be displayed when you focus the input and when you generate a mouse down event when you are typing an entry which matches with what Chrome has in memory. Keeping that in mind, and that Chrome does it for certain inputs when they have default names like "name", "email", etc. then we just need to remove the name when the dropdown is going to be displayed and add it back after :) I wanted to use a solution which can make it work just by adding the attribute autocomplete off. I thought it made sense. This is the code:

Solution 1

jQuery('body').on('mousedown','[name="name"][autocomplete="off"], [name="email"][autocomplete="off"]',function(e){
    if(typeof this.currentName =="undefined")


Solution 2 (My Favourite One)

The solution I described above will remove the name of the input until we remove the focus (blur), in that moment it will put the original name back. But might happen that we are interested on having access to the input through its name attribute while we are typing. Which means that we need to put the name back right after each input. This solution, basically is based on the first solution. In this case, we will add the name on key down, and put it back on keyup. I think this is more neat for compatibility with what the "autocomplete off" behaviour should be. Anyway this is the code:

jQuery('body').on('mousedown keydown','[name="name"][autocomplete="off"], [name="email"][autocomplete="off"]',function(e){
    if(typeof this.currentName =="undefined")
jQuery('body').on('blur keyup','[autocomplete="off"]',function(e){
    if(typeof this.currentName !="undefined")

Please notice that for Solution 1 and 2, I just took the cases where the input name is "name" and "email". For any other case where this attribute makes Chrome generate the dropdown you will have to add it in the selector for the mouse down event.

Solution 3

This solution is a lot more messy. I did not realize that the behaviour we are trying to correct is just based on those inputs with a specific name like "name, email, etc". The approach of this solution was for that case that Chrome display for other names that we don't know a priori. It would be a very generic solution. I do not like as much as the other 2, basically because there could be a small flicker when we press on the delete key. I will explain that bellow.

I found out that the dropdown was appearing after a second click on the input but not on the first click when you focus the first time on the input. I bind a "mousedown" event for all this elements where the handler basically detect if it is already focused on the input and in case it detects another "mouse down", force a .blur() and then .focus() after, preventing the dropdown on the second click once it is focused. I hope, it is clear, just in case here is the code that I used:

    if(jQuery(this).is(':focus')) {

In the other hand, in order to prevent the dropdown while you are typing in case it matches with Chrome suggestions... This is a little bit tricky. I just decided to replace the default behaviour of an input while user types. The dropdown evaluates the input on mouse down, so I prevent the default behaviour for alphanumerics, space, etc. The only problem is with Command,Ctrl and delete. For this case I had to bind also an event on mouse up. It allows the default behaviour in the first two cases so you can make copy, and paste, or select all. In the case of the delete, I have to allow the default behaviour, but if after deleting a character the input matches with Chrome suggestions, then again it was showing the dropdown. For this case I had to use the same trick of blur and focus. The only inconvenience I found on this is that since we are cancelling the behaviour on keyup, and chrome tries to show it on keydown, there is a small flicker. Anyway, this is the best I could do. Probably it will require for filtering of characters at one point. I just added the conditions made more sense for now. This is the second part of the code:

    var ctrlKey = 17,cmKey = 91;
    var charCode = e.which || e.keyCode;

    if(charCode!=16 && this.commandDown != true && this.ctrlDown != true && ((charCode>47 && charCode<58)||(charCode>64 && charCode<91)||(charCode>96 && charCode<123)||charCode==0 || charCode==32)){ 
        var charStr = String.fromCharCode(charCode);
            charStr = charStr.toLowerCase(charStr);
        $(this).val($(this).val() + charStr);
        if (charCode == cmKey) this.commandDown = true;
        if (charCode == ctrlKey) this.ctrlDown = true;
    var allowed=[8];//Delete
    var ctrlKey = 17,cmKey = 91;
    var charCode = e.which || e.keyCode;

    if (charCode == cmKey) {this.commandDown = false};
    if (charCode == ctrlKey) {this.ctrlDown = false};
    if(allowed.indexOf(charCode)>=0 || (this.commandDown!=false && this.ctrlDown!=false)){

As I said this solution is much more messy. It was the first one I used until I realized that the dropdown just appeared for certain input names.

Sorry for writing so much, I just wanted to be sure everything was clear. I hope it helps.

Change bootstrap navbar collapse breakpoint without using LESS

This is what did the trick for me:

@media only screen and (min-width:769px) and (max-width:1000px){
.navbar-collapse.collapse {
    display: none !important;
} {
    display: block !important;
.navbar-header .collapse, .navbar-toggle {
    display:block !important;

Check element exists in array

You may be able to use the built-in function dir() to produce similar behavior to PHP's isset(), something like:

if 'foo' in dir():  # returns False, foo is not defined yet.

foo = 'b'

if 'foo' in dir():  # returns True, foo is now defined and in scope.

dir() returns a list of the names in the current scope, more information can be found here:

Flask SQLAlchemy query, specify column names

You can use Query.values, Query.values

session.query(SomeModel).values('id', 'user')

git diff between two different files

Specify the paths explicitly:

git diff HEAD:full/path/to/foo full/path/to/bar

Check out the --find-renames option in the git-diff docs.

Credit: twaggs.

How does a hash table work?

Here's another way to look at it.

I assume you understand the concept of an array A. That's something that supports the operation of indexing, where you can get to the Ith element, A[I], in one step, no matter how large A is.

So, for example, if you want to store information about a group of people who all happen to have different ages, a simple way would be to have an array that is large enough, and use each person's age as an index into the array. Thay way, you could have one-step access to any person's information.

But of course there could be more than one person with the same age, so what you put in the array at each entry is a list of all the people who have that age. So you can get to an individual person's information in one step plus a little bit of search in that list (called a "bucket"). It only slows down if there are so many people that the buckets get big. Then you need a larger array, and some other way to get more identifying information about the person, like the first few letters of their surname, instead of using age.

That's the basic idea. Instead of using age, any function of the person that produces a good spread of values can be used. That's the hash function. Like you could take every third bit of the ASCII representation of the person's name, scrambled in some order. All that matters is that you don't want too many people to hash to the same bucket, because the speed depends on the buckets remaining small.

Initializing a static std::map<int, int> in C++

If you are stuck with C++98 and don't want to use boost, here there is the solution I use when I need to initialize a static map:

typedef std::pair< int, char > elemPair_t;
elemPair_t elemPairs[] = 
    elemPair_t( 1, 'a'), 
    elemPair_t( 3, 'b' ), 
    elemPair_t( 5, 'c' ), 
    elemPair_t( 7, 'd' )

const std::map< int, char > myMap( &elemPairs[ 0 ], &elemPairs[ sizeof( elemPairs ) / sizeof( elemPairs[ 0 ] ) ] );

IIS - 401.3 - Unauthorized

  1. Create a new Site, Right Click on Sites folder then click add Site
  2. Enter the site name.
  3. Select physical path
  4. Select Ip Address
  5. Change Port
  6. Click OK
  7. Go to Application Pools
  8. Select the site pool
  9. Right-click the click Advance Settings
  10. Change the .Net CLR Version to "No Manage Code"
  11. Change the Identity to "ApplicationPoolIdentity"
  12. Go to Site home page then click "Authentication"
  13. Right-click to AnonymousAuthentication then click "Edit"
  14. Select Application Pool Identity
  15. Click ok
  16. boom!

for routes add a web.config

                <rule name="React Routes" stopProcessing="true">
                    <match url=".*" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                        <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
                    <action type="Rewrite" url="/" />

Using union and order by clause in mysql

I got this working on a join plus union.

 FROM table1, table2, foo1, table5
 WHERE table5.somerecord = table1.column1
 ORDER BY table1.column1 ASC, table1.column2 DESC


    ... Another complex query as above

ORDER BY column1 DESC, column2 ASC

How to create an array from a CSV file using PHP and the fgetcsv function

Try this code:

function readCsv($file)
    if (($handle = fopen($file, 'r')) !== FALSE) {
        while (($lineArray = fgetcsv($handle, 4000)) !== FALSE) {

How to write UTF-8 in a CSV file

It's very simple for Python 3.x (docs).

import csv

with open('output_file_name', 'w', newline='', encoding='utf-8') as csv_file:
    writer = csv.writer(csv_file, delimiter=';')

For Python 2.x, look here.

How to clear an EditText on click?

For me the easiest way... Create an public EditText, for Example "myEditText1"

public EditText myEditText1;

Then, connect it with the EditText which should get cleared

myEditText1 = (EditText) findViewById(;

After that, create an void which reacts to an click to the EditText an let it clear the Text inside it when its Focused, for Example

        void textGone(){
            if (myEditText1.isFocused()){


Hope i could help you, Have a nice Day everyone

How to add not null constraint to existing column in MySQL

Just use an ALTER TABLE... MODIFY... query and add NOT NULL into your existing column definition. For example:


A word of caution: you need to specify the full column definition again when using a MODIFY query. If your column has, for example, a DEFAULT value, or a column comment, you need to specify it in the MODIFY statement along with the data type and the NOT NULL, or it will be lost. The safest practice to guard against such mishaps is to copy the column definition from the output of a SHOW CREATE TABLE YourTable query, modify it to include the NOT NULL constraint, and paste it into your ALTER TABLE... MODIFY... query.

How to detect control+click in Javascript from an onclick div attribute?

When there is a mouse click ctrlKey is event attribute which can be accessed as e.ctrlKey. Look down for example

    //if ctrl key is pressed
    // if ctrl key is not pressed


Formatting MM/DD/YYYY dates in textbox in VBA

I never suggest using Textboxes or Inputboxes to accept dates. So many things can go wrong. I cannot even suggest using the Calendar Control or the Date Picker as for that you need to register the mscal.ocx or mscomct2.ocx and that is very painful as they are not freely distributable files.

Here is what I recommend. You can use this custom made calendar to accept dates from the user


  1. You don't have to worry about user inputting wrong info
  2. You don't have to worry user pasting in the textbox
  3. You don't have to worry about writing any major code
  4. Attractive GUI
  5. Can be easily incorporated in your application
  6. Doesn't use any controls for which you need to reference any libraries like mscal.ocx or mscomct2.ocx


Ummm...Ummm... Can't think of any...

HOW TO USE IT (File missing from my dropbox. Please refer to the bottom of the post for an upgraded version of the calendar)

  1. Download the Userform1.frm and Userform1.frx from here.
  2. In your VBA, simply import Userform1.frm as shown in the image below.

Importing the form

enter image description here


You can call it in any procedure. For example

Sub Sample()
End Sub


enter image description here

NOTE: You may also want to see Taking Calendar to new level

Double precision floating values in Python?

For some applications you can use Fraction instead of floating-point numbers.

>>> from fractions import Fraction
>>> Fraction(1, 3**54)
Fraction(1, 58149737003040059690390169)

(For other applications, there's decimal, as suggested out by the other responses.)

How to work offline with TFS

If the code has already been checked out by the user that if offline and they have the latest version on their local hd, then they just need to browse to the solution location and open the solution by double clicking sln file. The solution will open in disconnected mode.

Table with table-layout: fixed; and how to make one column wider

Are you creating a very large table (hundreds of rows and columns)? If so, table-layout: fixed; is a good idea, as the browser only needs to read the first row in order to compute and render the entire table, so it loads faster.

But if not, I would suggest dumping table-layout: fixed; and changing your css as follows:

table th, table td{
border: 1px solid #000;
width:20px;  //or something similar   

table td.wideRow, table th.wideRow{
width: 300px;

In the shell, what does " 2>&1 " mean?

Provided that /foo does not exist on your system and /tmp does…

$ ls -l /tmp /foo

will print the contents of /tmp and print an error message for /foo

$ ls -l /tmp /foo > /dev/null

will send the contents of /tmp to /dev/null and print an error message for /foo

$ ls -l /tmp /foo 1> /dev/null

will do exactly the same (note the 1)

$ ls -l /tmp /foo 2> /dev/null

will print the contents of /tmp and send the error message to /dev/null

$ ls -l /tmp /foo 1> /dev/null 2> /dev/null

will send both the listing as well as the error message to /dev/null

$ ls -l /tmp /foo > /dev/null 2> &1

is shorthand

How to create a property for a List<T>

T must be defined within the scope in which you are working. Therefore, what you have posted will work if your class is generic on T:

public class MyClass<T>
    private List<T> newList;

    public List<T> NewList
        get{return newList;}
        set{newList = value;}

Otherwise, you have to use a defined type.

EDIT: Per @lKashef's request, following is how to have a List property:

private List<int> newList;

public List<int> NewList
    get{return newList;}
    set{newList = value;}

This can go within a non-generic class.

Edit 2: In response to your second question (in your edit), I would not recommend using a list for this type of data handling (if I am understanding you correctly). I would put the user settings in their own class (or struct, if you wish) and have a property of this type on your original class:

public class UserSettings
 string FirstName { get; set; }
 string LastName { get; set; }
 // etc.

public class MyClass
 string MyClassProperty1 { get; set; }
 // etc.

 UserSettings MySettings { get; set; }

This way, you have named properties that you can reference instead of an arbitrary index in a list. For example, you can reference MySettings.FirstName as opposed to MySettingsList[0].

Let me know if you have any further questions.

EDIT 3: For the question in the comments, your property would be like this:

public class MyClass
    public List<KeyValuePair<string, string>> MySettings { get; set; } 

EDIT 4: Based on the question's edit 2, following is how I would use this:

public class MyClass
    // note that this type of property declaration is called an "Automatic Property" and
    // it means the same thing as you had written (the private backing variable is used behind the scenes, but you don't see it)
    public List<KeyValuePair<string, string> MySettings { get; set; } 

public class MyConsumingClass
    public void MyMethod
        MyClass myClass = new MyClass();
        myClass.MySettings = new List<KeyValuePair<string, string>>();
        myClass.MySettings.Add(new KeyValuePair<string, string>("SomeKeyValue", "SomeValue"));

        // etc.

You mentioned that "the property still won't appear in the object's instance," and I am not sure what you mean. Does this property not appear in IntelliSense? Are you sure that you have created an instance of MyClass (like myClass.MySettings above), or are you trying to access it like a static property (like MyClass.MySettings)?

Regular expression containing one word or another

You can use a single group for seconds/minutes. The following expression may suit your needs:


Online demo

Change the maximum upload file size

With WAMP it's all pretty easy

WAMP Icon > PHP > PHP Settings > upload_max_filesize = nM > n = (2M, 4M, 8M, 16M, 32M, 64M, 128M, 256M, 512M, or Choose (custom)).

Service(s) reload automatically.

But, if you truly have no access to the server, you might want to explore writing a chunking API.

Bootstrap 3 grid with no gap

Another option would be to create your own special CSS class for whenever you want to apply the "gutterless" columns..


<div class="container">
    <div class="row no-gutter">
        <div class="col-6 col-sm-6 col-lg-6">Col 1</div>
        <div class="col-6 col-sm-6 col-lg-6">Col 2</div>


.no-gutter [class*="-6"] {


git undo all uncommitted or unsaved changes

there is also git stash - which "stashes" your local changes and can be reapplied at a later time or dropped if is no longer required

more info on stashing

How can I implement a tree in Python?

Python doesn't have the quite the extensive range of "built-in" data structures as Java does. However, because Python is dynamic, a general tree is easy to create. For example, a binary tree might be:

class Tree:
    def __init__(self):
        self.left = None
        self.right = None = None

You can use it like this:

root = Tree() = "root"
root.left = Tree() = "left"
root.right = Tree() = "right"

If you need an arbitrary number of children per node, then use a list of children:

class Tree:
    def __init__(self, data):
        self.children = [] = data

left = Tree("left")
middle = Tree("middle")
right = Tree("right")
root = Tree("root")
root.children = [left, middle, right]

Random shuffling of an array

The most simple solution for this Random Shuffling in an Array.

String location[] = {"delhi","banglore","mathura","lucknow","chandigarh","mumbai"};
int index;
String temp;
Random random = new Random();
for(int i=1;i<location.length;i++)
    index = random.nextInt(i+1);
    temp = location[index];
    location[index] = location[i];
    location[i] = temp;
    System.out.println("Location Based On Random Values :"+location[i]);

What is the difference between POST and GET?

With POST you can also do multipart mime encoding which means you can attach files as well. Also if you are using post variables across navigation of pages, the user will get a warning asking if they want to resubmit the post parameter. Typically they look the same in an HTTP request, but you should just stick to POST if you need to "POST" something TO a server and "GET" if you need to GET something FROM a server as that's the way they were intended.

Bootstrap 3 Align Text To Bottom of Div

You can do this:


#container {

#container h3{

Then in HTML:

<div class="row">
    <div class="col-sm-6">
        <img src="//" alt="Logo" />
    <div id="container" class="col-sm-6">
        <h3>Some Text</h3>

EDIT: add the <

JQuery window scrolling event?

Check if the user has scrolled past the header ad, then display the footer ad.

if($(your header ad).position().top < 0) { $(your footer ad).show() }

Am I correct at what you are looking for?

How to automatically redirect HTTP to HTTPS on Apache servers?

I have actually followed this example and it worked for me :)

NameVirtualHost *:80
<VirtualHost *:80>
   Redirect permanent /

<VirtualHost _default_:443>
  DocumentRoot /usr/local/apache2/htdocs
  SSLEngine On
 # etc...

Then do:

/etc/init.d/httpd restart

How to efficiently count the number of keys/properties of an object in JavaScript?

To do this in any ES5-compatible environment, such as Node, Chrome, IE 9+, Firefox 4+, or Safari 5+:


How can I check for NaN values?

It seems that checking if it's equal to itself


is the fastest.

import pandas as pd 
import numpy as np 
import math 

x = float('nan')

%timeit x!=x                                                                                                                                                                                                                        
44.8 ns ± 0.152 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

%timeit math.isnan(x)                                                                                                                                                                                                               
94.2 ns ± 0.955 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

%timeit pd.isna(x) 
281 ns ± 5.48 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit np.isnan(x)                                                                                                                                                                                                                 
1.38 µs ± 15.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Description Box using "onmouseover"

The CSS Tooltip allows you to format the popup as you like as any div section! And no Javascript needed.

mySQL Error 1040: Too Many Connection

you need check your all connection. Then try to close it one by one. it maybe caused by one of your connection.

I have similar case, the root cause come from my monitoring server. So when I closed it, it works.

how to use sqltransaction in c#

First you don't need a transaction since you are just querying select statements and since they are both select statement you can just combine them into one query separated by space and use Dataset to get the all the tables retrieved. Its better this way since you made only one transaction to the database because database transactions are expensive hence your code is faster. Second of you really have to use a transaction, just assign the transaction to the SqlCommand like

sqlCommand.Transaction = transaction;

And also just use one SqlCommand don't declare more than one, since variables consume space and we are also on the topic of making your code more efficient, do that by assigning commandText to different query string and executing them like

sqlCommand.CommandText = "select * from table1";
sqlCommand.CommandText = "select * from table2";

CSV in Python adding an extra carriage return, on Windows

In Python 3 (I haven't tried this in Python 2), you can also simply do

with open('output.csv','w',newline='') as f:

as per documentation.

More on this in the doc's footnote:

If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling.

Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell

In regards to Python optimization, in addition to using PyPy (for pretty impressive speed-ups with zero change to your code), you could use PyPy's translation toolchain to compile an RPython-compliant version, or Cython to build an extension module, both of which are faster than the C version in my testing, with the Cython module nearly twice as fast. For reference I include C and PyPy benchmark results as well:

C (compiled with gcc -O3 -lm)

% time ./euler12-c 

./euler12-c  11.95s 
 user 0.00s 
 system 99% 
 cpu 11.959 total

PyPy 1.5

% time pypy
16.44s user 
0.01s system 
99% cpu 16.449 total

RPython (using latest PyPy revision, c2f583445aee)

% time ./euler12-rpython-c
10.54s user 0.00s 
system 99% 
cpu 10.540 total

Cython 0.15

% time python
6.27s user 0.00s 
system 99% 
cpu 6.274 total

The RPython version has a couple of key changes. To translate into a standalone program you need to define your target, which in this case is the main function. It's expected to accept sys.argv as it's only argument, and is required to return an int. You can translate it by using, % which translates to C and compiles it for you.


import math, sys

def factorCount(n):
    square = math.sqrt(n)
    isquare = int(square)
    count = -1 if isquare == square else 0
    for candidate in xrange(1, isquare + 1):
        if not n % candidate: count += 2
    return count

def main(argv):
    triangle = 1
    index = 1
    while factorCount(triangle) < 1001:
        index += 1
        triangle += index
    print triangle
    return 0

if __name__ == '__main__':

def target(*args):
    return main, None

The Cython version was rewritten as an extension module _euler12.pyx, which I import and call from a normal python file. The _euler12.pyx is essentially the same as your version, with some additional static type declarations. The has the normal boilerplate to build the extension, using python build_ext --inplace.

# _euler12.pyx
from libc.math cimport sqrt

cdef int factorCount(int n):
    cdef int candidate, isquare, count
    cdef double square
    square = sqrt(n)
    isquare = int(square)
    count = -1 if isquare == square else 0
    for candidate in range(1, isquare + 1):
        if not n % candidate: count += 2
    return count

cpdef main():
    cdef int triangle = 1, index = 1
    while factorCount(triangle) < 1001:
        index += 1
        triangle += index
    print triangle

import _euler12

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

ext_modules = [Extension("_euler12", ["_euler12.pyx"])]

  name = 'Euler12-Cython',
  cmdclass = {'build_ext': build_ext},
  ext_modules = ext_modules

I honestly have very little experience with either RPython or Cython, and was pleasantly surprised at the results. If you are using CPython, writing your CPU-intensive bits of code in a Cython extension module seems like a really easy way to optimize your program.

How to download videos from youtube on java?

I know i am answering late. But this code may useful for some one. So i am attaching it here.

Use the following java code to download the videos from YouTube.

package com.mycompany.ytd;

import com.github.axet.vget.VGet;

 * @author Manindar
public class YTD {

    public static void main(String[] args) {
        try {
            String url = "";
            String path = "D:\\Manindar\\YTD\\";
            VGet v = new VGet(new URL(url), new File(path));
        } catch (Exception e) {
            throw new RuntimeException(e);

Add the below Dependency in your POM.XML file


Hope this will be useful.

Calculate difference between two datetimes in MySQL

If your start and end datetimes are on different days use TIMEDIFF.

SELECT TIMEDIFF(datetime1,datetime2)

if datetime1 > datetime2 then

SELECT TIMEDIFF("2019-02-20 23:46:00","2019-02-19 23:45:00")

gives: 24:01:00

and datetime1 < datetime2

SELECT TIMEDIFF("2019-02-19 23:45:00","2019-02-20 23:46:00")

gives: -24:01:00

Execute a shell script in current shell with sudo permission

I'm not sure if this breaks any rules but

sudo bash

seems to work for me.

How can building a heap be O(n) time complexity?

think you're making a mistake. Take a look at this: Building a heap isn'y O(n). However, inserting is O(lg(n). I'm assuming initialization is O(n) if you set a heap size b/c the heap needs to allocate space and set up the data structure. If you have n items to put into the heap then yes, each insert is lg(n) and there are n items, so you get n*lg(n) as u stated

css transition opacity fade background

It's not fading to "black transparent" or "white transparent". It's just showing whatever color is "behind" the image, which is not the image's background color - that color is completely hidden by the image.

If you want to fade to black(ish), you'll need a black container around the image. Something like:

.ctr {
    margin: 0; 
    padding: 0;
    background-color: black;
    display: inline-block;


<div class="ctr"><img ... /></div>

How do I convert array of Objects into one Object in JavaScript?

Tiny ES6 solution can look like:

var arr = [{key:"11", value:"1100"},{key:"22", value:"2200"}];
var object = arr.reduce(
  (obj, item) => Object.assign(obj, { [item.key]: item.value }), {});


Also, if you use object spread, than it can look like:

var object = arr.reduce((obj, item) => ({...obj, [item.key]: item.value}) ,{});

One more solution that is 99% faster is(tested on jsperf):

var object = arr.reduce((obj, item) => (obj[item.key] = item.value, obj) ,{});

Here we benefit from comma operator, it evaluates all expression before comma and returns a last one(after last comma). So we don't copy obj each time, rather assigning new property to it.

Access Controller method from another controller in Laravel 5

You can access the controller by instantiating it and calling doAction: (put use Illuminate\Support\Facades\App; before the controller class declaration)

$controller = App::make('\App\Http\Controllers\YouControllerName');
$data = $controller->callAction('controller_method', $parameters);

Also note that by doing this you will not execute any of the middlewares declared on that controller.

Set default value of javascript object attributes

I think the simplest approach is using Object.assign.

If you have this Class:

class MyHelper {
    constructor(options) {
        this.options = Object.assign({
            name: "John",
            surname: "Doe",
            birthDate: "1980-08-08"
        }, options);

You can use it like this:

let helper = new MyHelper({ name: "Mark" });
console.log(helper.options.surname); // this will output "Doe"

Documentation (with polyfill):

How to disable logging on the standard error stream in Python?

You can change the level of debug mode for specific handler instead of completely disable it.

So if you have a case you want to stop the debug mode for console only but you still need to keep the other levels like the Error. you can do this like the following

# create logger
logger = logging.getLogger(__name__)

def enableConsoleDebug (debug = False):
    #Set level to logging.DEBUG to see CRITICAL, ERROR, WARNING, INFO and DEBUG statements
    #Set level to logging.ERROR to see the CRITICAL & ERROR statements only

    debugLevel = logging.ERROR
    if debug:
        debugLevel = logging.DEBUG

    for handler in logger.handlers:
        if type(handler) is logging.StreamHandler:
            handler.setLevel (debugLevel)

Angular IE Caching issue for $http

I simply added three meta tags into index.html on angular project, and cache issue was solved on IE.

<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="Sat, 01 Dec 2001 00:00:00 GMT">

Post a json object to mvc controller with jquery and ajax

I see in your code that you are trying to pass an ARRAY to POST action. In that case follow below working code -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
    function submitForm() {
        var roles = ["role1", "role2", "role3"];

            type: "POST",
            url: "@Url.Action("AddUser")",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(roles),
            success: function (data) { alert(data); },
            failure: function (errMsg) {

<input type="button" value="Click" onclick="submitForm()"/>

And the controller action is going to be -

    public ActionResult AddUser(List<String> Roles)
        return null;

Then when you click on the button -

enter image description here

Broadcast Receiver within a Service

The better pattern is to create a standalone BroadcastReceiver. This insures that your app can respond to the broadcast, whether or not the Service is running. In fact, using this pattern may remove the need for a constant-running Service altogether.

Register the BroadcastReceiver in your Manifest, and create a separate class/file for it.


<receiver android:name=".FooReceiver" >
    <intent-filter >
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />

When the receiver runs, you simply pass an Intent (Bundle) to the Service, and respond to it in onStartCommand().


public class FooReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        // do your work quickly!
        // then call context.startService();

Disable webkit's spin buttons on input type="number"?

You can also hide spinner with following trick :

input[type=number]::-webkit-outer-spin-button {

How to suppress Update Links warning?

Hope to give some extra input in solving this question (or part of it).

This will work for opening an Excel file from another. A line of code from Mr. Peter L., for the change, use the following:

Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx", UpdateLinks:=3

This is in MSDS. The effect is that it just updates everything (yes, everything) with no warning. This can also be checked if you record a macro.

In MSDS, it refers this to MS EXCEL 2010 and 2013. I'm thinking that MS EXCEL 2016 has this covered as well.

I have MS EXCEL 2013, and have a situation pretty much the same as this topic. So I have a file (call it A) with Workbook_Open event code that always get's stuck on the update links prompt. I have another file (call it B) connected to this one, and Pivot Tables force me to open the file A so that the data model can be loaded. Since I want to open the A file silently in the background, I just use the line that I wrote above, with a Windows("A.xlsx").visible = false, and, apart from a bigger loading time, I open the A file from the B file with no problems or warnings, and fully updated.

Java - Including variables within strings?

Also consider java.text.MessageFormat, which uses a related syntax having numeric argument indexes. For example,

String aVariable = "of ponies";
String string = MessageFormat.format("A string {0}.", aVariable);

results in string containing the following:

A string of ponies.

More commonly, the class is used for its numeric and temporal formatting. An example of JFreeChart label formatting is described here; the class RCInfo formats a game's status pane.

How can I jump to class/method definition in Atom text editor?

As of November 2018 the package autocomplete-python offers this functionality with this key combo:


with mouse cursor on the function call.

How can I retrieve the remote git address of a repo?

When you want to show an URL of remote branches, try:

git remote -v

Should IBOutlets be strong or weak under ARC?

I think that most important information is: Elements in xib are automatically in subviews of view. Subviews is NSArray. NSArray owns it's elements. etc have strong pointers on them. So in most cases you don't want to create another strong pointer (IBOutlet)

And with ARC you don't need to do anything in viewDidUnload

Set time to 00:00:00

You would better to primarily set time zone to the DateFormat component like this:

DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

Then you can get "00:00:00" time by passing 0 milliseconds to formatter:

String time = dateFormat.format(0);

or you can create Date object:

Date date = new Date(0); // also pass milliseconds
String time = dateFormat.foramt(date);

or you be able to have more possibilities using Calendar component but you should also set timezone as GMT to calendar instance:

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US);
calendar.set(Calendar.HOUR_OF_DAY, 5);
calendar.set(Calendar.MINUTE, 37);
calendar.set(Calendar.SECOND, 27);


How to build a JSON array from mysql database

The PDO solution, just for a better implementation then mysql_*:

$array = $pdo->query("SELECT id, title, '$year-month-10' as start,url 
  FROM table")->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($array);

Nice feature is also that it will leave integers as integers as opposed to strings.

Unable to install packages in latest version of RStudio and R Version.3.1.1

Not 100% certain that you have the same problem, but I found out the hard way that my job blocks each mirror site option that was offered and I was getting errors like this:

Installing package into ‘/usr/lib64/R/library’
(as ‘lib’ is unspecified)
--- Please select a CRAN mirror for use in this session ---
Error in download.file(url, destfile = f, quiet = TRUE) : 
  unsupported URL scheme
Warning: unable to access index for repository
Warning message:
package ‘ggplot2’ is not available (for R version 3.2.2)

Workaround (I am using CentOS)...

install.packages('package_name', dependencies=TRUE, repos='')

I hope this saves someone hours of frustration.

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

In case you are uploading an sql file on cpanel, then try and replace root with your cpanel username in your sql file.

in the case above you could write

CREATE DEFINER = control_panel_username@localhost FUNCTION fnc_calcWalkedDistance

then upload the file. Hope it helps

Link to download apache http server for 64bit windows.

Check out the link given it has Apache HTTP Server 2.4.2 x86 and x64 Windows Installers

Oracle Sql get only month and year in date datatype

"FEB-2010" is not a Date, so it would not make a lot of sense to store it in a date column.

You can always extract the string part you need , in your case "MON-YYYY" using the TO_CHAR logic you showed above.

If this is for a DIMENSION table in a Data warehouse environment and you want to include these as separate columns in the Dimension table (as Data attributes), you will need to store the month and Year in two different columns, with appropriate Datatypes...


Month varchar2(3) --Month code in Alpha..
Year  NUMBER      -- Year in number


Month number(2)    --Month Number in Year.
Year  NUMBER      -- Year in number

Concatenating string and integer in python

String formatting, using the new-style .format() method (with the defaults .format() provides):

 '{}{}'.format(s, i)

Or the older, but "still sticking around", %-formatting:

 '%s%d' %(s, i)

In both examples above there's no space between the two items concatenated. If space is needed, it can simply be added in the format strings.

These provide a lot of control and flexibility about how to concatenate items, the space between them etc. For details about format specifications see this.

Rendering partial view on button click in ASP.NET MVC

Change the button to

<button id="search">Search</button>

and add the following script

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('#search').click(function() {
  var keyWord = $('#Keyword').val();
  $('#searchResults').load(url, { searchText: keyWord });

and modify the controller method to accept the search text

public ActionResult DisplaySearchResults(string searchText)
  var model = // build list based on parameter searchText
   return PartialView("SearchResults", model);

The jQuery .load method calls your controller method, passing the value of the search text and updates the contents of the <div> with the partial view.

Side note: The use of a <form> tag and @Html.ValidationSummary() and @Html.ValidationMessageFor() are probably not necessary here. Your never returning the Index view so ValidationSummary makes no sense and I assume you want a null search text to return all results, and in any case you do not have any validation attributes for property Keyword so there is nothing to validate.


Based on OP's comments that SearchCriterionModel will contain multiple properties with validation attributes, then the approach would be to include a submit button and handle the forms .submit() event

<input type="submit" value="Search" />

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('form').submit(function() {
  if (!$(this).valid()) { 
    return false; // prevent the ajax call if validation errors
  var form = $(this).serialize();
  $('#searchResults').load(url, form);
  return false; // prevent the default submit action

and the controller method would be

public ActionResult DisplaySearchResults(SearchCriterionModel criteria)
  var model = // build list based on the properties of criteria
  return PartialView("SearchResults", model);

How to enable file sharing for my app?

You just have to set UIFileSharingEnabled (Application Supports iTunes file sharing) key in the info plist of your app. Here's a link for the documentation. Scroll down to the file sharing support part.

In the past, it was also necessary to define CFBundleDisplayName (Bundle Display Name), if it wasn't already there. More details here.