Programs & Examples On #Contactus

There is already an object named in the database

Delete rows from dbo_MigrationHistory table or delete the table and run

update-database -verbose

It will run all the migrations in your project one by one

jQuery dialog popup

Use below Code, It worked for me.

<script type="text/javascript">
     $(document).ready(function () {
            $('#dialog').dialog({
                autoOpen: false,
                title: 'Basic Dialog'
            });
            $('#contactUs').click(function () {
                $('#dialog').dialog('open');
            });
        });
</script>

How to maintain page scroll position after a jquery event is carried out?

$('html,body').animate({
  scrollTop: $('#answer-<%= @answer.id %>').offset().top - 50
}, 700);

Get protocol, domain, and port from URL

var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');

How to store Java Date to Mysql datetime with JPA

you will get 2011-07-18 + time format

long timeNow = Calendar.getInstance().getTimeInMillis();
java.sql.Timestamp ts = new java.sql.Timestamp(timeNow);
...
preparedStatement.setTimestamp(TIME_COL_INDEX, ts);

How to unpackage and repackage a WAR file

no need to that, tomcat naturally extract the war file into a folder of the same name. you simply modify the desired file inside that folder (including .xml configuration files), that's all. technically no need to restart tomcat after applying the modifications

What is the best way to implement nested dictionaries?

As others have suggested, a relational database could be more useful to you. You can use a in-memory sqlite3 database as a data structure to create tables and then query them.

import sqlite3

c = sqlite3.Connection(':memory:')
c.execute('CREATE TABLE jobs (state, county, title, count)')

c.executemany('insert into jobs values (?, ?, ?, ?)', [
    ('New Jersey', 'Mercer County',    'Programmers', 81),
    ('New Jersey', 'Mercer County',    'Plumbers',     3),
    ('New Jersey', 'Middlesex County', 'Programmers', 81),
    ('New Jersey', 'Middlesex County', 'Salesmen',    62),
    ('New York',   'Queens County',    'Salesmen',    36),
    ('New York',   'Queens County',    'Plumbers',     9),
])

# some example queries
print list(c.execute('SELECT * FROM jobs WHERE county = "Queens County"'))
print list(c.execute('SELECT SUM(count) FROM jobs WHERE title = "Programmers"'))

This is just a simple example. You could define separate tables for states, counties and job titles.

Breaking out of a for loop in Java

How about

for (int k = 0; k < 10; k = k + 2) {
    if (k == 2) {
        break;
    }

    System.out.println(k);
}

The other way is a labelled loop

myloop:  for (int i=0; i < 5; i++) {

              for (int j=0; j < 5; j++) {

                if (i * j > 6) {
                  System.out.println("Breaking");
                  break myloop;
                }

                System.out.println(i + " " + j);
              }
          }

For an even better explanation you can check here

Seeking useful Eclipse Java code templates

This prints an entire object (assumes you have already initiated a log4j LOGGER object):

  ${:import(org.codehaus.jackson.map.ObjectMapper)}
  // If check to avoid argument evaluation costs
  if (LOGGER.isDebugEnabled()) {
        try {
            LOGGER.debug("Object ${Object}: " + "\n"
                + new ObjectMapper().writeValueAsString(${Object}));
        } catch (JsonGenerationException e) {
            LOGGER.info(e.toString());
        } catch (JsonMappingException e) {
            LOGGER.info(e.toString());
        } catch (IOException e) {
            LOGGER.info(e.toString());
        }
  }

How to change RGB color to HSV?

There's a C implementation here:

http://www.cs.rit.edu/~ncs/color/t_convert.html

Should be very straightforward to convert to C#, as almost no functions are called - just calculations.

found via Google

HTTP GET Request in Node.js Express

You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.

Just do the following for GET method request:

var requestify = require('requestify');

requestify.get('http://example.com/api/resource')
  .then(function(response) {
      // Get the response body (JSON parsed or jQuery object for XMLs)
      response.getBody();
  }
);

Find distance between two points on map using Google Map API V2

You can use the following method that will give you accurate result

public double CalculationByDistance(LatLng StartP, LatLng EndP) {
        int Radius = 6371;// radius of earth in Km
        double lat1 = StartP.latitude;
        double lat2 = EndP.latitude;
        double lon1 = StartP.longitude;
        double lon2 = EndP.longitude;
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
                + Math.cos(Math.toRadians(lat1))
                * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
                * Math.sin(dLon / 2);
        double c = 2 * Math.asin(Math.sqrt(a));
        double valueResult = Radius * c;
        double km = valueResult / 1;
        DecimalFormat newFormat = new DecimalFormat("####");
        int kmInDec = Integer.valueOf(newFormat.format(km));
        double meter = valueResult % 1000;
        int meterInDec = Integer.valueOf(newFormat.format(meter));
        Log.i("Radius Value", "" + valueResult + "   KM  " + kmInDec
                + " Meter   " + meterInDec);

        return Radius * c;
    }

Merge 2 DataTables and store in a new one

The Merge method takes the values from the second table and merges them in with the first table, so the first will now hold the values from both.

If you want to preserve both of the original tables, you could copy the original first, then merge:

dtAll = dtOne.Copy();
dtAll.Merge(dtTwo);

How can I get a random number in Kotlin?

Below in Kotlin worked well for me:

(fromNumber.rangeTo(toNumber)).random()

Range of the numbers starts with variable fromNumber and ends with variable toNumber. fromNumber and toNumber will also be included in the random numbers generated out of this.

Valid to use <a> (anchor tag) without href attribute?

It is valid. You can, for example, use it to show modals (or similar things that respond to data-toggle and data-target attributes).

Something like:

<a role="button" data-toggle="modal" data-target=".bs-example-modal-sm" aria-hidden="true"><i class="fa fa-phone"></i></a>

Here I use the font-awesome icon, which is better as a a tag rather than a button, to show a modal. Also, setting role="button" makes the pointer change to an action type. Without either href or role="button", the cursor pointer does not change.

How to have Android Service communicate with Activity

I am surprised that no one has given reference to Otto event Bus library

http://square.github.io/otto/

I have been using this in my android apps and it works seamlessly.

vbscript output to console

This was found on Dragon-IT Scripts and Code Repository.

You can do this with the following and stay away from the cscript/wscript differences and allows you to get the same console output that a batch file would have. This can help if your calling VBS from a batch file and need to make it look seamless.

Set fso = CreateObject ("Scripting.FileSystemObject")
Set stdout = fso.GetStandardStream (1)
Set stderr = fso.GetStandardStream (2)
stdout.WriteLine "This will go to standard output."
stderr.WriteLine "This will go to error output."

Adding CSRFToken to Ajax request

The answer above didn't work for me.

I added the following code before my ajax request:

function getCookie(name) {
                var cookieValue = null;
                if (document.cookie && document.cookie != '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = jQuery.trim(cookies[i]);
                        // Does this cookie string begin with the name we want?
                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }
            var csrftoken = getCookie('csrftoken');

            function csrfSafeMethod(method) {
                // these HTTP methods do not require CSRF protection
                return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
            }

            $.ajaxSetup({
                beforeSend: function(xhr, settings) {
                    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                }
            });

            $.ajax({
                     type: 'POST',
                     url: '/url/',
            });

how to open a page in new tab on button click in asp.net?

You could do this on the ASPX HTML front end to make the button go to a new tab to show page in your ASP.NET site dynamically:

        <asp:Button ID="btnNewEntry" CssClass="button"  OnClientClick="window.open('https://website','_blank'); return false;" text="WebsiteName"  runat="server" />

'printf' vs. 'cout' in C++

Two points not otherwise mentioned here that I find significant:

1) cout carries a lot of baggage if you're not already using the STL. It adds over twice as much code to your object file as printf. This is also true for string, and this is the major reason I tend to use my own string library.

2) cout uses overloaded << operators, which I find unfortunate. This can add confusion if you're also using the << operator for its intended purpose (shift left). I personally don't like to overload operators for purposes tangential to their intended use.

Bottom line: I'll use cout (and string) if I'm already using the STL. Otherwise, I tend to avoid it.

Using boolean values in C

From best to worse:

Option 1 (C99 and newer)

#include <stdbool.h>

Option 2

typedef enum { false, true } bool;

Option 3

typedef int bool;
enum { false, true };

Option 4

typedef int bool;
#define true 1
#define false 0

#Explanation

  • Option 1 will work only if you use C99 (or newer) and it's the "standard way" to do it. Choose this if possible.
  • Options 2, 3 and 4 will have in practice the same identical behavior. #2 and #3 don't use #defines though, which in my opinion is better.

If you are undecided, go with #1!

removing table border

From your case, you need to set the border to none on <table> and <td> tags.

    <table width=1000 style="border:none; border-collapse:collapse; cellspacing:0; cellpadding:0" >
        <tr>
            <td style="border:none" rowspan=2>
                <img src="/Content/Images/elk_banner.jpg" />
            </td>
            <td style="border:none">
                <div id="logindisplay">
                    @Html.Partial("_LogOnPartial")
                </div>
            </td>
        </tr>
    </table>

iOS UIImagePickerController result image orientation after upload

I achieve this by writing below a few lines of code

extension UIImage {

    public func correctlyOrientedImage() -> UIImage {
        guard imageOrientation != .up else { return self }

        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        draw(in: CGRect(origin: .zero, size: size))
        let normalizedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        return normalizedImage
    }
}

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

You need to add the package containing the executable pg_config.

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

How to subtract 30 days from the current datetime in mysql?

SELECT date_format(current_date - INTERVAL 50 DAY,'%d-%b-%Y')

You can format by using date format in SQL.

How can I get the "network" time, (from the "Automatic" setting called "Use network-provided values"), NOT the time on the phone?

NITZ is a form of NTP and is sent to the mobile device over Layer 3 or NAS layers. Commonly this message is seen as GMM Info and contains the following informaiton:

Certain carriers dont support this and some support it and have it setup incorrectly.

LAYER 3 SIGNALING MESSAGE

Time: 9:38:49.800

GMM INFORMATION 3GPP TS 24.008 ver 12.12.0 Rel 12 (9.4.19)

M Protocol Discriminator (hex data: 8)

(0x8) Mobility Management message for GPRS services

M Skip Indicator (hex data: 0) Value: 0 M Message Type (hex data: 21) Message number: 33

O Network time zone (hex data: 4680) Time Zone value: GMT+2:00 O Universal time and time zone (hex data: 47716070 70831580) Year: 17 Month: 06 Day: 07 Hour: 07 Minute :38 Second: 51 Time zone value: GMT+2:00 O Network Daylight Saving Time (hex data: 490100) Daylight Saving Time value: No adjustment

Layer 3 data: 08 21 46 80 47 71 60 70 70 83 15 80 49 01 00

How do I use PHP to get the current year?

<?php date_default_timezone_set("Asia/Kolkata");?><?=date("Y");?>

You can use this in footer sections to get dynamic copyright year

Match linebreaks - \n or \r\n?

Gonna answer in opposite direction.

2) For a full explanation about \r and \n I have to refer to this question, which is far more complete than I will post here: Difference between \n and \r?

Long story short, Linux uses \n for a new-line, Windows \r\n and old Macs \r. So there are multiple ways to write a newline. Your second tool (RegExr) does for example match on the single \r.

1) [\r\n]+ as Ilya suggested will work, but will also match multiple consecutive new-lines. (\r\n|\r|\n) is more correct.

How do I make a simple crawler in PHP?

Its worth remembering that when crawling external links (I do appreciate the OP relates to a users own page) you should be aware of robots.txt. I have found the following which will hopefully help http://www.the-art-of-web.com/php/parse-robots/.

Get div height with plain JavaScript

Here's one more alternative:

var classElements = document.getElementsByClassName("className");

function setClassHeight (classElements, desiredHeightValue) 
    {
        var arrayElements = Object.entries(classElements);
        for(var i = 0; i< arrayElements.length; i++) {
            arrayElements[i][1].style.height = desiredHeightValue;
        }

    }

How to override trait function and call it from the overridden function?

Using another trait:

trait ATrait {
    function calc($v) {
        return $v+1;
    }
}

class A {
    use ATrait;
}

trait BTrait {
    function calc($v) {
        $v++;
        return parent::calc($v);
    }
}

class B extends A {
    use BTrait;
}

print (new B())->calc(2); // should print 4

Xcode 6 Bug: Unknown class in Interface Builder file

I had this problem after I added a new target, then created a new class using the 'New File' dialog but accidentally failed to check the new target as well as the original target in the creation dialog, so the object was only added to my original target. The solution was to delete the source files (remove reference only) then add them back using 'Add Files', this time checking both targets.

How to change TIMEZONE for a java.util.Calendar/Date

  1. The class Date/Timestamp represents a specific instant in time, with millisecond precision, since January 1, 1970, 00:00:00 GMT. So this time difference (from epoch to current time) will be same in all computers across the world with irrespective of Timezone.

  2. Date/Timestamp doesn't know about the given time is on which timezone.

  3. If we want the time based on timezone we should go for the Calendar or SimpleDateFormat classes in java.

  4. If you try to print a Date/Timestamp object using toString(), it will convert and print the time with the default timezone of your machine.

  5. So we can say (Date/Timestamp).getTime() object will always have UTC (time in milliseconds)

  6. To conclude Date.getTime() will give UTC time, but toString() is on locale specific timezone, not UTC.

Now how will I create/change time on specified timezone?

The below code gives you a date (time in milliseconds) with specified timezones. The only problem here is you have to give date in string format.

   DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
   dateFormatLocal.setTimeZone(timeZone);
   java.util.Date parsedDate = dateFormatLocal.parse(date);

Use dateFormat.format for taking input Date (which is always UTC), timezone and return date as String.

How to store UTC/GMT time in DB:

If you print the parsedDate object, the time will be in default timezone. But you can store the UTC time in DB like below.

        Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        Timestamp tsSchedStartTime = new Timestamp (parsedDate.getTime());
        if (tsSchedStartTime != null) {
            stmt.setTimestamp(11, tsSchedStartTime, calGMT );
        } else {
            stmt.setNull(11, java.sql.Types.DATE);
        }

Difference between abstract class and interface in Python

Abstract classes are classes that contain one or more abstract methods. Along with abstract methods, Abstract classes can have static, class and instance methods. But in case of interface, it will only have abstract methods not other. Hence it is not compulsory to inherit abstract class but it is compulsory to inherit interface.

How to get the integer value of day of week

DateTime currentDateTime = DateTime.Now;
int week = (int) currentDateTime.DayOfWeek;

How to install Ruby 2.1.4 on Ubuntu 14.04

There is a PPA with up-to-date versions of Ruby 2.x for Ubuntu 12.04+:

$ sudo apt-add-repository ppa:brightbox/ruby-ng
$ sudo apt-get update
$ sudo apt-get install ruby2.4

$ ruby -v
ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux-gnu]

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

There is a better answer to solve this problem. add dependency

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

For the benefit of searchers looking to solve a similar problem, you can get a similar error if your input is an empty string.

e.g.

var d = "";
var json = JSON.parse(d);

or if you are using AngularJS

var d = "";
var json = angular.fromJson(d);

In chrome it resulted in 'Uncaught SyntaxError: Unexpected end of input', but Firebug showed it as 'JSON.parse: unexpected end of data at line 1 column 1 of the JSON data'.

Sure most people won't be caught out by this, but I hadn't protected the method and it resulted in this error.

Execution Failed for task :app:compileDebugJavaWithJavac in Android Studio

I faced this issue after upgrading the Android studio to version 2.2.2, I solved it by using embedded JDK as recommended : enter image description here

How do I stop/start a scheduled task on a remote computer programmatically?

schtasks /change /disable /tn "Name Of Task" /s REMOTEMACHINENAME /u mydomain\administrator /p adminpassword 

Google Chrome form autofill and its yellow background

If you want to avoid the yellow flicker until your css is applied slap a transition on that bad boy like so:

input:-webkit-autofill {
    -webkit-box-shadow: 0 0 0 1000px white inset !important;
    transition: background-color 10s ease-in-out 0s;
}

'True' and 'False' in Python

From 6.11. Boolean operations:

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.

The key phrasing here that I think you are misunderstanding is "interpreted as false" or "interpreted as true". This does not mean that any of those values are identical to True or False, or even equal to True or False.

The expression '/bla/bla/bla' will be treated as true where a Boolean expression is expected (like in an if statement), but the expressions '/bla/bla/bla' is True and '/bla/bla/bla' == True will evaluate to False for the reasons in Ignacio's answer.

Display fullscreen mode on Tkinter

I think if you are looking for fullscreen only, no need to set geometry or maxsize etc.

You just need to do this:

-If you are working on ubuntu:

root=tk.Tk()
root.attributes('-zoomed', True)

-and if you are working on windows:

root.state('zoomed')

Now for toggling between fullscreen, for minimising it to taskbar you can use:

Root.iconify()

Storing a Key Value Array into a compact JSON string

If the logic parsing this knows that {"key": "slide0001.html", "value": "Looking Ahead"} is a key/value pair, then you could transform it in an array and hold a few constants specifying which index maps to which key.

For example:

var data = ["slide0001.html", "Looking Ahead"];

var C_KEY = 0;
var C_VALUE = 1;

var value = data[C_VALUE];

So, now, your data can be:

[
    ["slide0001.html", "Looking Ahead"],
    ["slide0008.html", "Forecast"],
    ["slide0021.html", "Summary"]
]

If your parsing logic doesn't know ahead of time about the structure of the data, you can add some metadata to describe it. For example:

{ meta: { keys: [ "key", "value" ] },
  data: [
    ["slide0001.html", "Looking Ahead"],
    ["slide0008.html", "Forecast"],
    ["slide0021.html", "Summary"]
  ]
}

... which would then be handled by the parser.

#pragma once vs include guards?

#pragma once allows the compiler to skip the file completely when it occurs again - instead of parsing the file until it reaches the #include guards.

As such, the semantics are a little different, but they are identical if they are used they way they are intended to be used.

Combining both is probably the safest route to go, as in the worst case (a compiler flagging unknown pragmas as actual errors, not just warnings) you would just to have to remove the #pragma's themselves.

When you limit your platforms to, say "mainstream compilers on the desktop", you could safely omit the #include guards, but I feel uneasy on that, too.

OT: if you have other tips/experiences to share on speeding up builds, I'd be curious.

What is the difference between match_parent and fill_parent?

match_parent and fill_parent are same property, used to define width or height of a view in full screen horizontally or vertically.

These properties are used in android xml files like this.

 android:layout_width="match_parent"
 android:layout_height="fill_parent"

or

 android:layout_width="fill_parent"
 android:layout_height="match_parent"

fill_parent was used in previous versions, but now it has been deprecated and replaced by match_parent. I hope it'll help you.

how to change the dist-folder path in angular-cli after 'ng build'

The more current way of this is to update the outDir property in .angular-cli.json.

The ng build command argument --output-path (or -op for short) is still supported also, which can be useful if you want multiple values, you can save them in your package.json as npm scripts.

Beware: The .angular-cli.json property is NOT called output-path like the currently-accepted answer by @cwill747 says. That's the ng build argument only.

It's called outDir as mentioned above, and it's a under the apps property.

.

P.S.

(December 2017)

1-year after adding this answer, someone added a new answer with essentially same information, and the Original Poster changed the accepted answer to the 1-year-late answer containing same information in the first line of this one.

When should we implement Serializable interface?

  1. Implement the Serializable interface when you want to be able to convert an instance of a class into a series of bytes or when you think that a Serializable object might reference an instance of your class.

  2. Serializable classes are useful when you want to persist instances of them or send them over a wire.

  3. Instances of Serializable classes can be easily transmitted. Serialization does have some security consequences, however. Read Joshua Bloch's Effective Java.

How to get first character of a string in SQL?

SUBSTRING ( MyColumn, 1 , 1 ) for the first character and SUBSTRING ( MyColumn, 1 , 2 ) for the first two.

How to call a method defined in an AngularJS directive?

To be honest, I was not really convinced with any of the answers in this thread. So, here's are my solutions:

Directive Handler(Manager) Approach

This method is agnostic to whether the directive's $scope is a shared one or isolated one

A factory to register the directive instances

angular.module('myModule').factory('MyDirectiveHandler', function() {
    var instance_map = {};
    var service = {
        registerDirective: registerDirective,
        getDirective: getDirective,
        deregisterDirective: deregisterDirective
    };

    return service;

    function registerDirective(name, ctrl) {
        instance_map[name] = ctrl;
    }

    function getDirective(name) {
        return instance_map[name];
    }

    function deregisterDirective(name) {
        instance_map[name] = null;
    }
});

The directive code, I usually put all the logic that doesn't deal with DOM inside directive controller. And registering the controller instance inside our handler

angular.module('myModule').directive('myDirective', function(MyDirectiveHandler) {
    var directive = {
        link: link,
        controller: controller
    };

    return directive;

    function link() {
        //link fn code
    }

    function controller($scope, $attrs) {
        var name = $attrs.name;

        this.updateMap = function() {
            //some code
        };

        MyDirectiveHandler.registerDirective(name, this);

        $scope.$on('destroy', function() {
            MyDirectiveHandler.deregisterDirective(name);
        });
    }
})

template code

<div my-directive name="foo"></div>

Access the controller instance using the factory & run the publicly exposed methods

angular.module('myModule').controller('MyController', function(MyDirectiveHandler, $scope) {
    $scope.someFn = function() {
        MyDirectiveHandler.get('foo').updateMap();
    };
});

Angular's approach

Taking a leaf out of angular's book on how they deal with

<form name="my_form"></form>

using $parse and registering controller on $parent scope. This technique doesn't work on isolated $scope directives.

angular.module('myModule').directive('myDirective', function($parse) {
    var directive = {
        link: link,
        controller: controller,
        scope: true
    };

    return directive;

    function link() {
        //link fn code
    }

    function controller($scope, $attrs) {
        $parse($attrs.name).assign($scope.$parent, this);

        this.updateMap = function() {
            //some code
        };
    }
})

Access it inside controller using $scope.foo

angular.module('myModule').controller('MyController', function($scope) {
    $scope.someFn = function() {
        $scope.foo.updateMap();
    };
});

How to get config parameters in Symfony2 Twig Templates

On newer versions of Symfony2 (using a parameters.yml instead of parameters.ini), you can store objects or arrays instead of key-value pairs, so you can manage your globals this way:

config.yml (edited only once):

# app/config/config.yml
twig:
  globals:
    project: %project%

parameters.yml:

# app/config/parameters.yml
project:
  name:       myproject.com
  version:    1.1.42

And then in a twig file, you can use {{ project.version }} or {{ project.name }}.

Note: I personally dislike adding things to app, just because that's the Symfony's variable and I don't know what will be stored there in the future.

Count number of occurrences for each unique value

select time, coalesce(count(case when activities = 3 then 1 end), 0) as count
from MyTable
group by time

SQL Fiddle Example

Output:

|  TIME | COUNT |
-----------------
| 13:00 |     2 |
| 13:15 |     2 |
| 13:30 |     0 |
| 13:45 |     1 |

If you want to count all the activities in one query, you can do:

select time, 
    coalesce(count(case when activities = 1 then 1 end), 0) as count1,
    coalesce(count(case when activities = 2 then 1 end), 0) as count2,
    coalesce(count(case when activities = 3 then 1 end), 0) as count3,
    coalesce(count(case when activities = 4 then 1 end), 0) as count4,
    coalesce(count(case when activities = 5 then 1 end), 0) as count5
from MyTable
group by time

The advantage of this over grouping by activities, is that it will return a count of 0 even if there are no activites of that type for that time segment.

Of course, this will not return rows for time segments with no activities of any type. If you need that, you'll need to use a left join with table that lists all the possible time segments.

How to make a edittext box in a dialog

Use Activtiy Context

Replace this

  final EditText input = new EditText(this);

By

  final EditText input = new EditText(MainActivity.this);  
  LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.MATCH_PARENT);
  input.setLayoutParams(lp);
  alertDialog.setView(input); // uncomment this line

How to specify in crontab by what user to run script?

You can also try using runuser (as root) to run a command as a different user

*/1 * * * * runuser php5 \
            --command="/var/www/web/includes/crontab/queue_process.php \
                       >> /var/www/web/includes/crontab/queue.log 2>&1"

See also: man runuser

Java, Shifting Elements in an Array

Assuming your array is {10,20,30,40,50,60,70,80,90,100}

What your loop does is:

Iteration 1: array[1] = array[0]; {10,10,30,40,50,60,70,80,90,100}

Iteration 2: array[2] = array[1]; {10,10,10,40,50,60,70,80,90,100}

What you should be doing is

Object temp = pool[position];

for (int i = (position - 1); i >= 0; i--) {                
    array[i+1] = array[i];
}

array[0] = temp;

Is Python faster and lighter than C++?

Also: Psyco vs. C++.

It's still a bad comparison, since noone would do the numbercrunchy stuff benchmarks tend to focus on in pure Python anyway. A better one would be comparing the performance of realistic applications, or C++ versus NumPy, to get an idea whether your program will be noticeably slower.

Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function

@zdan. Good answer. I'd improve it like this...

I think that the closest you can come to a true return value in PowerShell is to use a local variable to pass the value and never to use return as it may be 'corrupted' by any manner of output situations

function CheckRestart([REF]$retval)
{
    # Some logic
    $retval.Value = $true
}
[bool]$restart = $false
CheckRestart( [REF]$restart)
if ( $restart )
{
    Restart-Computer -Force
}

The $restart variable is used either side of the call to the function CheckRestart making clear the scope of the variable. The return value can by convention be either the first or last parameter declared. I prefer last.

DataSet panel (Report Data) in SSRS designer is gone

With a report (rdl) file selected in your solution, select View and then Report Data.

It is a shortcut of Ctrl+Alt+D.

enter image description here

How to use componentWillMount() in React Hooks?

According to reactjs.org, componentWillMount will not be supported in the future. https://reactjs.org/docs/react-component.html#unsafe_componentwillmount

There is no need to use componentWillMount.

If you want to do something before the component mounted, just do it in the constructor().

If you want to do network requests, do not do it in componentWillMount. It is because doing this will lead to unexpected bugs.

Network requests can be done in componentDidMount.

Hope it helps.


updated on 08/03/2019

The reason why you ask for componentWillMount is probably because you want to initialize the state before renders.

Just do it in useState.

const helloWorld=()=>{
    const [value,setValue]=useState(0) //initialize your state here
    return <p>{value}</p>
}
export default helloWorld;

or maybe You want to run a function in componentWillMount, for example, if your original code looks like this:

componentWillMount(){
  console.log('componentWillMount')
}

with hook, all you need to do is to remove the lifecycle method:

const hookComponent=()=>{
    console.log('componentWillMount')
    return <p>you have transfered componeWillMount from class component into hook </p>
}

I just want to add something to the first answer about useEffect.

useEffect(()=>{})

useEffect runs on every render, it is a combination of componentDidUpdate, componentDidMount and ComponentWillUnmount.

 useEffect(()=>{},[])

If we add an empty array in useEffect it runs just when the component mounted. It is because useEffect will compare the array you passed to it. So it does not have to be an empty array.It can be array that is not changing. For example, it can be [1,2,3] or ['1,2']. useEffect still only runs when component mounted.

It depends on you whether you want it to run just once or runs after every render. It is not dangerous if you forgot to add an array as long as you know what you are doing.

I created a sample for hook. Please check it out.

https://codesandbox.io/s/kw6xj153wr


updated on 21/08/2019

It has been a while since I wrote the above answer. There is something that I think you need to pay attention to. When you use

useEffect(()=>{},[])

When react compares the values you passed to the array [], it uses Object.is() to compare. If you pass an object to it, such as

useEffect(()=>{},[{name:'Tom'}])

This is exactly the same as:

useEffect(()=>{})

It will re-render every time because when Object.is() compares an object, it compares its reference, not the value itself. It is the same as why {}==={} returns false because their references are different. If you still want to compare the object itself not the reference, you can do something like this:

useEffect(()=>{},[JSON.stringify({name:'Tom'})])

nodejs get file name from absolute path?

So Nodejs comes with the default global variable called '__fileName' that holds the current file being executed My advice is to pass the __fileName to a service from any file , so that the retrieval of the fileName is made dynamic

Below, I make use of the fileName string and then split it based on the path.sep. Note path.sep avoids issues with posix file seperators and windows file seperators (issues with '/' and '\'). It is much cleaner. Getting the substring and getting only the last seperated name and subtracting it with the actulal length by 3 speaks for itself.

You can write a service like this (Note this is in typescript , but you can very well write it in js )

export class AppLoggingConstants {

    constructor(){

    }
      // Here make sure the fileName param is actually '__fileName'
    getDefaultMedata(fileName: string, methodName: string) {
        const appName = APP_NAME;
        const actualFileName = fileName.substring(fileName.lastIndexOf(path.sep)+1, fileName.length - 3);
        //const actualFileName = fileName;
     return appName+ ' -- '+actualFileName;
    }


}

export const AppLoggingConstantsInstance = new AppLoggingConstants();

How can I set the 'backend' in matplotlib in Python?

For new comers,

matplotlib.pyplot.switch_backend(newbackend)

Stopping an Android app from console

pkill NAMEofAPP

Non rooted marshmallow, termux & terminal emulator.

@font-face not working

I'm also facing this type of problem. After trying all solutions I got final solution on this problem. Reasons for this type of problem is per-defined global fonts. Use !important keyword for each line in @font-face is the solution for this problem.

Full description and example for Solution of this problem is here :- http://answerdone.blogspot.com/2017/06/font-face-not-working-solution.html

How can I create C header files

  1. Open your favorite text editor
  2. Create a new file named whatever.h
  3. Put your function prototypes in it

DONE.

Example whatever.h

#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif

Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once but it is not guaranteed to be supported on every compiler.

Example whatever.c

#include "whatever.h"

int f(int a) { return a + 1; }

And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.

Like this:

sample.c

#include "whatever.h"

int main(int argc, char **argv)
{
    printf("%d\n", f(2)); /* prints 3 */
    return 0;
}

To compile it (if you use GCC):

$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o

To link the files to create an executable file:

$ gcc sample.o whatever.o -o sample

You can test sample:

$ ./sample
3
$

How to open a second activity on click of button in android app

This always works, either one should be just fine:

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    Button btn = (Button) findViewById(R.id.button1);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick (View v) {
            startActivity(new Intent("com.tobidae.Activity1"));
        }
        //** OR you can just use the one down here instead, both work either way
        @Override
        public void onClick (View v){
            Intent i = new Intent(getApplicationContext(), ChemistryActivity.class);
            startActivity(i);
        }
    }
}

How can I properly handle 404 in ASP.NET MVC?

My shortened solution that works with unhandled areas, controllers and actions:

  1. Create a view 404.cshtml.

  2. Create a base class for your controllers:

    public class Controller : System.Web.Mvc.Controller
    {
        protected override void HandleUnknownAction(string actionName)
        {
            Http404().ExecuteResult(ControllerContext);
        }
    
        protected virtual ViewResult Http404()
        {
            Response.StatusCode = (int)HttpStatusCode.NotFound;
            return View("404");
        }
    }
    
  3. Create a custom controller factory returning your base controller as a fallback:

    public class ControllerFactory : DefaultControllerFactory
    {
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType != null)
                return base.GetControllerInstance(requestContext, controllerType);
    
            return new Controller();
        }
    }
    
  4. Add to Application_Start() the following line:

    ControllerBuilder.Current.SetControllerFactory(typeof(ControllerFactory));
    

css transition opacity fade background

http://jsfiddle.net/6xJQq/13/

.container {
    display: inline-block;
    padding: 5px; /*included padding to see background when img apacity is 100%*/
    background-color: black;
    opacity: 1;
}

.container:hover {
    background-color: red;
}

img {
    opacity: 1;
}

img:hover {
    opacity: 0.7;
}

.transition {
    transition: all .25s ease-in-out;
    -moz-transition: all .25s ease-in-out;
    -webkit-transition: all .25s  ease-in-out;
}

How to see tomcat is running or not

open your browser,check whether Tomcat homepage is visible by below command.

http://ipaddress:portnumber

also check this

Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"

  1. Open Terminal
  2. Write or paste in: defaults write org.R-project.R force.LANG en_US.UTF-8
  3. Close Terminal (including any RStudio window)
  4. Start R

For someone runs R in a docker environment (under root), try to run R with below command,

LC_ALL=C.UTF-8 R
# instead of just `R`

How do I plot list of tuples in Python?

As others have answered, scatter() or plot() will generate the plot you want. I suggest two refinements to answers that are already here:

  1. Use numpy to create the x-coordinate list and y-coordinate list. Working with large data sets is faster in numpy than using the iteration in Python suggested in other answers.

  2. Use pyplot to apply the logarithmic scale rather than operating directly on the data, unless you actually want to have the logs.

    import matplotlib.pyplot as plt
    import numpy as np
    
    data = [(2, 10), (3, 100), (4, 1000), (5, 100000)]
    data_in_array = np.array(data)
    '''
    That looks like array([[     2,     10],
                           [     3,    100],
                           [     4,   1000],
                           [     5, 100000]])
    '''
    
    transposed = data_in_array.T
    '''
    That looks like array([[     2,      3,      4,      5],
                           [    10,    100,   1000, 100000]])
    '''    
    
    x, y = transposed 
    
    # Here is the OO method
    # You could also the state-based methods of pyplot
    fig, ax = plt.subplots(1,1) # gets a handle for the AxesSubplot object
    ax.plot(x, y, 'ro')
    ax.plot(x, y, 'b-')
    ax.set_yscale('log')
    fig.show()
    

result

I've also used ax.set_xlim(1, 6) and ax.set_ylim(.1, 1e6) to make it pretty.

I've used the object-oriented interface to matplotlib. Because it offers greater flexibility and explicit clarity by using names of the objects created, the OO interface is preferred over the interactive state-based interface.

How can I grep for a string that begins with a dash/hyphen?

The dash is a special character in Bash as noted at http://tldp.org/LDP/abs/html/special-chars.html#DASHREF. So escaping this once just gets you past Bash, but Grep still has it's own meaning to dashes (by providing options).

So you really need to escape it twice (if you prefer not to use the other mentioned answers). The following will/should work

grep \\-X
grep '\-X'
grep "\-X"

One way to try out how Bash passes arguments to a script/program is to create a .sh script that just echos all the arguments. I use a script called echo-args.sh to play with from time to time, all it contains is:

echo $*

I invoke it as:

bash echo-args.sh \-X
bash echo-args.sh \\-X
bash echo-args.sh "\-X"

You get the idea.

How do I loop through items in a list box and then remove those item?

Here my solution without going backward and without a temporary list

while (listBox1.Items.Count > 0)
{
  string s = listBox1.Items[0] as string;
  // do something with s
  listBox1.Items.RemoveAt(0);
}

How do I call the base class constructor?

In the header file define a base class:

class BaseClass {
public:
    BaseClass(params);
};

Then define a derived class as inheriting the BaseClass:

class DerivedClass : public BaseClass {
public:
    DerivedClass(params);
};

In the source file define the BaseClass constructor:

BaseClass::BaseClass(params)
{
     //Perform BaseClass initialization
}

By default the derived constructor only calls the default base constructor with no parameters; so in this example, the base class constructor is NOT called automatically when the derived constructor is called, but it can be achieved simply by adding the base class constructor syntax after a colon (:). Define a derived constructor that automatically calls its base constructor:

DerivedClass::DerivedClass(params) : BaseClass(params)
{
     //This occurs AFTER BaseClass(params) is called first and can
     //perform additional initialization for the derived class
}

The BaseClass constructor is called BEFORE the DerivedClass constructor, and the same/different parameters params may be forwarded to the base class if desired. This can be nested for deeper derived classes. The derived constructor must call EXACTLY ONE base constructor. The destructors are AUTOMATICALLY called in the REVERSE order that the constructors were called.

EDIT: There is an exception to this rule if you are inheriting from any virtual classes, typically to achieve multiple inheritance or diamond inheritance. Then you MUST explicitly call the base constructors of all virtual base classes and pass the parameters explicitly, otherwise it will only call their default constructors without any parameters. See: virtual inheritance - skipping constructors

How do you reindex an array in PHP but with indexes starting from 1?

Duplicate removal and reindex an array:

<?php  
   $oldArray = array('0'=>'php','1'=>'java','2'=>'','3'=>'asp','4'=>'','5'=>'mysql');
   //duplicate removal
   $fillteredArray = array_filter($oldArray);
   //reindexing actually happens  here
   $newArray = array_merge($filteredArray);
   print_r($newArray);
?>

Bind a function to Twitter Bootstrap Modal Close

Starting Bootstrap 3 (edit: still the same in Bootstrap 4) there are 2 instances in which you can fire up events, being:

1. When modal "hide" event starts

$('#myModal').on('hide.bs.modal', function () { 
    console.log('Fired at start of hide event!');
});  

2. When modal "hide" event finished

$('#myModal').on('hidden.bs.modal', function () {
    console.log('Fired when hide event has finished!');
});

Ref: http://getbootstrap.com/javascript/#js-events

Conditional logic in AngularJS template

You can use ng-show on every div element in the loop. Is this what you've wanted: http://jsfiddle.net/pGwRu/2/ ?

<div class="from" ng-show="message.from">From: {{message.from.name}}</div>

Symbol for any number of any characters in regex?

I would use .*. . matches any character, * signifies 0 or more occurrences. You might need a DOTALL switch to the regex to capture new lines with ..

What does "Use of unassigned local variable" mean?

If you declare the variable "annualRate" like

class Program {

**static double annualRate;**

public static void Main() {

Try it..

MySQL Error: #1142 - SELECT command denied to user

I had this problem too and for me, the problem was that I moved to a new server and the database I was trying to connect to with my PHP code changed from "my_Database" to "my_database".

How to generate access token using refresh token through google drive API?

POST /oauth2/v4/token

Host: www.googleapis.com

Headers

Content-length: 163

content-type: application/x-www-form-urlencoded

RequestBody

client_secret=************&grant_type=refresh_token&refresh_token=sasasdsa1312dsfsdf&client_id=************

Angular 2 router no base href set

Since 2.0 beta :)

import { APP_BASE_HREF } from 'angular2/platform/common';

Add shadow to custom shape on Android

if you need a straight line shadow (like in bottom of toolbar) you can also use gradient xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:type="linear"
        android:angle="-90"
        android:startColor="#19000000" <!-- black transparent -->
        android:endColor="#00000000" /> <!-- full transparent -->
</shape>

hope this help some one

Checking for an empty file in C++

if (nfile.eof()) // Prompt data from the Priming read:
    nfile >> CODE >> QTY >> PRICE;
else
{
    /*used to check that the file is not empty*/
    ofile << "empty file!!" << endl;
    return 1;
}

Switch: Multiple values in one case?

You can use ifelse instead.but if you want to know how to use switch in this case.here is an example.

int age = Convert.ToInt32(txtBoxAge.Text);`
int flag;
if(age >= 1 && age <= 8) {
flag = 1;
} else if (age >= 9 && age <= 15) {
 flag = 2;
} else if (age >= 16 && age <= 100) {
 flag = 3;
} else {
 flag = 4;   
}
switch (flag) 

{
 case 1:
  MessageBox.Show("You are only " + age + " years old\n You must be kidding right.\nPlease fill in your *real* age.");
break;
case 2:
  MessageBox.Show("You are only " + age + " years old\n That's too young!");
break;
case 3:
  MessageBox.Show("You are " + age + " years old\n Perfect.");
break;
default:
  MessageBox.Show("You an old person.");
break;
}

hope that helps ! :)

How to make a HTML Page in A4 paper size page(s)?

It's entirely possible to set your layout to assume the proportions of an a4 page. You would only have to set width and height accordingly (possibly check with window.innerHeight and window.innerWidth although I'm not sure if that is reliable).

The tricky part is with printing A4. Javascript for example only supports printing pages rudimentarily with the window.print method. As @Prutswonder suggested creating a PDF from the webpage probably is the most sophisticated way of doing this (other than supplying PDF documentation in the first place). However, this is not as trivial as one might think. Here's a link that has a description of an all open source Java class to create PDFs from HTML: http://www.javaworld.com/javaworld/jw-04-2006/jw-0410-html.html .

Obviously once you have created a PDF with A4 proportions printing it will result in a clean A4 print of your page. Whether that's worth the time investment is another question.

jQuery: find element by text

Yes, use the jQuery contains selector.

JSON Invalid UTF-8 middle byte

This awnser solved my problem. Below is a copy of it:

Make sure to start you JVM with -Dfile.encoding=UTF-8. You JVM defaults to the operating system charset

This is a JVM argument which could be added, for example, either to JBoss standalone or JBoss running from Eclipse.

In my case, this problem happened isolatelly on only one of my team people's computer. All the others was working without this problem.

How do I install a custom font on an HTML site

For the best possible browser support, your CSS code should look like this :

@font-face {
  font-family: 'MyWebFont';
  src: url('webfont.eot'); /* IE9 Compat Modes */
  src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('webfont.woff2') format('woff2'), /* Super Modern Browsers */
       url('webfont.woff') format('woff'), /* Pretty Modern Browsers */
       url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
       url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}

body {
  font-family: 'MyWebFont', Fallback, sans-serif;
}

For more info, see the article Using @font-face at CSS-tricks.com.

Fatal error: "No Target Architecture" in Visual Studio

If you are building 32bit then make sure you don't have _WIN64 defined for your project.

WITH CHECK ADD CONSTRAINT followed by CHECK CONSTRAINT vs. ADD CONSTRAINT

The first syntax is redundant - the WITH CHECK is default for new constraints, and the constraint is turned on by default as well.

This syntax is generated by the SQL management studio when generating sql scripts -- I'm assuming it's some sort of extra redundancy, possibly to ensure the constraint is enabled even if the default constraint behavior for a table is changed.

IntelliJ: Error:java: error: release version 5 not supported

If you are using spring boot as a parent, you should set the java.version property, because this will automatically set the correct versions.

<properties>
   <java.version>11</java.version>
</properties>

The property defined in your own project overrides whatever is set in the parent pom. This overrides all needed properties to compile to the correct version.

Some information can be found here: https://www.baeldung.com/maven-java-version

Find location of a removable SD card

Here is the method I use to find a removable SD card. It's complex, and probably overkill for some situations, but it works on a wide variety of Android versions and device manufacturers that I've tested over the last few years. I don't know of any devices since API level 15 on which it doesn't find the SD card, if there is one mounted. It won't return false positives in most cases, especially if you give it the name of a known file to look for.

Please let me know if you run into any cases where it doesn't work.

import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.regex.Pattern;

public class SDCard {
    private static final String TAG = "SDCard";

    /** In some scenarios we can expect to find a specified file or folder on SD cards designed
     * to work with this app. If so, set KNOWNFILE to that filename. It will make our job easier.
     * Set it to null otherwise. */
    private static final String KNOWNFILE = null;

    /** Common paths for microSD card. **/
    private static String[] commonPaths = {
            // Some of these taken from
            // https://stackoverflow.com/questions/13976982/removable-storage-external-sdcard-path-by-manufacturers
            // These are roughly in order such that the earlier ones, if they exist, are more sure
            // to be removable storage than the later ones.
            "/mnt/Removable/MicroSD",
            "/storage/removable/sdcard1", // !< Sony Xperia Z1
            "/Removable/MicroSD", // Asus ZenPad C
            "/removable/microsd",
            "/external_sd", // Samsung
            "/_ExternalSD", // some LGs
            "/storage/extSdCard", // later Samsung
            "/storage/extsdcard", // Main filesystem is case-sensitive; FAT isn't.
            "/mnt/extsd", // some Chinese tablets, e.g. Zeki
            "/storage/sdcard1", // If this exists it's more likely than sdcard0 to be removable.
            "/mnt/extSdCard",
            "/mnt/sdcard/external_sd",
            "/mnt/external_sd",
            "/storage/external_SD",
            "/storage/ext_sd", // HTC One Max
            "/mnt/sdcard/_ExternalSD",
            "/mnt/sdcard-ext",

            "/sdcard2", // HTC One M8s
            "/sdcard1", // Sony Xperia Z
            "/mnt/media_rw/sdcard1",   // 4.4.2 on CyanogenMod S3
            "/mnt/sdcard", // This can be built-in storage (non-removable).
            "/sdcard",
            "/storage/sdcard0",
            "/emmc",
            "/mnt/emmc",
            "/sdcard/sd",
            "/mnt/sdcard/bpemmctest",
            "/mnt/external1",
            "/data/sdext4",
            "/data/sdext3",
            "/data/sdext2",
            "/data/sdext",
            "/storage/microsd" //ASUS ZenFone 2

            // If we ever decide to support USB OTG storage, the following paths could be helpful:
            // An LG Nexus 5 apparently uses usb://1002/UsbStorage/ as a URI to access an SD
            // card over OTG cable. Other models, like Galaxy S5, use /storage/UsbDriveA
            //        "/mnt/usb_storage",
            //        "/mnt/UsbDriveA",
            //        "/mnt/UsbDriveB",
    };

    /** Find path to removable SD card. */
    public static File findSdCardPath(Context context) {
        String[] mountFields;
        BufferedReader bufferedReader = null;
        String lineRead = null;

        /** Possible SD card paths */
        LinkedHashSet<File> candidatePaths = new LinkedHashSet<>();

        /** Build a list of candidate paths, roughly in order of preference. That way if
         * we can't definitively detect removable storage, we at least can pick a more likely
         * candidate. */

        // Could do: use getExternalStorageState(File path), with and without an argument, when
        // available. With an argument is available since API level 21.
        // This may not be necessary, since we also check whether a directory exists and has contents,
        // which would fail if the external storage state is neither MOUNTED nor MOUNTED_READ_ONLY.

        // I moved hard-coded paths toward the end, but we need to make sure we put the ones in
        // backwards order that are returned by the OS. And make sure the iterators respect
        // the order!
        // This is because when multiple "external" storage paths are returned, it's always (in
        // experience, but not guaranteed by documentation) with internal/emulated storage
        // first, removable storage second.

        // Add value of environment variables as candidates, if set:
        // EXTERNAL_STORAGE, SECONDARY_STORAGE, EXTERNAL_SDCARD_STORAGE
        // But note they are *not* necessarily *removable* storage! Especially EXTERNAL_STORAGE.
        // And they are not documented (API) features. Typically useful only for old versions of Android.

        String val = System.getenv("SECONDARY_STORAGE");
        if (!TextUtils.isEmpty(val)) addPath(val, null, candidatePaths);
        val = System.getenv("EXTERNAL_SDCARD_STORAGE");
        if (!TextUtils.isEmpty(val)) addPath(val, null, candidatePaths);

        // Get listing of mounted devices with their properties.
        ArrayList<File> mountedPaths = new ArrayList<>();
        try {
            // Note: Despite restricting some access to /proc (http://stackoverflow.com/a/38728738/423105),
            // Android 7.0 does *not* block access to /proc/mounts, according to our test on George's Alcatel A30 GSM.
            bufferedReader = new BufferedReader(new FileReader("/proc/mounts"));

            // Iterate over each line of the mounts listing.
            while ((lineRead = bufferedReader.readLine()) != null) {
                Log.d(TAG, "\nMounts line: " + lineRead);
                mountFields = lineRead.split(" ");

                // columns: device, mountpoint, fs type, options... Example:
                // /dev/block/vold/179:97 /storage/sdcard1 vfat rw,dirsync,nosuid,nodev,noexec,relatime,uid=1000,gid=1015,fmask=0002,dmask=0002,allow_utime=0020,codepage=cp437,iocharset=iso8859-1,shortname=mixed,utf8,errors=remount-ro 0 0
                String device = mountFields[0], path = mountFields[1], fsType = mountFields[2];

                // The device, path, and fs type must conform to expected patterns.
                if (!(devicePattern.matcher(device).matches() &&
                        pathPattern.matcher(path).matches() &&
                        fsTypePattern.matcher(fsType).matches()) ||
                        // mtdblock is internal, I'm told.
                        device.contains("mtdblock") ||
                        // Check for disqualifying patterns in the path.
                        pathAntiPattern.matcher(path).matches()) {
                    // If this mounts line fails our tests, skip it.
                    continue;
                }

                // TODO maybe: check options to make sure it's mounted RW?
                // The answer at http://stackoverflow.com/a/13648873/423105 does.
                // But it hasn't seemed to be necessary so far in my testing.

                // This line met the criteria so far, so add it to candidate list.
                addPath(path, null, mountedPaths);
            }
        } catch (IOException ignored) {
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ignored) {
                }
            }
        }

        // Append the paths from mount table to candidate list, in reverse order.
        if (!mountedPaths.isEmpty()) {
            // See https://stackoverflow.com/a/5374346/423105 on why the following is necessary.
            // Basically, .toArray() needs its parameter to know what type of array to return.
            File[] mountedPathsArray = mountedPaths.toArray(new File[mountedPaths.size()]);
            addAncestors(candidatePaths, mountedPathsArray);
        }

        // Add hard-coded known common paths to candidate list:
        addStrings(candidatePaths, commonPaths);

        // If the above doesn't work we could try the following other options, but in my experience they
        // haven't added anything helpful yet.

        // getExternalFilesDir() and getExternalStorageDirectory() typically something app-specific like
        //   /storage/sdcard1/Android/data/com.mybackuparchives.android/files
        // so we want the great-great-grandparent folder.

        // This may be non-removable.
        Log.d(TAG, "Environment.getExternalStorageDirectory():");
        addPath(null, ancestor(Environment.getExternalStorageDirectory()), candidatePaths);

        // Context.getExternalFilesDirs() is only available from API level 19. You can use
        // ContextCompat.getExternalFilesDirs() on earlier APIs, but it only returns one dir anyway.
        Log.d(TAG, "context.getExternalFilesDir(null):");
        addPath(null, ancestor(context.getExternalFilesDir(null)), candidatePaths);

        // "Returns absolute paths to application-specific directories on all external storage
        // devices where the application can place persistent files it owns."
        // We might be able to use these to deduce a higher-level folder that isn't app-specific.
        // Also, we apparently have to call getExternalFilesDir[s](), at least in KITKAT+, in order to ensure that the
        // "external files" directory exists and is available.
        Log.d(TAG, "ContextCompat.getExternalFilesDirs(context, null):");
        addAncestors(candidatePaths, ContextCompat.getExternalFilesDirs(context, null));
        // Very similar results:
        Log.d(TAG, "ContextCompat.getExternalCacheDirs(context):");
        addAncestors(candidatePaths, ContextCompat.getExternalCacheDirs(context));

        // TODO maybe: use getExternalStorageState(File path), with and without an argument, when
        // available. With an argument is available since API level 21.
        // This may not be necessary, since we also check whether a directory exists,
        // which would fail if the external storage state is neither MOUNTED nor MOUNTED_READ_ONLY.

        // A "public" external storage directory. But in my experience it doesn't add anything helpful.
        // Note that you can't pass null, or you'll get an NPE.
        final File publicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
        // Take the parent, because we tend to get a path like /pathTo/sdCard/Music.
        addPath(null, publicDirectory.getParentFile(), candidatePaths);
        // EXTERNAL_STORAGE: may not be removable.
        val = System.getenv("EXTERNAL_STORAGE");
        if (!TextUtils.isEmpty(val)) addPath(val, null, candidatePaths);

        if (candidatePaths.isEmpty()) {
            Log.w(TAG, "No removable microSD card found.");
            return null;
        } else {
            Log.i(TAG, "\nFound potential removable storage locations: " + candidatePaths);
        }

        // Accept or eliminate candidate paths if we can determine whether they're removable storage.
        // In Lollipop and later, we can check isExternalStorageRemovable() status on each candidate.
        if (Build.VERSION.SDK_INT >= 21) {
            Iterator<File> itf = candidatePaths.iterator();
            while (itf.hasNext()) {
                File dir = itf.next();
                // handle illegalArgumentException if the path is not a valid storage device.
                try {
                    if (Environment.isExternalStorageRemovable(dir)
                        // && containsKnownFile(dir)
                            ) {
                        Log.i(TAG, dir.getPath() + " is removable external storage");
                        return dir;
                    } else if (Environment.isExternalStorageEmulated(dir)) {
                        Log.d(TAG, "Removing emulated external storage dir " + dir);
                        itf.remove();
                    }
                } catch (IllegalArgumentException e) {
                    Log.d(TAG, "isRemovable(" + dir.getPath() + "): not a valid storage device.", e);
                }
            }
        }

        // Continue trying to accept or eliminate candidate paths based on whether they're removable storage.
        // On pre-Lollipop, we only have singular externalStorage. Check whether it's removable.
        if (Build.VERSION.SDK_INT >= 9) {
            File externalStorage = Environment.getExternalStorageDirectory();
            Log.d(TAG, String.format(Locale.ROOT, "findSDCardPath: getExternalStorageDirectory = %s", externalStorage.getPath()));
            if (Environment.isExternalStorageRemovable()) {
                // Make sure this is a candidate.
                // TODO: Does this contains() work? Should we be canonicalizing paths before comparing?
                if (candidatePaths.contains(externalStorage)
                    // && containsKnownFile(externalStorage)
                        ) {
                    Log.d(TAG, "Using externalStorage dir " + externalStorage);
                    return externalStorage;
                }
            } else if (Build.VERSION.SDK_INT >= 11 && Environment.isExternalStorageEmulated()) {
                Log.d(TAG, "Removing emulated external storage dir " + externalStorage);
                candidatePaths.remove(externalStorage);
            }
        }

        // If any directory contains our special test file, consider that the microSD card.
        if (KNOWNFILE != null) {
            for (File dir : candidatePaths) {
                Log.d(TAG, String.format(Locale.ROOT, "findSdCardPath: Looking for known file in candidate path, %s", dir));
                if (containsKnownFile(dir)) return dir;
            }
        }

        // If we don't find the known file, still try taking the first candidate.
        if (!candidatePaths.isEmpty()) {
            Log.d(TAG, "No definitive path to SD card; taking the first realistic candidate.");
            return candidatePaths.iterator().next();
        }

        // If no reasonable path was found, give up.
        return null;
    }

    /** Add each path to the collection. */
    private static void addStrings(LinkedHashSet<File> candidatePaths, String[] newPaths) {
        for (String path : newPaths) {
            addPath(path, null, candidatePaths);
        }
    }

    /** Add ancestor of each File to the collection. */
    private static void addAncestors(LinkedHashSet<File> candidatePaths, File[] files) {
        for (int i = files.length - 1; i >= 0; i--) {
            addPath(null, ancestor(files[i]), candidatePaths);
        }
    }

    /**
     * Add a new candidate directory path to our list, if it's not obviously wrong.
     * Supply path as either String or File object.
     * @param strNew path of directory to add (or null)
     * @param fileNew directory to add (or null)
     */
    private static void addPath(String strNew, File fileNew, Collection<File> paths) {
        // If one of the arguments is null, fill it in from the other.
        if (strNew == null) {
            if (fileNew == null) return;
            strNew = fileNew.getPath();
        } else if (fileNew == null) {
            fileNew = new File(strNew);
        }

        if (!paths.contains(fileNew) &&
                // Check for paths known not to be removable SD card.
                // The antipattern check can be redundant, depending on where this is called from.
                !pathAntiPattern.matcher(strNew).matches()) {

            // Eliminate candidate if not a directory or not fully accessible.
            if (fileNew.exists() && fileNew.isDirectory() && fileNew.canExecute()) {
                Log.d(TAG, "  Adding candidate path " + strNew);
                paths.add(fileNew);
            } else {
                Log.d(TAG, String.format(Locale.ROOT, "  Invalid path %s: exists: %b isDir: %b canExec: %b canRead: %b",
                        strNew, fileNew.exists(), fileNew.isDirectory(), fileNew.canExecute(), fileNew.canRead()));
            }
        }
    }

    private static final String ANDROID_DIR = File.separator + "Android";

    private static File ancestor(File dir) {
        // getExternalFilesDir() and getExternalStorageDirectory() typically something app-specific like
        //   /storage/sdcard1/Android/data/com.mybackuparchives.android/files
        // so we want the great-great-grandparent folder.
        if (dir == null) {
            return null;
        } else {
            String path = dir.getAbsolutePath();
            int i = path.indexOf(ANDROID_DIR);
            if (i == -1) {
                return dir;
            } else {
                return new File(path.substring(0, i));
            }
        }
    }

    /** Returns true iff dir contains the special test file.
     * Assumes that dir exists and is a directory. (Is this a necessary assumption?) */
    private static boolean containsKnownFile(File dir) {
        if (KNOWNFILE == null) return false;

        File knownFile = new File(dir, KNOWNFILE);
        return knownFile.exists();
    }

    private static Pattern
            /** Pattern that SD card device should match */
            devicePattern = Pattern.compile("/dev/(block/.*vold.*|fuse)|/mnt/.*"),
    /** Pattern that SD card mount path should match */
    pathPattern = Pattern.compile("/(mnt|storage|external_sd|extsd|_ExternalSD|Removable|.*MicroSD).*",
            Pattern.CASE_INSENSITIVE),
    /** Pattern that the mount path should not match.
     * 'emulated' indicates an internal storage location, so skip it.
     * 'asec' is an encrypted package file, decrypted and mounted as a directory. */
    pathAntiPattern = Pattern.compile(".*(/secure|/asec|/emulated).*"),
    /** These are expected fs types, including vfat. tmpfs is not OK.
     * fuse can be removable SD card (as on Moto E or Asus ZenPad), or can be internal (Huawei G610). */
    fsTypePattern = Pattern.compile(".*(fat|msdos|ntfs|ext[34]|fuse|sdcard|esdfs).*");
}

P.S.

  • Don't forget <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> in the manifest. And at API level 23 and higher, make sure to use checkSelfPermission / requestPermissions.
  • Set KNOWNFILE="myappfile" if there's a file or folder you expect to find on the SD card. That makes detection more accurate.
  • Obviously you'll want to cache the value of findSdCardPath(), rather than recomputing it every time you need it.
  • There's a bunch of logging (Log.d()) in the above code. It helps diagnose any cases where the right path isn't found. Comment it out if you don't want logging.

"No such file or directory" error when executing a binary

I also had problems because my program interpreter was /lib/ld-linux.so.2 however it was on an embedded device, so I solved the problem by asking gcc to use ls-uClibc instead as follows:

-Wl,--dynamic-linker=/lib/ld-uClibc.so.0

What does an exclamation mark before a cell reference mean?

If you use that forumla in the name manager you are creating a dynamic range which uses "this sheet" in place of a specific sheet.

As Jerry says, Sheet1!A1 refers to cell A1 on Sheet1. If you create a named range and omit the Sheet1 part you will reference cell A1 on the currently active sheet. (omitting the sheet reference and using it in a cell formula will error).

edit: my bad, I was using $A$1 which will lock it to the A1 cell as above, thanks pnuts :p

SQL Call Stored Procedure for each Row without using a cursor

DELIMITER //

CREATE PROCEDURE setFakeUsers (OUT output VARCHAR(100))
BEGIN

    -- define the last customer ID handled
    DECLARE LastGameID INT;
    DECLARE CurrentGameID INT;
    DECLARE userID INT;

    SET @LastGameID = 0; 

    -- define the customer ID to be handled now

    SET @userID = 0;

    -- select the next game to handle    
    SELECT @CurrentGameID = id
    FROM online_games
    WHERE id > LastGameID
    ORDER BY id LIMIT 0,1;

    -- as long as we have customers......    
    WHILE (@CurrentGameID IS NOT NULL) 
    DO
        -- call your sproc

        -- set the last customer handled to the one we just handled
        SET @LastGameID = @CurrentGameID;
        SET @CurrentGameID = NULL;

        -- select the random bot
        SELECT @userID = userID
        FROM users
        WHERE FIND_IN_SET('bot',baseInfo)
        ORDER BY RAND() LIMIT 0,1;

        -- update the game
        UPDATE online_games SET userID = @userID WHERE id = @CurrentGameID;

        -- select the next game to handle    
        SELECT @CurrentGameID = id
         FROM online_games
         WHERE id > LastGameID
         ORDER BY id LIMIT 0,1;
    END WHILE;
    SET output = "done";
END;//

CALL setFakeUsers(@status);
SELECT @status;

How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?

tv_nsec is the sleep time in nanoseconds. 500000us = 500000000ns, so you want:

nanosleep((const struct timespec[]){{0, 500000000L}}, NULL);

PDO error message?

Try this instead:

print_r($sth->errorInfo());

Add this before your prepare:

$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );

This will change the PDO error reporting type and cause it to emit a warning whenever there is a PDO error. It should help you track it down, although your errorInfo should have bet set.

Use dynamic variable names in `dplyr`

In the new release of dplyr (0.6.0 awaiting in April 2017), we can also do an assignment (:=) and pass variables as column names by unquoting (!!) to not evaluate it

 library(dplyr)
 multipetalN <- function(df, n){
      varname <- paste0("petal.", n)
      df %>%
         mutate(!!varname := Petal.Width * n)
 }

 data(iris)
 iris1 <- tbl_df(iris)
 iris2 <- tbl_df(iris)
 for(i in 2:5) {
     iris2 <- multipetalN(df=iris2, n=i)
 }   

Checking the output based on @MrFlick's multipetal applied on 'iris1'

identical(iris1, iris2)
#[1] TRUE

Set auto height and width in CSS/HTML for different screen sizes

///UPDATED DEMO 2 WATCH SOLUTION////

I hope that is the solution you're looking for! DEMO1 DEMO2

With that solution the only scrollbar in the page is on your contents section in the middle! In that section build your structure with a sidebar or whatever you want!

You can do that with that code here:

<div class="navTop">
<h1>Title</h1>
    <nav>Dynamic menu</nav>
</div>
<div class="container">
    <section>THE CONTENTS GOES HERE</section>
</div>
<footer class="bottomFooter">
    Footer
</footer>

With that css:

.navTop{
width:100%;
border:1px solid black;
float:left;
}
.container{
width:100%;
float:left;
overflow:scroll;
}
.bottomFooter{
float:left;
border:1px solid black;
width:100%;
}

And a bit of jquery:

$(document).ready(function() {
  function setHeight() {
    var top = $('.navTop').outerHeight();
    var bottom = $('footer').outerHeight();
    var totHeight = $(window).height();
    $('section').css({ 
      'height': totHeight - top - bottom + 'px'
    });
  }

  $(window).on('resize', function() { setHeight(); });
  setHeight();
});

DEMO 1

If you don't want jquery

<div class="row">
    <h1>Title</h1>
    <nav>NAV</nav>
</div>

<div class="row container">
    <div class="content">
        <div class="sidebar">
            SIDEBAR
        </div>
        <div class="contents">
            CONTENTS
        </div>
    </div>
    <footer>Footer</footer>
</div>

CSS

*{
margin:0;padding:0;    
}
html,body{
height:100%;
width:100%;
}
body{
display:table;
}
.row{
width: 100%;
background: yellow;
display:table-row;
}
.container{
background: pink;
height:100%; 
}
.content {
display: block;
overflow:auto;
height:100%;
padding-bottom: 40px;
box-sizing: border-box;
}
footer{ 
position: fixed; 
bottom: 0; 
left: 0; 
background: yellow;
height: 40px;
line-height: 40px;
width: 100%;
text-align: center;
}
.sidebar{
float:left;
background:green;
height:100%;
width:10%;
}
.contents{
float:left;
background:red;
height:100%;
width:90%;
overflow:auto;
}

DEMO 2

How to add/subtract dates with JavaScript?

The JavaScript Date object can help here.

The first step is to convert those strings to Date instances. That's easily done:

var str = "06/07/2012"; // E.g., "mm/dd/yyyy";
var dt = new Date(parseInt(str.substring(6), 10),        // Year
                  parseInt(str.substring(0, 2), 10) - 1, // Month (0-11)
                  parseInt(str.substring(3, 5), 10));    // Day

Then you can do all sorts of useful calculations. JavaScript dates understand leap years and such. They use an idealized concept of "day" which is exactly 86,400 seconds long. Their underlying value is the number of milliseconds since The Epoch (midnight, Jan 1st, 1970); it can be a negative number for dates prior to The Epoch.

More on the MDN page on Date.

You might also consider using a library like MomentJS, which will help with parsing, doing date math, formatting...

Can "git pull --all" update all my local branches?

There are plenty of acceptable answers here, but some of the plumbing may be be a little opaque to the uninitiated. Here's a much simpler example that can easily be customized:

$ cat ~/bin/git/git-update-all
#!/bin/bash
# Update all local branches, checking out each branch in succession.
# Eventually returns to the original branch. Use "-n" for dry-run.
git_update_all() {
  local run br
  br=$(git name-rev --name-only HEAD 2>/dev/null)
  [ "$1" = "-n" ] && shift && run=echo

  for x in $( git branch | cut -c3- ) ; do
     $run git checkout $x && $run git pull --ff-only || return 2
  done

  [ ${#br} -gt 0 ] && $run git checkout "$br"
}

git_update_all "$@"

If you add ~/bin/git to your PATH (assuming the file is ~/bin/git/git-update-all), you can just run:

$ git update-all

Command failed due to signal: Segmentation fault: 11

In my case, I forgot to remove a 'colorLiteral' (which is not assigning to any property or not passing as a method parameter) in my source code that's why the compiler was not able to compile all swift files. I just removed the 'colorLiteral' and its working fine as expected.

Running script upon login mac

tl;dr: use OSX's native process launcher and manager, launchd.

To do so, make a launchctl daemon. You'll have full control over all aspects of the script. You can run once or keep alive as a daemon. In most cases, this is the way to go.

  1. Create a .plist file according to the instructions in the Apple Dev docs here or more detail below.
  2. Place in ~/Library/LaunchAgents
  3. Log in (or run manually via launchctl load [filename.plist])

For more on launchd, the wikipedia article is quite good and describes the system and its advantages over other older systems.


Here's the specific plist file to run a script at login.

Updated 2017/09/25 for OSX El Capitan and newer (credit to José Messias Jr):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
   <key>Label</key>
   <string>com.user.loginscript</string>
   <key>ProgramArguments</key>
   <array><string>/path/to/executable/script.sh</string></array>
   <key>RunAtLoad</key>
   <true/>
</dict>
</plist>

Replace the <string> after the Program key with your desired command (note that any script referenced by that command must be executable: chmod a+x /path/to/executable/script.sh to ensure it is for all users).

Save as ~/Library/LaunchAgents/com.user.loginscript.plist

Run launchctl load ~/Library/LaunchAgents/com.user.loginscript.plist and log out/in to test (or to test directly, run launchctl start com.user.loginscript)

Tail /var/log/system.log for error messages.

The key is that this is a User-specific launchd entry, so it will be run on login for the given user. System-specific launch daemons (placed in /Library/LaunchDaemons) are run on boot.

If you want a script to run on login for all users, I believe LoginHook is your only option, and that's probably the reason it exists.

Change the color of a bullet in a html list?

You can use Jquery if you have lots of pages and don't need to go and edit the markup your self.

here is a simple example:

$("li").each(function(){
var content = $(this).html();
var myDiv = $("<div />")
myDiv.css("color", "red"); //color of text.
myDiv.html(content);
$(this).html(myDiv).css("color", "yellow"); //color of bullet
});

Interpreting "condition has length > 1" warning from `if` function

Use lapply function after creating your function normally.

lapply(x="your input", fun="insert your function name")

lapply gives a list so use unlist function to take them out of the function

unlist(lapply(a,w))

Android appcompat v7:23

Original answer:

I too tried to change the support library to "23". When I changed the targetSdkVersion to 23, Android Studio reported the following error:

This support library should not use a lower version (22) than the targetSdkVersion (23)

I simply changed:

compile 'com.android.support:appcompat-v7:23.0.0'

to

compile 'com.android.support:appcompat-v7:+'

Although this fixed my issue, you should not use dynamic versions. After a few hours the new support repository was available and it is currently 23.0.1.


Pro tip:

You can use double quotes and create a ${supportLibVersion} variable for simplicity. Example:

ext {
    supportLibVersion = '23.1.1'
}

compile "com.android.support:appcompat-v7:${supportLibVersion}"
compile "com.android.support:design:${supportLibVersion}"
compile "com.android.support:palette-v7:${supportLibVersion}"
compile "com.android.support:customtabs:${supportLibVersion}"
compile "com.android.support:gridlayout-v7:${supportLibVersion}"

source: https://twitter.com/manidesto/status/669195097947377664

Force overwrite of local file with what's in origin repo?

Full sync has few tasks:

  • reverting changes
  • removing new files
  • get latest from remote repository

git reset HEAD --hard

git clean -f

git pull origin master

Or else, what I prefer is that, I may create a new branch with the latest from the remote using:

git checkout origin/master -b <new branch name>

origin is my remote repository reference, and master is my considered branch name. These may different from yours.

How can I get the last 7 characters of a PHP string?

umh.. like that?

$newstring = substr($dynamicstring, -7);

Is there a way to remove the separator line from a UITableView?

In your viewDidLoad:

self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)])
{
    [self.tableView setSeparatorInset:UIEdgeInsetsZero];
}

JavaScript, getting value of a td with id name

To get the text content

document.getElementById ( "tdid" ).innerText

or

document.getElementById ( "tdid" ).textContent

var tdElem = document.getElementById ( "tdid" );
var tdText = tdElem.innerText | tdElem.textContent;

If you can use jQuery then you can use

$("#tdid").text();

To get the HTML content

var tdElem = document.getElementById ( "tdid" );
var tdText = tdElem.innerHTML;

in jQuery

$("#tdid").html();

MySQL Daemon Failed to Start - centos 6

 /etc/init.d/mysqld stop

 mysqld_safe --skip-grant-tables & mysql_upgrade

 /etc/init.d/mysqld stop

 /etc/init.d/mysqld start

What is a magic number, and why is it bad?

What about return variables?

I specially find it challenging when implementing stored procedures.

Imagine the next stored procedure (wrong syntax, I know, just to show an example):

int procGetIdCompanyByName(string companyName);

It return the Id of the company if it exists in a particular table. Otherwise, it returns -1. Somehow it's a magic number. Some of the recommendations I've read so far says that I'll really have to do design somthing like that:

int procGetIdCompanyByName(string companyName, bool existsCompany);

By the way, what should it return if the company does not exists? Ok: it will set existesCompany as false, but also will return -1.

Antoher option is to make two separate functions:

bool procCompanyExists(string companyName);
int procGetIdCompanyByName(string companyName);

So a pre-condition for the second stored procedure is that company exists.

But i'm afraid of concurrency, because in this system, a company can be created by another user.

The bottom line by the way is: what do you think about using that kind of "magic numbers" that are relatively known and safe to tell that something is unsuccessful or that something does not exists?

Visual Studio Code: Auto-refresh file changes

{
    "files.useExperimentalFileWatcher" : true
}

in Code -> Preferences -> Settings

Tested with Visual Studio Code Version 1.26.1 on mac and win

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

Also, we can use it following ways

To get only first

 $cat_details = DB::table('an_category')->where('slug', 'people')->first();

To get by limit and offset

$top_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(0)->orderBy('id', 'DESC')->get();
$remaining_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(30)->orderBy('id', 'DESC')->get();

How to catch exception output from Python subprocess.check_output()?

Based on the answer of @macetw I print the exception directly to stderr in a decorator.

Python 3

from functools import wraps
from sys import stderr
from traceback import format_exc
from typing import Callable, Collection, Any, Mapping


def force_error_output(func: Callable):
    @wraps(func)
    def forced_error_output(*args: Collection[Any], **kwargs: Mapping[str, Any]):
        nonlocal func

        try:
            func(*args, **kwargs)
        except Exception as exception:
            stderr.write(format_exc())
            stderr.write("\n")
            stderr.flush()

            raise exception

    return forced_error_output

Python 2

from functools import wraps
from sys import stderr
from traceback import format_exc


def force_error_output(func):
    @wraps(func)
    def forced_error_output(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except Exception as exception:
            stderr.write(format_exc())
            stderr.write("\n")
            stderr.flush()

            raise exception

    return forced_error_output

Then in your worker just use the decorator

@force_error_output
def da_worker(arg1: int, arg2: str):
    pass

How can I remove duplicate rows?

By useing below query we can able to delete duplicate records based on the single column or multiple column. below query is deleting based on two columns. table name is: testing and column names empno,empname

DELETE FROM testing WHERE empno not IN (SELECT empno FROM (SELECT empno, ROW_NUMBER() OVER (PARTITION BY empno ORDER BY empno) 
AS [ItemNumber] FROM testing) a WHERE ItemNumber > 1)
or empname not in
(select empname from (select empname,row_number() over(PARTITION BY empno ORDER BY empno) 
AS [ItemNumber] FROM testing) a WHERE ItemNumber > 1)

python convert list to dictionary

Using the usual grouper recipe, you could do:

Python 2:

d = dict(itertools.izip_longest(*[iter(l)] * 2, fillvalue=""))

Python 3:

d = dict(itertools.zip_longest(*[iter(l)] * 2, fillvalue=""))

Class JavaLaunchHelper is implemented in two places

You can find all the details here:

  • IDEA-170117 "objc: Class JavaLaunchHelper is implemented in both ..." warning in Run consoles

It's the old bug in Java on Mac that got triggered by the Java Agent being used by the IDE when starting the app. This message is harmless and is safe to ignore. Oracle developer's comment:

The message is benign, there is no negative impact from this problem since both copies of that class are identical (compiled from the exact same source). It is purely a cosmetic issue.

The problem is fixed in Java 9 and in Java 8 update 152.

If it annoys you or affects your apps in any way (it shouldn't), the workaround for IntelliJ IDEA is to disable idea_rt launcher agent by adding idea.no.launcher=true into idea.properties (Help | Edit Custom Properties...). The workaround will take effect on the next restart of the IDE.

I don't recommend disabling IntelliJ IDEA launcher agent, though. It's used for such features as graceful shutdown (Exit button), thread dumps, workarounds a problem with too long command line exceeding OS limits, etc. Losing these features just for the sake of hiding the harmless message is probably not worth it, but it's up to you.

How to do a deep comparison between 2 objects with lodash?

This is my solution to the problem

const _ = require('lodash');

var objects = [{ 'x': 1, 'y': 2, 'z':3, a:{b:1, c:2, d:{n:0}}, p:[1, 2, 3]  }, { 'x': 2, 'y': 1, z:3, a:{b:2, c:2,d:{n:1}}, p:[1,3], m:3  }];

const diffFn=(a,b, path='')=>_.reduce(a, function(result, value, key) {

    if(_.isObjectLike(value)){
      if(_.isEqual(value, b[key])){
        return result;
      }else{

return result.concat(diffFn(value, b[key], path?(`${path}.${key}`):key))
      }
    }else{
return _.isEqual(value, b[key]) ?
        result : result.concat(path?(`${path}.${key}`):key);
    }
    
}, []);

const diffKeys1=diffFn(objects[0], objects[1])
const diffKeys2=diffFn(objects[1], objects[0])
const diffKeys=_.union(diffKeys1, diffKeys2)
const res={};

_.forEach(diffKeys, (key)=>_.assign(res, {[key]:{ old: _.get(objects[0], key), new:_.get(objects[1], key)} }))

res
/*
Returns
{
  x: { old: 1, new: 2 },
  y: { old: 2, new: 1 },
  'a.b': { old: 1, new: 2 },
  'a.d.n': { old: 0, new: 1 },
  'p.1': { old: 2, new: 3 },
  'p.2': { old: 3, new: undefined },
  m: { old: undefined, new: 3 }
}
*/

Creating columns in listView and add items

            listView1.View = View.Details;
        listView1.Columns.Add("Target No.", 83, HorizontalAlignment.Center);
        listView1.Columns.Add("   Range   ", 100, HorizontalAlignment.Center);
        listView1.Columns.Add(" Azimuth ", 100, HorizontalAlignment.Center);     

i also had same problem .. i drag column to left .. but now ok .. so let's say i have 283*196 size of listview ..... We declared in the column width -2 for auto width .. For fitting in the listview ,we can divide listview width into 3 parts (83,100,100) ...

The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM'

Not this exact problem, but this is the top result when googling for almost the exact same error:

If you see this problem calling a WCF Service hosted on the same machine, you may need to populate the BackConnectionHostNames registry key

  1. In regedit, locate and then click the following registry subkey: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0
  2. Right-click MSV1_0, point to New, and then click Multi-String Value.
  3. In the Name column, type BackConnectionHostNames, and then press ENTER.
  4. Right-click BackConnectionHostNames, and then click Modify. In the Value data box, type the CNAME or the DNS alias, that is used for the local shares on the computer, and then click OK.
    • Type each host name on a separate line.

See Calling WCF service hosted in IIS on the same machine as client throws authentication error for details.

to_string is not a member of std, says g++ (mingw)

to_string() is only present in c++11 so if c++ version is less use some alternate methods such as sprintf or ostringstream

round() doesn't seem to be rounding properly

I would avoid relying on round() at all in this case. Consider

print(round(61.295, 2))
print(round(1.295, 2))

will output

61.3
1.29

which is not a desired output if you need solid rounding to the nearest integer. To bypass this behavior go with math.ceil() (or math.floor() if you want to round down):

from math import ceil
decimal_count = 2
print(ceil(61.295 * 10 ** decimal_count) / 10 ** decimal_count)
print(ceil(1.295 * 10 ** decimal_count) / 10 ** decimal_count)

outputs

61.3
1.3

Hope that helps.

Python DNS module import error

In my case, I hava writen the code in the file named "dns.py", it's conflict for the package, I have to rename the script filename.

Convert laravel object to array

You need to iterate over the array

for ($i = 0, $c = count($array); $i < $c; ++$i) {
    $array[$i] = (array) $array[$i];
}

ans use (array) conversion because you have array of objects of Std class and not object itself

Example:

$users = DB::table('users')->get();

var_dump($users);

echo "<br /><br />";

for ($i = 0, $c = count($users); $i < $c; ++$i) {
    $users[$i] = (array) $users[$i];
}
var_dump($users);
exit;

Output for this is:

array(1) { [0]=> object(stdClass)#258 (8) { ["id"]=> int(1) ["user_name"]=> string(5) "admin" ["email"]=> string(11) "admin@admin" ["passwd"]=> string(60) "$2y$10$T/0fW18gPGgz0CILTy2hguxNpcNjYZHsTyf5dvpor9lYMw/mtKYfi" ["balance"]=> string(4) "0.00" ["remember_token"]=> string(60) "moouXQOJFhtxkdl9ClEXYh9ioBSsRp28WZZbLPkJskcCr0325TyrxDK4al5H" ["created_at"]=> string(19) "2014-10-01 12:00:00" ["updated_at"]=> string(19) "2014-09-27 12:20:54" } }

array(1) { [0]=> array(8) { ["id"]=> int(1) ["user_name"]=> string(5) "admin" ["email"]=> string(11) "admin@admin" ["passwd"]=> string(60) "$2y$10$T/0fW18gPGgz0CILTy2hguxNpcNjYZHsTyf5dvpor9lYMw/mtKYfi" ["balance"]=> string(4) "0.00" ["remember_token"]=> string(60) "moouXQOJFhtxkdl9ClEXYh9ioBSsRp28WZZbLPkJskcCr0325TyrxDK4al5H" ["created_at"]=> string(19) "2014-10-01 12:00:00" ["updated_at"]=> string(19) "2014-09-27 12:20:54" } } 

as expected. Object of stdClass has been converted to array.

Undefined or null for AngularJS

I asked the same question of the lodash maintainers a while back and they replied by mentioning the != operator can be used here:

if(newVal != null) {
  // newVal is defined
}

This uses JavaScript's type coercion to check the value for undefined or null.

If you are using JSHint to lint your code, add the following comment blocks to tell it that you know what you are doing - most of the time != is considered bad.

/* jshint -W116 */ 
if(newVal != null) {
/* jshint +W116 */
  // newVal is defined
}

How can I set the initial value of Select2 when using AJAX?

Hi was almost quitting this and go back to select 3.5.1. But finally I got the answer!

$('#test').select2({
    placeholder: "Select a Country",
    minimumResultsForSearch: 2,
    ajax: {
        url: '...',
        dataType: 'json',
        cache: false,
        data: function (params) {
                var queryParameters = {
                    q: params.term
                }
                return queryParameters;
        },
        processResults: function (data) {
            return {
                results: data.items
            };
        }
    }
});

var option1 = new Option("new",true, true);

$('#status').append(option1);

$('#status').trigger('change');

Just be sure that the new option is one of the select2 options. I get this by a json.

How to delete a row from GridView?

My solution:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    myobj.myconnection();// connection created
    string mystr = "Delete table_name where water_id= '" + GridView1.DataKeys[e.RowIndex].Value + "'";// query
    sqlcmd = new SqlCommand(mystr, myobj.mycon);
    sqlcmd.ExecuteNonQuery();
    fillgrid();
}

Difference between AutoPostBack=True and AutoPostBack=False?

There is one event which is default associate with any webcontrol. For example, in case of Button click event, in case of Check box CheckChangedEvent is there. So in case of AutoPostBack true these events are called by default and event handle at server side.

Importing larger sql files into MySQL

Since you state (in a clarification comment to another person's answer) that you are using MySQL Workbench, you could try using the "sql script" option there. This will avoid the need to use the commandline (although I agree with the other answer that it's good to climb up on that horse and learn to ride).

  1. In MySQL Workbench, go to File menu, then select "open script". This is probably going to take a long time and might even crash the app since it's not made to open things that are as big as what you describe.

  2. The better way is to use the commandline. Make sure you have MySQL client installed on your machine. This means the actual MySQL (not Workbench GUI or PhpMyAdmin or anything like that). Here is a link describing the command-line tool. Once you have that downloaded and installed, open a terminal window on your machine, and you have two choices for slurping data from your file system (such as in a backup file) up into your target database. One is to use 'source' command and the other is to use the < redirection operator.

Option 1: from the directory where your backup file is:

$mysql -u username -p -h hostname databasename < backupfile.sql

Option 2: from the directory where your backup file is:

$mysql -u username -p -h hostname
[enter your password]
> use databasename;
> source backupfile.sql

Obviously, both of these options require that you have a backup file that is SQL.

How to create full path with node's fs.mkdirSync?

Too many answers, but here's a solution without recursion that works by splitting the path and then left-to-right building it back up again

function mkdirRecursiveSync(path) {
    let paths = path.split(path.delimiter);
    let fullPath = '';
    paths.forEach((path) => {

        if (fullPath === '') {
            fullPath = path;
        } else {
            fullPath = fullPath + '/' + path;
        }

        if (!fs.existsSync(fullPath)) {
            fs.mkdirSync(fullPath);
        }
    });
};

For those concerned about windows vs Linux compatibility, simply replace the forward slash with double backslash '\' in both occurrence above but TBH we are talking about node fs not windows command line and the former is pretty forgiving and the above code will simply work on Windows and is more a complete solution cross platform.

How to pass command line arguments to a rake task

To run rake tasks with traditional arguments style:

rake task arg1 arg2

And then use:

task :task do |_, args|
  puts "This is argument 1: #{args.first}"
end

Add following patch of rake gem:

Rake::Application.class_eval do

  alias origin_top_level top_level

  def top_level
    @top_level_tasks = [top_level_tasks.join(' ')]
    origin_top_level
  end

  def parse_task_string(string) # :nodoc:
    parts = string.split ' '
    return parts.shift, parts
  end

end

Rake::Task.class_eval do

  def invoke(*args)
    invoke_with_call_chain(args, Rake::InvocationChain::EMPTY)
  end

end

PHP GuzzleHttp. How to make a post request with params?

$client = new \GuzzleHttp\Client();
$request = $client->post('http://demo.website.com/api', [
    'body' => json_encode($dataArray)
]);
$response = $request->getBody();

Add

openssl.cafile in php.ini file

ProgressDialog in AsyncTask

This question is already answered and most of the answers here are correct but they don't solve one major issue with config changes. Have a look at this article https://androidresearch.wordpress.com/2013/05/10/dealing-with-asynctask-and-screen-orientation/ if you would like to write a async task in a better way.

Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST

tl;dr

The other Answers are outmoded as of Java 8.

Instant                           // Represent a moment in UTC. 
.parse( "2013-09-29T18:46:19Z" )  // Parse text in standard ISO 8601 format where the `Z` means UTC, pronounces “Zulu”.
.atZone(                          // Adjust from UTC to a time zone. 
    ZoneId.of( "Asia/Kolkata" )
)                                 // Returns a `ZonedDateTime` object. 

ISO 8601

Your string format happens to comply with the ISO 8601 standard. This standard defines sensible formats for representing various date-time values as text.

java.time

The old java.util.Date/.Calendar and java.text.SimpleDateFormat classes have been supplanted by the java.time framework built into Java 8 and later. See Tutorial. Avoid the old classes as they have proven to be poorly designed, confusing, and troublesome.

Part of the poor design in the old classes has bitten you, where the toString method applies the JVM's current default time zone when generating a text representation of the date-time value that is actually in UTC (GMT); well-intentioned but confusing.

The java.time classes use ISO 8601 formats by default when parsing/generating textual representations of date-time values. So no need to specify a parsing pattern.

An Instant is a moment on the timeline in UTC.

Instant instant = Instant.parse( "2013-09-29T18:46:19Z" );

You can apply a time zone as needed to produce a ZonedDateTime object.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( zoneId );

Table of date-time types in Java, both modern and legacy

Need a row count after SELECT statement: what's the optimal SQL approach?

Approach 2 will always return a count that matches your result set.

I suggest you link the sub-query to your outer query though, to guarantee that the condition on your count matches the condition on the dataset.

SELECT 
  mt.my_row,
 (SELECT COUNT(mt2.my_row) FROM my_table mt2 WHERE mt2.foo = mt.foo) as cnt
FROM my_table mt
WHERE mt.foo = 'bar';

Custom Card Shape Flutter SDK

An Alternative Solution to the above

Card(
  shape: RoundedRectangleBorder(
     borderRadius: BorderRadius.only(topLeft: Radius.circular(20), topRight: Radius.circular(20))),
  color: Colors.white,
  child: ...
)

You can use BorderRadius.only() to customize the corners you wish to manage.

How do I prevent a form from being resized by the user?

Set the window start style as maximized. Then, hide the minimize and maximize buttons.

error C2039: 'string' : is not a member of 'std', header file problem

You need to have

#include <string>

in the header file too.The forward declaration on it's own doesn't do enough.

Also strongly consider header guards for your header files to avoid possible future problems as your project grows. So at the top do something like:

#ifndef THE_FILE_NAME_H
#define THE_FILE_NAME_H

/* header goes in here */

#endif

This will prevent the header file from being #included multiple times, if you don't have such a guard then you can have issues with multiple declarations.

Populating a razor dropdownlist from a List<object> in MVC

Something close to:

@Html.DropDownListFor(m => m.UserRole, 
   new SelectList(Model.Roles, "UserRoleId", "UserRole", Model.Roles.First().UserRoleId), 
   new { /* any html  attributes here */ }) 

You need a SelectList to populate the DropDownListFor. For any HTML attributes you need, you can add:

new { @class = "DropDown", @id = "dropdownUserRole" }

java.net.BindException: Address already in use: JVM_Bind <null>:80

PID 0 is the System Idle Process, which is surely not listening to port 80. How did you check which process was using the port?

You can use

netstat /nao | findstr "80"

to find the PID and check what process it is.

Copy data from one column to other column (which is in a different table)

I think that all previous answers are correct, this below code is very valid specially if you have to update multiple rows at once, note: it's PL/SQL

DECLARE
    CURSOR myCursor IS 
      Select contacts.BusinessCountry 
      From contacts c WHERE c.Key = t.Key;
    ---------------------------------------------------------------------
BEGIN
    FOR resultValue IN myCursor LOOP
        Update tblindiantime t
        Set CountryName=resultValue.BusinessCountry 
        where t.key=resultValue.key;
    END LOOP;
END;

I wish this could help.

How to check if object has any properties in JavaScript?

Very late answer, but this is how you could handle it with prototypes.

Array.prototype.Any = function(func) {
    return this.some(func || function(x) { return x });
}

Object.prototype.IsAny = function() {
    return Object.keys(this).Any();
}

How to find serial number of Android device?

There is an excellent post on the Android Developer's Blog discussing this.

It recommends against using TelephonyManager.getDeviceId() as it doesn't work on Android devices which aren't phones such as tablets, it requires the READ_PHONE_STATE permission and it doesn't work reliably on all phones.

Instead you could use one of the following:

  • Mac Address
  • Serial Number
  • ANDROID_ID

The post discusses the pros and cons of each and it's worth reading so you can work out which would be the best for your use.

How can I display the users profile pic using the facebook graph api?

The returned data is the binary data of the image type. If you use JavaScript to retrieve the user photo, please get the photo data as blob type in a XMLHttpRequest, and then retrieve the blob URL from the response. For your reference:

 var request = new XMLHttpRequest;
 var photoUri=config.endpoints.graphApiUri + "/v1.0/me/photo/$value";
 request.open("GET",photoUri);
 request.setRequestHeader("Authorization","Bearer "+token);
 request.responseType = "blob";
 request.onload = function (){
        if(request.readyState == 4 && request.status == 200){
               var image = document.createElement("img");
               var url = window.URL || window.webkitURL;
               var blobUrl = url.createObjectURL(request.response);
               image.src = blobUrl;
               document.getElementById("UserShow").appendChild(image);
        }
 };
 request.send(null); 

Switch statement fall-through...should it be allowed?

As with anything: if used with care, it can be an elegant tool.

However, I think the drawbacks more than justify not to use it, and finally not to allow it anymore (C#). Among the problems are:

  • it's easy to "forget" a break
  • it's not always obvious for code maintainers that an omitted break was intentional

Good use of a switch/case fall-through:

switch (x)
{
case 1:
case 2:
case 3:
 Do something
 break;
}

Baaaaad use of a switch/case fall-through:

switch (x)
{
case 1:
    Some code
case 2:
    Some more code
case 3:
    Even more code
    break;
}

This can be rewritten using if/else constructs with no loss at all in my opinion.

My final word: stay away from fall-through case labels as in the bad example, unless you are maintaining legacy code where this style is used and well understood.

@HostBinding and @HostListener: what do they do and what are they for?

// begginers
@Component({
  selector: 'custom-comp',
  template: ` <div class="my-class" (click)="onClick()">CLICK ME</div> `,
})
export class CustomComp {
  onClick = () => console.log('click event');
}

// pros
@Component({
  selector: 'custom-comp',
  template: ` CLICK ME `,
})
export class CustomComp {
  @HostBinding('class') class = 'my-class';
  @HostListener('click') onClick = () => console.log('click event');
}

// experts
@Component({
  selector: 'custom-comp',
  template: ` CLICK ME `,
  host: {
    class: 'my-class',
    '(click)': 'onClick()',
  },
})
export class CustomComp {}

------------------------------------------------
The 1st way will result in:
<custom-comp>
   <div class="my-class" (click)="onClick()">
      CLICK ME
   <div>
</custom-comp>

The last 2 ways will result in:
<custom-comp class="my-class" (click)="onClick()">
   CLICK ME
</custom-comp>

How to Generate Barcode using PHP and Display it as an Image on the same page

There is a library for this BarCode PHP. You just need to include a few files:

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

You can generate many types of barcodes, namely 1D or 2D. Add the required library:

require_once('class/BCGcode39.barcode.php');

Generate the colours:

// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);

After you have added all the codes, you will get this way:

Example

Since several have asked for an example here is what I was able to do to get it done

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

require_once('class/BCGcode128.barcode.php');

header('Content-Type: image/png');

$color_white = new BCGColor(255, 255, 255);

$code = new BCGcode128();
$code->parse('HELLO');

$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);

$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);

If you want to actually create the image file so you can save it then change

$drawing = new BCGDrawing('', $color_white);

to

$drawing = new BCGDrawing('image.png', $color_white);

Running AMP (apache mysql php) on Android

Here is the App Bit Web Server (PHP,MySQL,PMA)

It can run a variety of CMS like Wordpress, Joomla, Drupal, Prestashop, etc. Besides CMS can also run PHP frameworks like Code Igniter, YII, CakePHP, etc. It is the same as WAMP or LAMP or XAMPP on your computer or laptop, but this is for android devices with lighttpd instead of apache.

html select option separator

Instead of the regular hyphon I replaced it using a horizontal bar symbol from the extended character set, it won't look very nice if the user is in another country that replaces that character but works fine for me. There is a range of different chacters you could use for some great effects and there is no css involved.

<option value='-' disabled>----</option>

How to set the default value for radio buttons in AngularJS?

Set a default value for people with ngInit

<div ng-app>
    <div ng-init="people=1" />
        <input type="radio" ng-model="people" value="1"><label>1</label>
        <input type="radio" ng-model="people" value="2"><label>2</label>
        <input type="radio" ng-model="people" value="3"><label>3</label>
    <ul>
        <li>{{10*people}}€</li>
        <li>{{8*people}}€</li>
        <li>{{30*people}}€</li>
    </ul>
</div>

Demo: Fiddle

Undoing a git rebase

If you mess something up within a git rebase, e.g. git rebase --abort, while you have uncommitted files, they will be lost and git reflog will not help. This happened to me and you will need to think outside the box here. If you are lucky like me and use IntelliJ Webstorm then you can right-click->local history and can revert to a previous state of your file/folders no matter what mistakes you have done with versioning software. It is always good to have another failsafe running.

How to add new line in Markdown presentation?

Just add \ at the end of line. For example

one\
two

Will become

one
two

It's also better than two spaces because it's visible.

Can the :not() pseudo-class have multiple arguments?

I was having some trouble with this, and the "X:not():not()" method wasn't working for me.

I ended up resorting to this strategy:

INPUT {
    /* styles */
}
INPUT[type="radio"], INPUT[type="checkbox"] {
    /* styles that reset previous styles */
}

It's not nearly as fun, but it worked for me when :not() was being pugnacious. It's not ideal, but it's solid.

How do I include a JavaScript script file in Angular and call a function from that script?

Add external js file in index.html.

<script src="./assets/vendors/myjs.js"></script>

Here's myjs.js file :

var myExtObject = (function() {

    return {
      func1: function() {
        alert('function 1 called');
      },
      func2: function() {
        alert('function 2 called');
      }
    }

})(myExtObject||{})


var webGlObject = (function() { 
    return { 
      init: function() { 
        alert('webGlObject initialized');
      } 
    } 
})(webGlObject||{})

Then declare it is in component like below

demo.component.ts

declare var myExtObject: any;
declare var webGlObject: any;

constructor(){
    webGlObject.init();
}

callFunction1() {
    myExtObject.func1();
}

callFunction2() {
    myExtObject.func2();
}

demo.component.html

<div>
    <p>click below buttons for function call</p>
    <button (click)="callFunction1()">Call Function 1</button>
    <button (click)="callFunction2()">Call Function 2</button>
</div>

It's working for me...

LINQ order by null column where order is ascending and nulls should be last

I have another option in this situation. My list is objList, and I have to order but nulls must be in the end. my decision:

var newList = objList.Where(m=>m.Column != null)
                     .OrderBy(m => m.Column)
                     .Concat(objList.where(m=>m.Column == null));

Split a string by a delimiter in python

When you have two or more (in the example below there're three) elements in the string, then you can use comma to separate these items:

date, time, event_name = ev.get_text(separator='@').split("@")

After this line of code, the three variables will have values from three parts of the variable ev

So, if the variable ev contains this string and we apply separator '@':

Sa., 23. März@19:00@Klavier + Orchester: SPEZIAL

Then, after split operation the variable

  • date will have value "Sa., 23. März"
  • time will have value "19:00"
  • event_name will have value "Klavier + Orchester: SPEZIAL"

Oracle SQL Where clause to find date records older than 30 days

Use:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= TRUNC(SYSDATE) - 30

SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date that is 30 days previous including the current time.

Depending on your needs, you could also look at using ADD_MONTHS:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)

Aggregate / summarize multiple variables per group (e.g. sum, mean)

Using the data.table package, which is fast (useful for larger datasets)

https://github.com/Rdatatable/data.table/wiki

library(data.table)
df2 <- setDT(df1)[, lapply(.SD, sum), by=.(year, month), .SDcols=c("x1","x2")]
setDF(df2) # convert back to dataframe

Using the plyr package

require(plyr)
df2 <- ddply(df1, c("year", "month"), function(x) colSums(x[c("x1", "x2")]))

Using summarize() from the Hmisc package (column headings are messy in my example though)

# need to detach plyr because plyr and Hmisc both have a summarize()
detach(package:plyr)
require(Hmisc)
df2 <- with(df1, summarize( cbind(x1, x2), by=llist(year, month), FUN=colSums))

Python handling socket.error: [Errno 104] Connection reset by peer

"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur. (From other SO answer)

So you can't do anything about it, it is the issue of the server.

But you could use try .. except block to handle that exception:

from socket import error as SocketError
import errno

try:
    response = urllib2.urlopen(request).read()
except SocketError as e:
    if e.errno != errno.ECONNRESET:
        raise # Not error we are looking for
    pass # Handle error here.

Regex how to match an optional character

You can make the single letter optional by adding a ? after it as:

([A-Z]{1}?)

The quantifier {1} is redundant so you can drop it.

SQL conditional SELECT

You want the CASE statement:

SELECT
  CASE 
    WHEN @SelectField1 = 1 THEN Field1
    WHEN @SelectField2 = 1 THEN Field2
    ELSE NULL
  END AS NewField
FROM Table

EDIT: My example is for combining the two fields into one field, depending on the parameters supplied. It is a one-or-neither solution (not both). If you want the possibility of having both fields in the output, use Quassnoi's solution.

Using psql to connect to PostgreSQL in SSL mode

psql below 9.2 does not accept this URL-like syntax for options.

The use of SSL can be driven by the sslmode=value option on the command line or the PGSSLMODE environment variable, but the default being prefer, SSL connections will be tried first automatically without specifying anything.

Example with a conninfo string (updated for psql 8.4)

psql "sslmode=require host=localhost dbname=test"

Read the manual page for more options.

Java: Static vs inner class

There are two differences between static inner and non static inner classes.

  1. In case of declaring member fields and methods, non static inner class cannot have static fields and methods. But, in case of static inner class, can have static and non static fields and method.

  2. The instance of non static inner class is created with the reference of object of outer class, in which it has defined, this means it has enclosing instance. But the instance of static inner class is created without the reference of Outer class, which means it does not have enclosing instance.

See this example

class A
{
    class B
    {
        // static int x; not allowed here
    }

    static class C
    {
        static int x; // allowed here
    }
}

class Test
{
    public static void main(String… str)
    {
        A a = new A();

        // Non-Static Inner Class
        // Requires enclosing instance
        A.B obj1 = a.new B(); 

        // Static Inner Class
        // No need for reference of object to the outer class
        A.C obj2 = new A.C(); 
    }
}

How to initialize a vector with fixed length in R

The initialization method easiest to remember is

vec = vector(,10); #the same as "vec = vector(length = 10);"

The values of vec are: "[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE" (logical mode) by default.

But after setting a character value, like

vec[2] = 'abc'

vec becomes: "FALSE" "abc" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE"", which is of the character mode.

How to URL encode in Python 3?

For Python 3 you could try using quote instead of quote_plus:

import urllib.parse

print(urllib.parse.quote("http://www.sample.com/"))

Result:

http%3A%2F%2Fwww.sample.com%2F

Or:

from requests.utils import requote_uri
requote_uri("http://www.sample.com/?id=123 abc")

Result:

'https://www.sample.com/?id=123%20abc'

Create HTML table using Javascript

This beautiful code here creates a table with each td having array values. Not my code, but it helped me!

var rows = 6, cols = 7;

for(var i = 0; i < rows; i++) {
  $('table').append('<tr></tr>');
  for(var j = 0; j < cols; j++) {
    $('table').find('tr').eq(i).append('<td></td>');
    $('table').find('tr').eq(i).find('td').eq(j).attr('data-row', i).attr('data-col', j);
  }
}

Where to put a textfile I want to use in eclipse?

You should probably take a look at the various flavours of getResource in the ClassLoader class: https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html.

What is the significance of #pragma marks? Why do we need #pragma marks?

Just to add the information I was looking for: pragma mark is Xcode specific, so if you deal with a C++ project that you open in different IDEs, it does not have any effect there. In Qt Creator, for example, it does not add categories for methods, nor generate any warnings/errors.

EDIT

#pragma is a preprocessor directive which comes from C programming language. Its purpose is to specify implementation-dependent information to the compiler - that is, each compiler might choose to interpret this directive as it wants. That said, it is rather considered an extension which does not change/influence the code itself. So compilers might as well ignore it.

Xcode is an IDE which takes advantage of #pragma and uses it in its own specific way. The point is, #pragma is not Xcode and even Objective-C specific.

How to sort a file in-place

No answers about few files, so:

sort -u file1 file2 -o file1

RelativeLayout center vertical

This maybe because the textview is too high. Change android:layout_height of the textview to wrap_content or use

android:gravity="center_vertical"

Break promise chain and call a function based on the step in the chain where it is broken (rejected)

If you want to solve this issue using async/await:

(async function(){    
    try {        
        const response1, response2, response3
        response1 = await promise1()

        if(response1){
            response2 = await promise2()
        }
        if(response2){
            response3 = await promise3()
        }
        return [response1, response2, response3]
    } catch (error) {
        return []
    }

})()

Get IFrame's document, from JavaScript in main document

The problem is that in IE (which is what I presume you're testing in), the <iframe> element has a document property that refers to the document containing the iframe, and this is getting used before the contentDocument or contentWindow.document properties. What you need is:

function GetDoc(x) {
    return x.contentDocument || x.contentWindow.document;
}

Also, document.all is not available in all browsers and is non-standard. Use document.getElementById() instead.

matplotlib colorbar for scatter

If you're looking to scatter by two variables and color by the third, Altair can be a great choice.

Creating the dataset

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame(40*np.random.randn(10, 3), columns=['A', 'B','C'])

Altair plot

from altair import *
Chart(df).mark_circle().encode(x='A',y='B', color='C').configure_cell(width=200, height=150)

Plot

enter image description here

How to make link not change color after visited?

Something like this should work:

a, a:visited { 
    color:red; text-decoration:none; 
    }

send bold & italic text on telegram bot with html

For JS:

First, if you haven't installed telegram bot just install with the command

npm i messaging-api-telegram

Now, initialize its client with

const client = new TelegramClient({
    accessToken: process.env.<TELEGRAM_ACCESS_TOKEN>
});

Then, to send message use sendMessage() async function like below -

    const resp = await client.sendMessage(chatId, msg, {
        disableWebPagePreview: false,
        disableNotification: false,
        parseMode: "HTML"
    });

Here parse mode by default would be plain text but with parseOptions parseMode we can do 1. "HTML" and "MARKDOWN" to let use send messages in stylish way. Also get your access token of bot from telegram page and chatId or group chat Id from same.

How to get the mobile number of current sim card in real device?

As many said:

String phoneNumber = TelephonyManager.getDefault().getLine1Number();

The availability depends strictly on the carrier and the way the number is encoded on the SIM card. If it is hardcoded by the company that makes the SIMs or by the mobile carrier itself. This returns the same as in Settings->about phone.

Fatal error: Call to undefined function mb_detect_encoding()

I had the same problem with Ubuntu 17, Ispconfig was not processing the operations queued of any kind and also the server.sh command was not working. I checked and the running PHP version after the OS upgrade was 7.1 so the solution was to type:

apt-get install php7.1-mbstring

and now is everything ok

how to use math.pi in java

Here is usage of Math.PI to find circumference of circle and Area First we take Radius as a string in Message Box and convert it into integer

public class circle {

    public static void main(String[] args) {
        // TODO code application logic here

        String rad;

        float radius,area,circum;

       rad = JOptionPane.showInputDialog("Enter the Radius of circle:");

        radius = Integer.parseInt(rad);
        area = (float) (Math.PI*radius*radius);
        circum = (float) (2*Math.PI*radius);

        JOptionPane.showMessageDialog(null, "Area: " + area,"AREA",JOptionPane.INFORMATION_MESSAGE);
        JOptionPane.showMessageDialog(null, "circumference: " + circum, "Circumfernce",JOptionPane.INFORMATION_MESSAGE);
    }

}

Plotting with C#

NPlot is a pretty good simple open source 2D plotting API. Unfortunately, the web site is down. I don't know if this is just temporary or not. I haven't heard of any bad news. It may come back up.

http://www.nplot.com

Here is an article describing it:

http://aspnet.4guysfromrolla.com/articles/072507-1.aspx

The previous article uses VB.NET, but obviously this will work with C#.

Again, not sure why nplot's site is not currently working but it is a somewhat popular plotting API that I've used in the past. I post it for your information and in case of the likely event nplot will be back up soon. :)

Edit:

Thanks to a Hosam Aly, it looks like the SourceForge project can still be accessed here:

http://sourceforge.net/projects/nplot

Laravel 5 PDOException Could Not Find Driver

sudo apt-get update

For Mysql Database

sudo apt-get install php-mysql

For PostgreSQL Database

sudo apt-get install php-pgsql

Than

php artisan migrate

How can I search an array in VB.NET?

VB

Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim result = arr.Where(Function(a) a.Contains("ra")).Select(Function(s) Array.IndexOf(arr, s)).ToArray()

C#

string[] arr = { "ravi", "Kumar", "Ravi", "Ramesh" };
var result = arr.Where(a => a.Contains("Ra")).Select(a => Array.IndexOf(arr, a)).ToArray();

-----Detailed------

Module Module1

    Sub Main()
        Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
        Dim searchStr = "ra"
        'Not case sensitive - checks if item starts with searchStr
        Dim result1 = arr.Where(Function(a) a.ToLower.StartsWith(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
        'Case sensitive - checks if item starts with searchStr
        Dim result2 = arr.Where(Function(a) a.StartsWith(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
        'Not case sensitive - checks if item contains searchStr
        Dim result3 = arr.Where(Function(a) a.ToLower.Contains(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
        Stop
    End Sub

End Module

Android Animation Alpha

The "setStartOffset" should be smaller, else animation starts at view alpha 0.xf and waits for start offset before animating to 1f. Hope the following code helps.

AlphaAnimation animation1 = new AlphaAnimation(0.1f, 1f);

animation1.setDuration(1000);
animation1.setStartOffset(50);

animation1.setFillAfter(true);

view.setVisibility(View.VISIBLE);

view.startAnimation(animation1);

In what cases do I use malloc and/or new?

The new and delete operators can operate on classes and structures, whereas malloc and free only work with blocks of memory that need to be cast.

Using new/delete will help to improve your code as you will not need to cast allocated memory to the required data structure.

Replace a string in a file with nodejs

This may help someone:

This is a little different than just a global replace

from the terminal we run
node replace.js

replace.js:

function processFile(inputFile, repString = "../") {
var fs = require('fs'),
    readline = require('readline'),
    instream = fs.createReadStream(inputFile),
    outstream = new (require('stream'))(),
    rl = readline.createInterface(instream, outstream);
    formatted = '';   

const regex = /<xsl:include href="([^"]*)" \/>$/gm;

rl.on('line', function (line) {
    let url = '';
    let m;
    while ((m = regex.exec(line)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
            regex.lastIndex++;
        }
        
        url = m[1];
    }

    let re = new RegExp('^.* <xsl:include href="(.*?)" \/>.*$', 'gm');

    formatted += line.replace(re, `\t<xsl:include href="${repString}${url}" />`);
    formatted += "\n";
});

rl.on('close', function (line) {
    fs.writeFile(inputFile, formatted, 'utf8', function (err) {
        if (err) return console.log(err);
    });

});
}


// path is relative to where your running the command from
processFile('build/some.xslt');

This is what this does. We have several file that have xml:includes

However in development we need the path to move down a level.

From this

<xsl:include href="common/some.xslt" />

to this

<xsl:include href="../common/some.xslt" />

So we end up running two regx patterns one to get the href and the other to write there is probably a better way to do this but it work for now.

Thanks

no module named zlib

I had a lot of problems making a virtual environment (venv) as described in the tensorflow installation guide.

Most of the commands listed in this post didn't help me either so, if this is also your case this is what I did:

  1. pip3 install --user pipenv
  2. pip install virtualenv

Installs the dependencies to create a virtual environment

  1. mkdir myenv

Makes a new directory called myenv but you can call it whatever you want e.g. mynewenv

  1. cd myenv

Or whatever you call your directory so: cd [your_directory_name]

  1. virtualenv -p /usr/bin/python3 venv

Creates a virtual environment called venv in the folder myenv. You can call your virtual env whatever you like e.g. vitualenv [v_env_name]

  1. source ./venv/bin/activate

Activates the virtual environment. Note that if you choose a different v. env. name your commands should be written as such source ./[v_env_name]/bin/activate

  1. deactivate

Deactivates the virtual environment.

Note: I am using Python 3.6.6 & Ubuntu 18.04

source for the commands

Slide a layout up from bottom of screen

Try this below code, Its very short and simple.

transalate_anim.xml

<?xml version="1.0" encoding="utf-8"?><!-- Copyright (C) 2013 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="4000"
        android:fromXDelta="0"
        android:fromYDelta="0"
        android:repeatCount="infinite"
        android:toXDelta="0"
        android:toYDelta="-90%p" />

    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="4000"
        android:fromAlpha="0.0"
        android:repeatCount="infinite"
        android:toAlpha="1.0" />
</set>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.naveen.congratulations.MainActivity">


    <ImageView
        android:id="@+id/image_1"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginStart="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:srcCompat="@drawable/balloons" />
</android.support.constraint.ConstraintLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ImageView imageView1 = (ImageView) findViewById(R.id.image_1);
        imageView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startBottomToTopAnimation(imageView1);
            }
        });

    }

    private void startBottomToTopAnimation(View view) {
        view.startAnimation(AnimationUtils.loadAnimation(this, R.anim.translate_anim));
    }
}

bottom_up_navigation of image

Show popup after page load

If you don't want to use jquery, use this:

<script>
 // without jquery
document.addEventListener("DOMContentLoaded", function() {
 setTimeout(function() {
  // run your open popup function after 5 sec = 5000
  PopUp();
 }, 5000)
});
</script>

OR With jquery

<script>
  $(document).ready(function(){
   setTimeout(function(){
   // open popup after 5 seconds
   PopUp();
  },5000);  
 });
</script>

How to upload a file using Java HttpClient library working with PHP

I ran into the same problem and found out that the file name is required for httpclient 4.x to be working with PHP backend. It was not the case for httpclient 3.x.

So my solution is to add a name parameter in the FileBody constructor. ContentBody cbFile = new FileBody(file, "image/jpeg", "FILE_NAME");

Hope it helps.

Converting JSON data to Java object

What's wrong with the standard stuff?

JSONObject jsonObject = new JSONObject(someJsonString);
JSONArray jsonArray = jsonObject.getJSONArray("someJsonArray");
String value = jsonArray.optJSONObject(i).getString("someJsonValue");

pip3: command not found

Try this if other methods do not work:

  1. brew install python3
  2. brew link --overwrite python
  3. brew postinstall python3

error: expected declaration or statement at end of input in c

Normally that error occurs when a } was missed somewhere in the code, for example:

void mi_start_curr_serv(void){
    #if 0
    //stmt
    #endif

would fail with this error due to the missing } at the end of the function. The code you posted doesn't have this error, so it is likely coming from some other part of your source.

Execute stored procedure with an Output parameter?

CREATE PROCEDURE DBO.MY_STORED_PROCEDURE
(@PARAM1VALUE INT,
@PARAM2VALUE INT,
@OUTPARAM VARCHAR(20) OUT)
AS 
BEGIN
SELECT * FROM DBO.PARAMTABLENAME WHERE PARAM1VALUE=@PARAM1VALUE
END

DECLARE @OUTPARAM2 VARCHAR(20)
EXEC DBO.MY_STORED_PROCEDURE 1,@OUTPARAM2 OUT
PRINT @OUTPARAM2

VBA procedure to import csv file into access

Your file seems quite small (297 lines) so you can read and write them quite quickly. You refer to Excel CSV, which does not exists, and you show space delimited data in your example. Furthermore, Access is limited to 255 columns, and a CSV is not, so there is no guarantee this will work

Sub StripHeaderAndFooter()
Dim fs As Object ''FileSystemObject
Dim tsIn As Object, tsOut As Object ''TextStream
Dim sFileIn As String, sFileOut As String
Dim aryFile As Variant

    sFileIn = "z:\docs\FileName.csv"
    sFileOut = "z:\docs\FileOut.csv"

    Set fs = CreateObject("Scripting.FileSystemObject")
    Set tsIn = fs.OpenTextFile(sFileIn, 1) ''ForReading

    sTmp = tsIn.ReadAll

    Set tsOut = fs.CreateTextFile(sFileOut, True) ''Overwrite
    aryFile = Split(sTmp, vbCrLf)

    ''Start at line 3 and end at last line -1
    For i = 3 To UBound(aryFile) - 1
        tsOut.WriteLine aryFile(i)
    Next

    tsOut.Close

    DoCmd.TransferText acImportDelim, , "NewCSV", sFileOut, False
End Sub

Edit re various comments

It is possible to import a text file manually into MS Access and this will allow you to choose you own cell delimiters and text delimiters. You need to choose External data from the menu, select your file and step through the wizard.

About importing and linking data and database objects -- Applies to: Microsoft Office Access 2003

Introduction to importing and exporting data -- Applies to: Microsoft Access 2010

Once you get the import working using the wizards, you can save an import specification and use it for you next DoCmd.TransferText as outlined by @Olivier Jacot-Descombes. This will allow you to have non-standard delimiters such as semi colon and single-quoted text.

How to cast/convert pointer to reference in C++

foo(*ob);

You don't need to cast it because it's the same Object type, you just need to dereference it.

How to update value of a key in dictionary in c#?

Just use the indexer and update directly:

dictionary["cat"] = 3

How to copy file from HDFS to the local file system

  1. bin/hadoop fs -get /hdfs/source/path /localfs/destination/path
  2. bin/hadoop fs -copyToLocal /hdfs/source/path /localfs/destination/path
  3. Point your web browser to HDFS WEBUI(namenode_machine:50070), browse to the file you intend to copy, scroll down the page and click on download the file.

How do you tell if a checkbox is selected in Selenium for Java?

if ( !driver.findElement(By.id("idOfTheElement")).isSelected() )
{
     driver.findElement(By.id("idOfTheElement")).click();
}

See changes to a specific file using git

you can also try

git show <filename>

For commits, git show will show the log message and textual diff (between your file and the commited version of the file).

You can check git show Documentation for more info.

Ajax LARAVEL 419 POST error

Had the same problem, regenerating application key helped - php artisan key:generate