Programs & Examples On #Acts as state machine

A plugin for adding finite state machines to Ruby classes. Evolved to [AASM] library.

open resource with relative path in Java

When you use 'getResource' on a Class, a relative path is resolved based on the package the Class is in. When you use 'getResource' on a ClassLoader, a relative path is resolved based on the root folder.

If you use an absolute path, both 'getResource' methods will start at the root folder.

How can I add items to an empty set in python

>>> d = {}
>>> D = set()
>>> type(d)
<type 'dict'>
>>> type(D)
<type 'set'>

What you've made is a dictionary and not a Set.

The update method in dictionary is used to update the new dictionary from a previous one, like so,

>>> abc = {1: 2}
>>> d.update(abc)
>>> d
{1: 2}

Whereas in sets, it is used to add elements to the set.

>>> D.update([1, 2])
>>> D
set([1, 2])

Error pushing to GitHub - insufficient permission for adding an object to repository database

I was getting this error because every time a user push some content, the group of the file changed to the user. And then if some other user tried to push into the repository, it caused permission error and the push was rejected. So one need to ask your sysadmin to change the settings of the repository so that group of any file in the repository is not changed for any push by any user.

To avoid such problem, please ensure that when you initialize your git repository, use the command "git init --shared=group".

How to replace all occurrences of a character in string?

The question is centered on character replacement, but, as I found this page very useful (especially Konrad's remark), I'd like to share this more generalized implementation, which allows to deal with substrings as well:

std::string ReplaceAll(std::string str, const std::string& from, const std::string& to) {
    size_t start_pos = 0;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
    }
    return str;
}

Usage:

std::cout << ReplaceAll(string("Number Of Beans"), std::string(" "), std::string("_")) << std::endl;
std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("X")) << std::endl;
std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("h")) << std::endl;

Outputs:

Number_Of_Beans

XXjXugtXty

hhjhugthty


EDIT:

The above can be implemented in a more suitable way, in case performances are of your concern, by returning nothing (void) and performing the changes directly on the string str given as argument, passed by address instead of by value. This would avoid useless and costly copy of the original string, while returning the result. Your call, then...

Code :

static inline void ReplaceAll2(std::string &str, const std::string& from, const std::string& to)
{
    // Same inner code...
    // No return statement
}

Hope this will be helpful for some others...

Install a module using pip for specific python version

for python2 use:

py -2 -m pip install beautifulsoup4

bash: npm: command not found?

If you already installed npm globally on your system, and you are still getting the above error message by using VSCode terminal. Just close your VSCode application and reopen again, that should resolve the issue.

Exclude Blank and NA in R

A good idea is to set all of the "" (blank cells) to NA before any further analysis.

If you are reading your input from a file, it is a good choice to cast all "" to NAs:

foo <- read.table(file="Your_file.txt", na.strings=c("", "NA"), sep="\t") # if your file is tab delimited

If you have already your table loaded, you can act as follows:

foo[foo==""] <- NA

Then to keep only rows with no NA you may just use na.omit():

foo <- na.omit(foo)

Or to keep columns with no NA:

foo <- foo[, colSums(is.na(foo)) == 0] 

Autoplay an audio with HTML5 embed tag while the player is invisible

Sometimes autoplay is needed. Someone once pointed out that the famous Les Paul Google Doodle (2011) required autoplay, even though the sound didn't play until you moused over the guitar strings. If it's done with class and great design it can be beautiful (especially movie websites with immersive design)

What is the difference between SQL and MySQL?

SQL - Structured Query Language. It is declarative computer language aimed at querying relational databases.

MySQL is a relational database - a piece of software optimized for data storage and retrieval. There are many such databases - Oracle, Microsoft SQL Server, SQLite and many others are examples of such.

Send json post using php

use CURL luke :) seriously, thats one of the best ways to do it AND you get the response.

EC2 instance has no public DNS

  1. Go to VPC
  2. Select your VPC
  3. Click actions and choose Edit DNS hostnames
  4. Tick Enable for DNS Hostnames
  5. Click save changes

How to compare if two structs, slices or maps are equal?

If you're comparing them in unit test, a handy alternative is EqualValues function in testify.

Manage toolbar's navigation and back button from fragment in android

You have to manage your back button pressed action on your main Activity because your main Activity is container for your fragment.

First, add your all fragment to transaction.addToBackStack(null) and now navigation back button call will be going on main activity. I hope following code will help you...

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        onBackPressed();
        }
    return super.onOptionsItemSelected(item);
}

you can also use

Fragment fragment =fragmentManager.findFragmentByTag(Constant.TAG); 
if(fragment!=null) {          
      FragmentTransaction transaction = fragmentManager.beginTransaction();
      transaction.remove(fragment).commit();
}

And to change the title according to fragment name from fragment you can use the following code:

activity.getSupportActionBar().setTitle("Keyword Report Detail");

Add a new item to a dictionary in Python

It can be as simple as:

default_data['item3'] = 3

As Chris' answer says, you can use update to add more than one item. An example:

default_data.update({'item4': 4, 'item5': 5})

Please see the documentation about dictionaries as data structures and dictionaries as built-in types.

how to remove key+value from hash in javascript

Why do you use new Array(); for hash? You need to use new Object() instead.

And i think you will get what you want.

Named parameters in JDBC

Plain vanilla JDBC does not support named parameters.

If you are using DB2 then using DB2 classes directly:

  1. Using named parameter markers with PreparedStatement objects
  2. Using named parameter markers with CallableStatement objects

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

Remove title in Toolbar in appcompat-v7

It's obvious, but the App Theme selection in design is just for display a draft during layout edition, is not related to real app looking in cell phone. In my case, there is no title bar in design but the title bar was always in cell phone.

I'm starting with Android programming and fight to discover a right solution.

Just change the manifest file (AndroidManifest.xml) is not enough because the style need to be predefined is styles.xml. Also is useless change the layout files.

All proposed solution in Java or Kotlin has failed for me. Some of them crash the app. And if one never (like me) intend to use the title bar in app, the static solution is cleaner.

For me the only solution that works in 2019 (Android Studio 3.4.1) is:

in styles.xml (under app/res/values) add the lines:

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

After in AndroidManifest.xml (under app/manifests)

Replace

android:theme="@style/AppTheme">

by

android:theme="@style/AppTheme.NoActionBar">

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Find the file "config.inc.php" under your phpMyAdmin directory and edit the following lines:

$cfg['Servers'][$i]['auth_type'] = 'config'; // config, http, cookie

$cfg['Servers'][$i]['user'] = 'root'; // MySQL user

$cfg['Servers'][$i]['password'] = 'TYPE_YOUR_PASSWORD_HERE'; // MySQL password

Note that the password used in the 'password' field must be the same for the MySQL root password. Also, you should check if root login is allowed in this line:

$cfg['Servers'][$i]['AllowRoot']     = TRUE;        // true = allow root login

This way you have your root password set.

Printing an int list in a single line python3

# Print In One Line Python

print('Enter Value')

n = int(input())

print(*range(1, n+1), sep="")

Getting IP address of client

I use the following static helper method to retrieve the IP of a client:

public static String getClientIpAddr(HttpServletRequest request) {  
    String ip = request.getHeader("X-Forwarded-For");  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("Proxy-Client-IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("WL-Proxy-Client-IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_X_FORWARDED");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_X_CLUSTER_CLIENT_IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_CLIENT_IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_FORWARDED_FOR");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_FORWARDED");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_VIA");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("REMOTE_ADDR");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getRemoteAddr();  
    }  
    return ip;  
}

Write to file, but overwrite it if it exists

#!/bin/bash

cat <<EOF > SampleFile

Put Some text here 
Put some text here
Put some text here

EOF

Good Patterns For VBA Error Handling

Here's my standard implementation. I like the labels to be self-descriptive.

Public Sub DoSomething()

    On Error GoTo Catch ' Try
    ' normal code here

    Exit Sub
Catch:

    'error code: you can get the specific error by checking Err.Number

End Sub

Or, with a Finally block:

Public Sub DoSomething()

    On Error GoTo Catch ' Try

    ' normal code here

    GoTo Finally
Catch:

    'error code

Finally:

    'cleanup code

End Sub

Lodash .clone and .cloneDeep behaviors

Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.

As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:

var clone = _.clone(data, true);

data[1].values.d = 'x';

I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.

Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).

JQuery Ajax Post results in 500 Internal Server Error

Your return string data can be very long.

<system.web>        
   <compilation debug="true" targetFramework="4.0" />
   <httpRuntime maxRequestLength="2147483647" />
</system.web>

For example:

  • 1 Char = 1 Byte
  • 5 Char = 5 Byte
  • "Hakki" = 5 Byte

Are Git forks actually Git clones?

Fork, in the GitHub context, doesn't extend Git.
It only allows clone on the server side.

When you clone a GitHub repository on your local workstation, you cannot contribute back to the upstream repository unless you are explicitly declared as "contributor". That's because your clone is a separate instance of that project. If you want to contribute to the project, you can use forking to do it, in the following way:

  • clone that GitHub repository on your GitHub account (that is the "fork" part, a clone on the server side)
  • contribute commits to that GitHub repository (it is in your own GitHub account, so you have every right to push to it)
  • signal any interesting contribution back to the original GitHub repository (that is the "pull request" part by way of the changes you made on your own GitHub repository)

Check also "Collaborative GitHub Workflow".

If you want to keep a link with the original repository (also called upstream), you need to add a remote referring that original repository.
See "What is the difference between origin and upstream on GitHub?"

fork and upstream

And with Git 2.20 (Q4 2018) and more, fetching from fork is more efficient, with delta islands.

Slick.js: Get current and total slides (ie. 3/5)

Based on the first proposition posted by @Mx. (posted sept.15th 2014) I created a variant to get a decent HTML markup for ARIA support.

$('.slideshow').slick({
    slide: 'img',
    autoplay: true,
    dots: true,
    dotsClass: 'custom_paging',
    customPaging: function (slider, i) {
        //FYI just have a look at the object to find available information
        //press f12 to access the console in most browsers
        //you could also debug or look in the source
        console.log(slider);
        var slideNumber   = (i + 1),
            totalSlides = slider.slideCount;
        return '<a class="custom-dot" role="button" title="' + slideNumber + ' of ' + totalSlides + '"><span class="string">' + slideNumber + '</span></a>';
    }
});

jsFiddle DEMO

Best way to encode Degree Celsius symbol into web page?

Using sup on the letter "o" and a capital "C"

_x000D_
_x000D_
<sup>o</sup>C
_x000D_
_x000D_
_x000D_

Should work in all browsers and IE6+

Move all files except one

Put the following to your .bashrc

shopt -s extglob

It extends regexes. You can then move all files except one by

mv !(fileOne) ~/path/newFolder

Exceptions in relation to other commands

Note that, in copying directories, the forward-flash cannot be used in the name as noticed in the thread Why extglob except breaking except condition?:

cp -r !(Backups.backupdb) /home/masi/Documents/

so Backups.backupdb/ is wrong here before the negation and I would not use it neither in moving directories because of the risk of using wrongly then globs with other commands and possible other exceptions.

How to send HTTP request in java?

Apache HttpComponents. The examples for the two modules - HttpCore and HttpClient will get you started right away.

Not that HttpUrlConnection is a bad choice, HttpComponents will abstract a lot of the tedious coding away. I would recommend this, if you really want to support a lot of HTTP servers/clients with minimum code. By the way, HttpCore could be used for applications (clients or servers) with minimum functionality, whereas HttpClient is to be used for clients that require support for multiple authentication schemes, cookie support etc.

Side-by-side plots with ggplot2

In my experience gridExtra:grid.arrange works perfectly, if you are trying to generate plots in a loop.

Short Code Snippet:

gridExtra::grid.arrange(plot1, plot2, ncol = 2)

** Updating this comment to show how to use grid.arrange() within a for loop to generate plots for different factors of a categorical variable.

for (bin_i in levels(athlete_clean$BMI_cat)) {

plot_BMI <- athlete_clean %>% filter(BMI_cat == bin_i) %>% group_by(BMI_cat,Team) %>% summarize(count_BMI_team = n()) %>% 
          mutate(percentage_cbmiT = round(count_BMI_team/sum(count_BMI_team) * 100,2)) %>% 
          arrange(-count_BMI_team) %>% top_n(10,count_BMI_team) %>% 
          ggplot(aes(x = reorder(Team,count_BMI_team), y = count_BMI_team, fill = Team)) +
            geom_bar(stat = "identity") +
            theme_bw() +
            # facet_wrap(~Medal) +
            labs(title = paste("Top 10 Participating Teams with \n",bin_i," BMI",sep=""), y = "Number of Athletes", 
                 x = paste("Teams - ",bin_i," BMI Category", sep="")) +
            geom_text(aes(label = paste(percentage_cbmiT,"%",sep = "")), 
                      size = 3, check_overlap = T,  position = position_stack(vjust = 0.7) ) +
            theme(axis.text.x = element_text(angle = 00, vjust = 0.5), plot.title = element_text(hjust = 0.5), legend.position = "none") +
            coord_flip()

plot_BMI_Medal <- athlete_clean %>% 
          filter(!is.na(Medal), BMI_cat == bin_i) %>% 
          group_by(BMI_cat,Team) %>% 
          summarize(count_BMI_team = n()) %>% 
          mutate(percentage_cbmiT = round(count_BMI_team/sum(count_BMI_team) * 100,2)) %>% 
          arrange(-count_BMI_team) %>% top_n(10,count_BMI_team) %>% 
          ggplot(aes(x = reorder(Team,count_BMI_team), y = count_BMI_team, fill = Team)) +
            geom_bar(stat = "identity") +
            theme_bw() +
            # facet_wrap(~Medal) +
            labs(title = paste("Top 10 Winning Teams with \n",bin_i," BMI",sep=""), y = "Number of Athletes", 
                 x = paste("Teams - ",bin_i," BMI Category", sep="")) +
            geom_text(aes(label = paste(percentage_cbmiT,"%",sep = "")), 
                      size = 3, check_overlap = T,  position = position_stack(vjust = 0.7) ) +
            theme(axis.text.x = element_text(angle = 00, vjust = 0.5), plot.title = element_text(hjust = 0.5), legend.position = "none") +
            coord_flip()

gridExtra::grid.arrange(plot_BMI, plot_BMI_Medal, ncol = 2)

}

One of the Sample Plots from the above for loop is included below. The above loop will produce multiple plots for all levels of BMI category.

Sample Image

If you wish to see a more comprehensive use of grid.arrange() within for loops, check out https://rpubs.com/Mayank7j_2020/olympic_data_2000_2016

How to turn NaN from parseInt into 0 for an empty string?

var value = isNaN(parseInt(tbb)) ? 0 : parseInt(tbb);

Android ADB devices unauthorized

Ensure that you have accepted the pressed the "ok" button when it is asking it is showing the fingerprint of the device after connecting through usb to your PC.

Making RGB color in Xcode

Objective-C

You have to give the values between 0 and 1.0. So divide the RGB values by 255.

myLabel.textColor= [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1] ;

Update:

You can also use this macro

#define Rgb2UIColor(r, g, b)  [UIColor colorWithRed:((r) / 255.0) green:((g) / 255.0) blue:((b) / 255.0) alpha:1.0]

and you can call in any of your class like this

 myLabel.textColor = Rgb2UIColor(160, 97, 5);

Swift

This is the normal color synax

myLabel.textColor = UIColor(red: (160/255.0), green: (97/255.0), blue: (5/255.0), alpha: 1.0) 
//The values should be between 0 to 1

Swift is not much friendly with macros

Complex macros are used in C and Objective-C but have no counterpart in Swift. Complex macros are macros that do not define constants, including parenthesized, function-like macros. You use complex macros in C and Objective-C to avoid type-checking constraints or to avoid retyping large amounts of boilerplate code. However, macros can make debugging and refactoring difficult. In Swift, you can use functions and generics to achieve the same results without any compromises. Therefore, the complex macros that are in C and Objective-C source files are not made available to your Swift code.

So we use extension for this

extension UIColor {
    convenience init(_ r: Double,_ g: Double,_ b: Double,_ a: Double) {
        self.init(red: r/255, green: g/255, blue: b/255, alpha: a)
    }
}

You can use it like

myLabel.textColor = UIColor(160.0, 97.0, 5.0, 1.0)

Are PHP short tags acceptable to use?

Note: Starting in PHP 5.4 the short tag, <?=, is now always available.

How is length implemented in Java Arrays?

You're correct, length is a data member, not a method.

From the Arrays tutorial:

The length of an array is established when the array is created. After creation, its length is fixed.

Grant Select on all Tables Owned By Specific User

From http://psoug.org/reference/roles.html, create a procedure on your database for your user to do it:

CREATE OR REPLACE PROCEDURE GRANT_SELECT(to_user in varchar2) AS

  CURSOR ut_cur IS SELECT table_name FROM user_tables;

  RetVal  NUMBER;
  sCursor INT;
  sqlstr  VARCHAR2(250);

BEGIN
    FOR ut_rec IN ut_cur
    LOOP
      sqlstr := 'GRANT SELECT ON '|| ut_rec.table_name || ' TO ' || to_user;
      sCursor := dbms_sql.open_cursor;
      dbms_sql.parse(sCursor,sqlstr, dbms_sql.native);
      RetVal := dbms_sql.execute(sCursor);
      dbms_sql.close_cursor(sCursor);

    END LOOP;
END grant_select;

How to debug a bash script?

I think you can try this Bash debugger: http://bashdb.sourceforge.net/.

JavaScript: Check if mouse button down?

        var mousedown = 0;
        $(function(){
            document.onmousedown = function(e){
                mousedown = mousedown | getWindowStyleButton(e);
                e = e || window.event;
                console.log("Button: " + e.button + " Which: " + e.which + " MouseDown: " + mousedown);
            }

            document.onmouseup = function(e){
                mousedown = mousedown ^ getWindowStyleButton(e);
                e = e || window.event;
                console.log("Button: " + e.button + " Which: " + e.which + " MouseDown: " + mousedown);
            }

            document.oncontextmenu = function(e){
                // to suppress oncontextmenu because it blocks
                // a mouseup when two buttons are pressed and 
                // the right-mouse button is released before
                // the other button.
                return false;
            }
        });

        function getWindowStyleButton(e){
            var button = 0;
                if (e) {
                    if (e.button === 0) button = 1;
                    else if (e.button === 1) button = 4;
                    else if (e.button === 2) button = 2;  
                }else if (window.event){
                    button = window.event.button;
                }
            return button;
        }

this cross-browser version works fine for me.

How do you set the max number of characters for an EditText in Android?

Kotlin way

editText.filters = arrayOf(InputFilter.LengthFilter(maxLength))

Java way to check if a string is palindrome

You can try something like this :

    String variable = ""; #write a string name

    StringBuffer rev = new StringBuffer(variable).reverse(); 

    String strRev = rev.toString(); 

    if(variable.equalsIgnoreCase(strRev)) # Check the condition

ASP.NET: Session.SessionID changes between requests

Using Neville's answer (deleting requireSSL = true, in web.config) and slightly modifying Joel Etherton's code, here is the code that should handle a site that runs in both SSL mode and non SSL mode, depending on the user and the page (I am jumping back into code and haven't tested it on SSL yet, but expect it should work - will be too busy later to get back to this, so here it is:

if (HttpContext.Current.Response.Cookies.Count > 0)
        {
            foreach (string s in HttpContext.Current.Response.Cookies.AllKeys)
            {
                if (s == FormsAuthentication.FormsCookieName || s.ToLower() == "asp.net_sessionid")
                {
                    HttpContext.Current.Response.Cookies[s].Secure = HttpContext.Current.Request.IsSecureConnection;
                }
            }
        }

What is the difference between "screen" and "only screen" in media queries?

The following is from Adobe docs.


The media queries specification also provides the keyword only, which is intended to hide media queries from older browsers. Like not, the keyword must come at the beginning of the declaration. For example:

media="only screen and (min-width: 401px) and (max-width: 600px)"

Browsers that don't recognize media queries expect a comma-separated list of media types, and the specification says they should truncate each value immediately before the first nonalphanumeric character that isn't a hyphen. So, an old browser should interpret the preceding example as this:

media="only"

Because there is no such media type as only, the stylesheet is ignored. Similarly, an old browser should interpret

media="screen and (min-width: 401px) and (max-width: 600px)"

as

media="screen"

In other words, it should apply the style rules to all screen devices, even though it doesn't know what the media queries mean.

Unfortunately, IE 6–8 failed to implement the specification correctly.

Instead of applying the styles to all screen devices, it ignores the style sheet altogether.

In spite of this behavior, it's still recommended to prefix media queries with only if you want to hide the styles from other, less common browsers.


So, using

media="only screen and (min-width: 401px)"

and

media="screen and (min-width: 401px)"

will have the same effect in IE6-8: both will prevent those styles from being used. They will, however, still be downloaded.

Also, in browsers that support CSS3 media queries, both versions will load the styles if the viewport width is larger than 401px and the media type is screen.

I'm not entirely sure which browsers that don't support CSS3 media queries would need the only version

media="only screen and (min-width: 401px)" 

as opposed to

media="screen and (min-width: 401px)"

to make sure it is not interpreted as

media="screen"

It would be a good test for someone with access to a device lab.

instanceof Vs getClass( )

Do you want to match a class exactly, e.g. only matching FileInputStream instead of any subclass of FileInputStream? If so, use getClass() and ==. I would typically do this in an equals, so that an instance of X isn't deemed equal to an instance of a subclass of X - otherwise you can get into tricky symmetry problems. On the other hand, that's more usually useful for comparing that two objects are of the same class than of one specific class.

Otherwise, use instanceof. Note that with getClass() you will need to ensure you have a non-null reference to start with, or you'll get a NullPointerException, whereas instanceof will just return false if the first operand is null.

Personally I'd say instanceof is more idiomatic - but using either of them extensively is a design smell in most cases.

How to calculate the time interval between two time strings

I like how this guy does it — https://amalgjose.com/2015/02/19/python-code-for-calculating-the-difference-between-two-time-stamps. Not sure if it has some cons.

But looks neat for me :)

from datetime import datetime
from dateutil.relativedelta import relativedelta

t_a = datetime.now()
t_b = datetime.now()

def diff(t_a, t_b):
    t_diff = relativedelta(t_b, t_a)  # later/end time comes first!
    return '{h}h {m}m {s}s'.format(h=t_diff.hours, m=t_diff.minutes, s=t_diff.seconds)

Regarding to the question you still need to use datetime.strptime() as others said earlier.

What is the JUnit XML format specification that Hudson supports?

I've decided to post a new answer, because some existing answers are outdated or incomplete.

First of all: there is nothing like JUnit XML Format Specification, simply because JUnit doesn't produce any kind of XML or HTML report.

The XML report generation itself comes from the Ant JUnit task/ Maven Surefire Plugin/ Gradle (whichever you use for running your tests). The XML report format was first introduced by Ant and later adapted by Maven (and Gradle).

If somebody just needs an official XML format then:

  1. There exists a schema for a maven surefire-generated XML report and it can be found here: surefire-test-report.xsd.
  2. For an ant-generated XML there is a 3rd party schema available here (but it might be slightly outdated).

Hope it will help somebody.

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

If issue remains even after updating dependency version, then delete everything present under
C:\Users\[your_username]\.m2\repository\com\fasterxml

And, make sure following dependencies are present:

            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>${jackson.version}</version>
            </dependency>

            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
                <version>${jackson.version}</version>
            </dependency>

            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
                <version>${jackson.version}</version>
            </dependency>

Remove leading or trailing spaces in an entire column of data

If you would like to use a formula, the TRIM function will do exactly what you're looking for:

+----+------------+---------------------+
|    |     A      |           B         |
+----+------------+---------------------+
| 1  | =TRIM(B1)  |  value to trim here |
+----+------------+---------------------+

So to do the whole column...
1) Insert a column
2) Insert TRIM function pointed at cell you are trying to correct.
3) Copy formula down the page
4) Copy inserted column
5) Paste as "Values"

Should be good to go from there...

"Cannot start compilation: the output path is not specified for module..."

I'm answering this so that I can find the solution when I have to google this error again.

Set project compile output path to path_of_the_project_folder/out. That's what is working today. The intellj documentation makes it seem like we can select any folder but that's not the case.

Django ChoiceField

If your choices are not pre-decided or they are coming from some other source, you can generate them in your view and pass it to the form .

Example:

views.py:

def my_view(request, interview_pk):
    interview = Interview.objects.get(pk=interview_pk)
    all_rounds = interview.round_set.order_by('created_at')
    all_round_names = [rnd.name for rnd in all_rounds]
    form = forms.AddRatingForRound(all_round_names)
    return render(request, 'add_rating.html', {'form': form, 'interview': interview, 'rounds': all_rounds})

forms.py

class AddRatingForRound(forms.ModelForm):

    def __init__(self, round_list, *args, **kwargs):
        super(AddRatingForRound, self).__init__(*args, **kwargs)
        self.fields['name'] = forms.ChoiceField(choices=tuple([(name, name) for name in round_list]))

    class Meta:
        model = models.RatingSheet
        fields = ('name', )

template:

<form method="post">
    {% csrf_token %}
    {% if interview %}
         {{ interview }}
    {% endif %}
    {% if rounds %}
    <hr>
        {{ form.as_p }}
        <input type="submit" value="Submit" />
    {% else %}
        <h3>No rounds found</h3>
    {% endif %}

</form>

Parse an URL in JavaScript

If your string is called s then

var id = s.match(/img_id=([^&]+)/)[1]

will give it to you.

What does "./" (dot slash) refer to in terms of an HTML file path location?

Yes, ./ means the current working directory. You can just reference the file directly by name, without it.

How to run a command in the background on Windows?

I'm assuming what you want to do is run a command without an interface (possibly automatically?). On windows there are a number of options for what you are looking for:

  • Best: write your program as a windows service. These will start when no one logs into the server. They let you select the user account (which can be different than your own) and they will restart if they fail. These run all the time so you can automate tasks at specific times or on a regular schedule from within them. For more information on how to write a windows service you can read a tutorial online such as (http://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx).

  • Better: Start the command and hide the window. Assuming the command is a DOS command you can use a VB or C# script for this. See here for more information. An example is:

    Set objShell = WScript.CreateObject("WScript.Shell")
    objShell.Run("C:\yourbatch.bat"), 0, True
    

    You are still going to have to start the command manually or write a task to start the command. This is one of the biggest down falls of this strategy.

  • Worst: Start the command using the startup folder. This runs when a user logs into the computer

Hope that helps some!

How to correctly get image from 'Resources' folder in NetBeans

I have a slightly different approach that might be useful/more beneficial to some.

Under your main project folder, create a resource folder. Your folder structure should look something like this.

  • Project Folder
    • build
    • dist
    • lib
    • nbproject
    • resources
    • src

Go to the properties of your project. You can do this by right clicking on your project in the Projects tab window and selecting Properties in the drop down menu.

Under categories on the left side, select Sources.

In Source Package Folders on the right side, add your resource folder using the Add Folder button. Once you click OK, you should see a Resources folder under your project.

enter image description here

You should now be able to pull resources using this line or similar approach:

MyClass.class.getResource("/main.jpg");

If you were to create a package called Images under the resources folder, you can retrieve the resource like this:

MyClass.class.getResource("/Images/main.jpg");

Changing background color of selected cell?

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

     UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
     cell.contentView.backgroundColor = [UIColor yellowColor];

}

Best way to do Version Control for MS Excel

Let me summarise what you would like to version control and why:

  1. What:

    • Code (VBA)
    • Spreadsheets (Formulae)
    • Spreadsheets (Values)
    • Charts
    • ...
  2. Why:

    • Audit log
    • Collaboration
    • Version comparison ("diffing")
    • Merging

As others have posted here, there are a couple of solutions on top of existing version control systems such as:

  • Git
  • Mercurial
  • Subversion
  • Bazaar

If your only concern is the VBA code in your workbooks, then the approach Demosthenex above proposes or VbaGit (https://github.com/brucemcpherson/VbaGit) work very well working and are relatively simple to implement. The advantages are that you can rely on well proven version control systems and chose one according to your needs (have a look at https://help.github.com/articles/what-are-the-differences-between-svn-and-git/ for a brief comparison between Git and Subversion).

If you not only worry about code but also about the data in your sheets ("hardcoded" values and formula results), you can use a similar strategy for that: Serialise the contents of your sheets into some text format (via Range.Value) and use an existing version control system. Here's a very good blog post about this: https://wiki.ucl.ac.uk/display/~ucftpw2/2013/10/18/Using+git+for+version+control+of+spreadsheet+models+-+part+1+of+3

However, spreadsheet comparison is a non-trivial algorithmic problem. There are a few tools around, such as Microsoft's Spreadsheet Compare (https://support.office.com/en-us/article/Overview-of-Spreadsheet-Compare-13fafa61-62aa-451b-8674-242ce5f2c986), Exceldiff (http://exceldiff.arstdesign.com/) and DiffEngineX (https://www.florencesoft.com/compare-excel-workbooks-differences.html). But it's another challenge to integrate these comparison with a version control system like Git.

Finally, you have to settle on a workflow that suits your needs. For a simple, tailored Git for Excel workflow, have a look at https://www.xltrail.com/blog/git-workflow-for-excel.

Loop code for each file in a directory

Looks for the function glob():

<?php
$files = glob("dir/*.jpg");
foreach($files as $jpg){
    echo $jpg, "\n";
}
?>

Reset local repository branch to be just like remote repository HEAD

Here is a script that automates what the most popular answer suggests ... See https://stackoverflow.com/a/13308579/1497139 for an improved version that supports branches

#!/bin/bash
# reset the current repository
# WF 2012-10-15
# see https://stackoverflow.com/questions/1628088/how-to-reset-my-local-repository-to-be-just-like-the-remote-repository-head
timestamp=`date "+%Y-%m-%d-%H_%M_%S"`
git commit -a -m "auto commit at $timestamp"
if [ $? -eq 0 ]
then
  git branch "auto-save-at-$timestamp" 
fi
git fetch origin
git reset --hard origin/master

Creating a thumbnail from an uploaded image

<?php 
error_reporting(0);

$change="";
$abc="";


 define ("MAX_SIZE","4000");
 function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }

 $errors=0;

 if($_SERVER["REQUEST_METHOD"] == "POST")
 {
    $image =$_FILES["file"]["name"];
    $uploadedfile = $_FILES['file']['tmp_name'];


    if ($image) 
    {

        $filename = stripslashes($_FILES['file']['name']);

        $extension = getExtension($filename);
        $extension = strtolower($extension);


 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
        {

            $change='<div class="msgdiv">Unknown Image extension </div> ';
            $errors=1;
        }
        else
        {

 $size=filesize($_FILES['file']['tmp_name']);


if ($size > MAX_SIZE*1024)
{
    $change='<div class="msgdiv">You have exceeded the size limit!</div> ';
    $errors=1;
}


if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);

}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);

}
else 
{
$src = imagecreatefromgif($uploadedfile);
}

echo $scr;

list($width,$height)=getimagesize($uploadedfile);


$newwidth=45;
$newheight=45;
$tmp=imagecreatetruecolor($newwidth,$newheight);


$newwidth1=90;
$newheight1=90;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);

$tmp2=imagecreatetruecolor($width,$height);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);

imagecopyresampled($tmp2,$src,0,0,0,0,$width,$height,$width,$height);

$filename = "images/1-". $_FILES['file']['name']=time();

$filename1 = "images/2-". $_FILES['file']['name']=time();

$filename2 = "images/3-". $_FILES['file']['name']=time();

imagejpeg($tmp,$filename,100);

imagejpeg($tmp1,$filename1,100);

imagejpeg($tmp2,$filename2,100);

imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}

}
 if(isset($_POST['Submit']) && !$errors) 
 {

   // mysql_query("update {$prefix}users set img='$big',img_small='$small' where user_id='$user'");
    $change=' <div class="msgdiv">Image Uploaded Successfully!</div>';
 }

?>
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>
    <title>picture demo</title>

   <link href=".css" media="screen, projection" rel="stylesheet" type="text/css">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery_002.js"></script>
<script type="text/javascript" src="js/displaymsg.js"></script>
<script type="text/javascript" src="js/ajaxdelete.js"></script>


  <style type="text/css">
  .help
{
font-size:11px; color:#006600;
}
body {
     color: #000000;
 background-color:#999999 ;
    background:#999999 url(<?php echo $user_row['img_src']; ?>) fixed repeat top left;


    font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif; 

    }
        .msgdiv{
    width:759px;
padding-top:8px;
padding-bottom:8px;
background-color: #fff;
font-weight:bold;
font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px;
}
#container{width:763px;margin:0 auto;padding:3px 0;text-align:left;position:relative; -moz-border-radius: 6px;-webkit-border-radius: 6px; background-color:#FFFFFF }
</style>

  </head><body>
     <div align="center" id="err">
<?php echo $change; ?>  </div>
   <div id="space"></div>





  <div id="container" >

   <div id="con">



        <table width="502" cellpadding="0" cellspacing="0" id="main">
          <tbody>
            <tr>
              <td width="500" height="238" valign="top" id="main_right">

              <div id="posts">
              &nbsp;&nbsp;&nbsp;&nbsp;<img src="<?php// echo $filename; ?>" />  &nbsp;&nbsp;&nbsp;&nbsp;<img src="<?php// echo $filename1; ?>"  />
                <form method="post" action="" enctype="multipart/form-data" name="form1">
                <table width="500" border="0" align="center" cellpadding="0" cellspacing="0">
               <tr><Td style="height:25px">&nbsp;</Td></tr>
        <tr>
          <td width="150"><div align="right" class="titles">Picture 
            : </div></td>
          <td width="350" align="left">
            <div align="left">
              <input size="25" name="file" type="file" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10pt" class="box"/>

              </div></td>

        </tr>
        <tr><Td></Td>
        <Td valign="top" height="35px" class="help">Image maximum size <b>4000 </b>kb</span></Td>
        </tr>
        <tr><Td></Td><Td valign="top" height="35px"><input type="submit" id="mybut" value="       Upload        " name="Submit"/></Td></tr>
        <tr>
          <td width="200">&nbsp;</td>
          <td width="200"><table width="200" border="0" cellspacing="0" cellpadding="0">
              <tr>
                <td width="200" align="center"><div align="left"></div></td>
                <td width="100">&nbsp;</td>
              </tr>
          </table></td>
        </tr>
      </table>
    </form>
 </div>
            </td>

        </tr>
          </tbody>
     </table>
   </div>

  </div>



</body></html>

How to convert BigInteger to String in java

//How to solve BigDecimal & BigInteger and return a String.

  BigDecimal x = new BigDecimal( a );
  BigDecimal y = new BigDecimal( b ); 
  BigDecimal result = BigDecimal.ZERO;
  BigDecimal result = x.add(y);
  return String.valueOf(result); 

Eclipse java debugging: source not found

Remove the existing Debug Configuration and create a new one. That should resolve the problem.

Custom Listview Adapter with filter Android

please check below code it will help you

DrawerActivity.userListview
            .setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {

                    int pos = position;
                    Intent intent = new Intent(getContext(),
                            UserDetail.class);
                    intent.putExtra("model", list.get(position));
                    context.startActivity(intent);
                }
            });
    return convertView;
}

@Override
public android.widget.Filter getFilter() {

    return new android.widget.Filter() {

        @Override
        protected void publishResults(CharSequence constraint,
                FilterResults results) {

            ArrayList<UserListModel> updatelist = (ArrayList<UserListModel>) results.values;
            UserListCustomAdaptor newadaptor = new UserListCustomAdaptor(
                    getContext(), getCount(), updatelist);

            if (results.equals(constraint)) {
                updatelist.add(modelobj);
            }
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {

                notifyDataSetInvalidated();
            }
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            FilterResults filterResults = new FilterResults();
            list = new ArrayList<UserListModel>();

            if (constraint != null && DrawerActivity.userlist != null) {

                constraint = constraint.toString().toLowerCase();
                int length = DrawerActivity.userlist.size();
                int i = 0;
                while (i < length) {

                    UserListModel modelobj = DrawerActivity.userlist.get(i);
                    String data = modelobj.getFirstName() + " "
                            + modelobj.getLastName();
                    if (data.toLowerCase().contains(constraint.toString())) {
                        list.add(modelobj);
                    }

                    i++;
                }
                filterResults.values = list;
                filterResults.count = list.size();
            }
            return filterResults;
        }
    };
}

@Override
public int getCount() {
    return list.size();
}

@Override
public UserListModel getItem(int position) {

    return list.get(position);
}

Handle file download from ajax post

For those looking a more modern approach, you can use the fetch API. The following example shows how to download a spreadsheet file. It is easily done with the following code.

fetch(url, {
    body: JSON.stringify(data),
    method: 'POST',
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    },
})
.then(response => response.blob())
.then(response => {
    const blob = new Blob([response], {type: 'application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
    const downloadUrl = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = downloadUrl;
    a.download = "file.xlsx";
    document.body.appendChild(a);
    a.click();
})

I believe this approach to be much easier to understand than other XMLHttpRequest solutions. Also, it has a similar syntax to the jQuery approach, without the need to add any additional libraries.

Of course, I would advise checking to which browser you are developing, since this new approach won't work on IE. You can find the full browser compatibility list on the following [link][1].

Important: In this example I am sending a JSON request to a server listening on the given url. This url must be set, on my example I am assuming you know this part. Also, consider the headers needed for your request to work. Since I am sending a JSON, I must add the Content-Type header and set it to application/json; charset=utf-8, as to let the server know the type of request it will receive.

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

It might be a conflict with the same port specified in docker-compose.yml and docker-compose.override.yml or the same port specified explicitly and using an environment variable.

I had a docker-compose.yml with ports on a container specified using environment variables, and a docker-compose.override.yml with one of the same ports specified explicitly. Apparently docker tried to open both on the same container. docker container ls -a listed neither because the container could not start and list the ports.

jQuery datepicker, onSelect won't work

$('.date-picker').datepicker({
                    autoclose : true,
                    todayHighlight : true,
                    clearBtn: true,
                    format: 'yyyy-mm-dd', 
                    onSelect: function(value, date) { 
                         alert(123);
                    },
                    todayBtn: "linked",
                    startView: 0, maxViewMode: 0,minViewMode:0

                    }).on('changeDate',function(ev){
                    //this is right events ,trust me
                    }
});

No value accessor for form control

In my case, I used Angular forms with contenteditable elements like div and had similar problems before.

I wrote ng-contenteditable module to resolve this problem.

How to change Navigation Bar color in iOS 7?

It's actually easier than the answers I've seen here:

1) Just make sure you select the navigation bar on the Navigation control. 
2) Select the color you want in the bar tint.
3) You have other options too, and/or individually on each view (just play with it).

I hope this helps somebody. I didn't like the answers I saw. I like to keep my code as clean as possible. Not saying that it's wrong to do it programmatically, but there are people out there like me....this is for you guys. Changing color of the navigation bar

Redis: How to access Redis log file

vi /usr/local/etc/redis.conf

Look for dir, logfile

# The working directory.
#
# The DB will be written inside this directory, with the filename specified
# above using the 'dbfilename' configuration directive.
#
# The Append Only File will also be created inside this directory.
#
# Note that you must specify a directory here, not a file name.
dir /usr/local/var/db/redis/



# Specify the log file name. Also the empty string can be used to force
# Redis to log on the standard output. Note that if you use standard
# output for logging but daemonize, logs will be sent to /dev/null 
logfile "redis_log"

So the log file is created at /usr/local/var/db/redis/redis_log with the name redis_log

You can also try MONITOR command from redis-cli to review the number of commands executed.

implements Closeable or implements AutoCloseable

Recently I have read a Java SE 8 Programmer Guide ii Book.

I found something about the difference between AutoCloseable vs Closeable.

The AutoCloseable interface was introduced in Java 7. Before that, another interface existed called Closeable. It was similar to what the language designers wanted, with the following exceptions:

  • Closeable restricts the type of exception thrown to IOException.
  • Closeable requires implementations to be idempotent.

The language designers emphasize backward compatibility. Since changing the existing interface was undesirable, they made a new one called AutoCloseable. This new interface is less strict than Closeable. Since Closeable meets the requirements for AutoCloseable, it started implementing AutoCloseable when the latter was introduced.

How to "z-index" to make a menu always on top of the content

You most probably don't need z-index to do that. You can use relative and absolute positioning.

I advise you to take a better look at css positioning and the difference between relative and absolute positioning... I saw you're setting position: absolute; to an element and trying to float that element. It won't work friend! When you understand positioning in CSS it will make your work a lot easier! ;)

Edit: Just to be clear, positioning is not a replacement for them and I do use z-index. I just try to avoid using them. Using z-indexes everywhere seems easy and fun at first... until you have bugs related to them and find yourself having to revisit and manage z-indexes.

Is it good practice to make the constructor throw an exception?

I am not for throwing Exceptions in the constructor since I am considering this as non-clean. There are several reasons for my opinion.

  1. As Richard mentioned you cannot initialize an instance in an easy manner. Especially in tests it is really annoying to build a test-wide object only by surrounding it in a try-catch during initialization.

  2. Constructors should be logic-free. There is no reason at all to encapsulate logic in a constructor, since you are always aiming for the Separation of Concerns and Single Responsibility Principle. Since the concern of the constructor is to "construct an object" it should not encapsulate any exception handling if following this approach.

  3. It smells like bad design. Imho if I am forced to do exception handling in the constructor I am at first asking myself if I have any design frauds in my class. It is necessary sometimes, but then I outsource this to a builder or factory to keep the constructor as simple as possible.

So if it is necessary to do some exception handling in the constructor, why would you not outsource this logic to a Builder of Factory? It might be a few more lines of code but gives you the freedom to implement a far more robust and well suited exception handling since you can outsource the logic for the exception handling even more and are not sticked to the constructor, which will encapsulate too much logic. And the client does not need to know anything about your constructing logic if you delegate the exception handling properly.

JavaScript math, round to two decimal places

I think the best way I've seen it done is multiplying by 10 to the power of the number of digits, then doing a Math.round, then finally dividing by 10 to the power of digits. Here is a simple function I use in typescript:

function roundToXDigits(value: number, digits: number) {
    value = value * Math.pow(10, digits);
    value = Math.round(value);
    value = value / Math.pow(10, digits);
    return value;
}

Or plain javascript:

function roundToXDigits(value, digits) {
    if(!digits){
        digits = 2;
    }
    value = value * Math.pow(10, digits);
    value = Math.round(value);
    value = value / Math.pow(10, digits);
    return value;
}

What is the standard way to add N seconds to datetime.time in Python?

In a real world environment it's never a good idea to work solely with time, always use datetime, even better utc, to avoid conflicts like overnight, daylight saving, different timezones between user and server etc.

So I'd recommend this approach:

import datetime as dt

_now = dt.datetime.now()  # or dt.datetime.now(dt.timezone.utc)
_in_5_sec = _now + dt.timedelta(seconds=5)

# get '14:39:57':
_in_5_sec.strftime('%H:%M:%S')

Python NameError: name is not defined

You must define the class before creating an instance of the class. Move the invocation of Something to the end of the script.

You can try to put the cart before the horse and invoke procedures before they are defined, but it will be an ugly hack and you will have to roll your own as defined here:

Make function definition in a python file order independent

Cross-Domain Cookies

You can attempt to push the cookie val to another domain using an image tag.

Your mileage may vary when trying to do this because some browsers require you to have a proper P3P Policy on the WebApp2 domain or the browser will reject the cookie.

If you look at plus.google.com p3p policy you will see that their policy is:

CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."

that is the policy they use for their +1 buttons to these cross domain requests.

Another warning is that if you are on https make sure that the image tag is pointing to an https address also otherwise the cookies will not set.

jquery UI dialog: how to initialize without a title bar?

I find it more efficient, and more readable, to use the open event, and hide the title bar from there. I don't like using page-global class name searches.

open: function() { $(this).closest(".ui-dialog").find(".ui-dialog-titlebar:first").hide(); }

Simple.

git with IntelliJ IDEA: Could not read from remote repository

I've resolved this by adding my SSH private key to the ssh-agent in the command:

$ ssh-add -K ~/.ssh/id_rsa

And setting Settings --> Version Control --> Git, and then, in the SSH executable dropdown, choose Native

Convert INT to FLOAT in SQL

In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):

select myintfield + 0.0 as myfloatfield from mytable

While @Heximal's answer works, I don't personally recommend it.

This is because it uses implicit casting. Although you didn't type CAST, either the SUM() or the 0.0 need to be cast to be the same data-types, before the + can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +. But SUM(aFloatField) + 0 does not yield an INT, because the 0 is being implicitly cast to a FLOAT.

I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.

If you want to be explicit, I would use the following.

CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT  requires 8.0

I won't discuss whether NUMERIC or FLOAT *(fixed point, instead of floating point)* is more appropriate, when it comes to rounding errors, etc. I'll just let you google that if you need to, but FLOAT is so massively misused that there is a lot to read about the subject already out there.

You can try the following to see what happens...

CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))

Android Closing Activity Programmatically

What about the Activity.finish() method (quoting) :

Call this when your activity is done and should be closed.

Extract value of attribute node via XPath

//Parent[@id='1']/Children/child/@name 

Your original child[@name] means an element child which has an attribute name. You want child/@name.

m2e error in MavenArchiver.getManifest()

I solved this error in pom.xml by adding the below code

spring-rest-demo org.apache.maven.plugins maven-war-plugin 2.6

Android : difference between invisible and gone?

INVISIBLE:
The view has to be drawn and it takes time.

GONE:
The view doesn't have to be drawn.

What is the difference between print and puts?

The API docs give some good hints:

print() ? nil

print(obj, ...) ? nil

Writes the given object(s) to ios. Returns nil.

The stream must be opened for writing. Each given object that isn't a string will be converted by calling its to_s method. When called without arguments, prints the contents of $_.

If the output field separator ($,) is not nil, it is inserted between objects. If the output record separator ($\) is not nil, it is appended to the output.

...

puts(obj, ...) ? nil

Writes the given object(s) to ios. Writes a newline after any that do not already end with a newline sequence. Returns nil.

The stream must be opened for writing. If called with an array argument, writes each element on a new line. Each given object that isn't a string or array will be converted by calling its to_s method. If called without arguments, outputs a single newline.

Experimenting a little with the points given above, the differences seem to be:

  • Called with multiple arguments, print separates them by the 'output field separator' $, (which defaults to nothing) while puts separates them by newlines. puts also puts a newline after the final argument, while print does not.

    2.1.3 :001 > print 'hello', 'world'
    helloworld => nil 
    2.1.3 :002 > puts 'hello', 'world'
    hello
    world
     => nil
    2.1.3 :003 > $, = 'fanodd'
     => "fanodd" 
    2.1.3 :004 > print 'hello', 'world'
    hellofanoddworld => nil 
    2.1.3 :005 > puts 'hello', 'world'
    hello
    world
     => nil
  • puts automatically unpacks arrays, while print does not:

    2.1.3 :001 > print [1, [2, 3]], [4]
    [1, [2, 3]][4] => nil 
    2.1.3 :002 > puts [1, [2, 3]], [4]
    1
    2
    3
    4
     => nil
  • print with no arguments prints $_ (the last thing read by gets), while puts prints a newline:

    2.1.3 :001 > gets
    hello world
     => "hello world\n" 
    2.1.3 :002 > puts
    
     => nil 
    2.1.3 :003 > print
    hello world
     => nil
  • print writes the output record separator $\ after whatever it prints, while puts ignores this variable:

    mark@lunchbox:~$ irb
    2.1.3 :001 > $\ = 'MOOOOOOO!'
     => "MOOOOOOO!" 
    2.1.3 :002 > puts "Oink! Baa! Cluck! "
    Oink! Baa! Cluck! 
     => nil 
    2.1.3 :003 > print "Oink! Baa! Cluck! "
    Oink! Baa! Cluck! MOOOOOOO! => nil

Python string to unicode

Unicode escapes only work in unicode strings, so this

 a="\u2026"

is actually a string of 6 characters: '\', 'u', '2', '0', '2', '6'.

To make unicode out of this, use decode('unicode-escape'):

a="\u2026"
print repr(a)
print repr(a.decode('unicode-escape'))

## '\\u2026'
## u'\u2026'

Stored procedure return into DataSet in C# .Net

Try this

    DataSet ds = new DataSet("TimeRanges");
    using(SqlConnection conn = new SqlConnection("ConnectionString"))
    {               
            SqlCommand sqlComm = new SqlCommand("Procedure1", conn);               
            sqlComm.Parameters.AddWithValue("@Start", StartTime);
            sqlComm.Parameters.AddWithValue("@Finish", FinishTime);
            sqlComm.Parameters.AddWithValue("@TimeRange", TimeRange);

            sqlComm.CommandType = CommandType.StoredProcedure;

            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = sqlComm;

            da.Fill(ds);
     }

How do I query using fields inside the new PostgreSQL JSON datatype?

With postgres 9.3 use -> for object access. 4 example

seed.rb

se = SmartElement.new
se.data = 
{
    params:
    [
        {
            type: 1,
            code: 1,
            value: 2012,
            description: 'year of producction'
        },
        {
            type: 1,
            code: 2,
            value: 30,
            description: 'length'
        }
    ]
}

se.save

rails c

SELECT data->'params'->0 as data FROM smart_elements;

returns

                                 data
----------------------------------------------------------------------
 {"type":1,"code":1,"value":2012,"description":"year of producction"}
(1 row)

You can continue nesting

SELECT data->'params'->0->'type' as data FROM smart_elements;

return

 data
------
 1
(1 row)

How to manually include external aar package using new Gradle Android Build System

For me, this was an issue with how Android Studio environment was configured.

When I updated the File -> Project Structure -> JDK Location to a later Java version (jdk1.8.0_192.jdk - for me), everything started working.

How to run Linux commands in Java?

You need not store the diff in a 3rd file and then read from in. Instead you make use of the Runtime.exec

Process p = Runtime.getRuntime().exec("diff fileA fileB");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
}

How to define a circle shape in an Android XML drawable file?

a circle shape in an Android XML drawable file

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="@android:color/white" />
    <stroke
        android:width="1.5dp"
        android:color="@android:color/holo_red_light" />
    <size
        android:width="120dp"
        android:height="120dp" />
</shape>

Screenshot

enter image description here

Directory.GetFiles of certain extension

Doesn't the Directory.GetFiles(String, String) overload already do that? You would just do Directory.GetFiles(dir, "*.jpg", SearchOption.AllDirectories)

If you want to put them in a list, then just replace the "*.jpg" with a variable that iterates over a list and aggregate the results into an overall result set. Much clearer than individually specifying them. =)

Something like...

foreach(String fileExtension in extensionList){
    foreach(String file in Directory.GetFiles(dir, fileExtension, SearchOption.AllDirectories)){
        allFiles.Add(file);
    }
}

(If your directories are large, using EnumerateFiles instead of GetFiles can potentially be more efficient)

Error: class X is public should be declared in a file named X.java

This happens when you have 1 name for the Java class on hard disk and another name of Java class in the code!!

For example, I renamed my MainActivity class to MainnActivity only (!) in the code. I got this error immediately.

There is also a visual indicator in the Project tab of Android Studio - a class inside a class, like you have nested classed, but with an error indicator.

The solution is to simply rename class name in the Project tab (SHIFT + F6) to match the name in the Java code.

Mobile Safari: Javascript focus() method on inputfield only works with click?

I managed to make it work with the following code:

event.preventDefault();
timeout(function () {
    $inputToFocus.focus();
}, 500);

I'm using AngularJS so I have created a directive which solved my problem:

Directive:

angular.module('directivesModule').directive('focusOnClear', [
    '$timeout',
    function (timeout) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                var id = attrs.focusOnClear;
                var $inputSearchElement = $(element).parent().find('#' + id);
                element.on('click', function (event) {
                    event.preventDefault();
                    timeout(function () {
                        $inputSearchElement.focus();
                    }, 500);
                });
            }
        };
    }
]);

How to use the directive:

<div>
    <input type="search" id="search">
    <i class="icon-clear" ng-click="clearSearchTerm()" focus-on-clear="search"></i>
</div>

It looks like you are using jQuery, so I don't know if the directive is any help.

Ruby 'require' error: cannot load such file

What about including the current directory in the search path?

ruby -I. main.rb

CSS Auto hide elements after 5 seconds

based from the answer of @SW4, you could also add a little animation at the end.

_x000D_
_x000D_
body > div{_x000D_
    border:1px solid grey;_x000D_
}_x000D_
html, body, #container {_x000D_
    height:100%;_x000D_
    width:100%;_x000D_
    margin:0;_x000D_
    padding:0;_x000D_
}_x000D_
#container {_x000D_
    overflow:hidden;_x000D_
    position:relative;_x000D_
}_x000D_
#hideMe {_x000D_
    -webkit-animation: cssAnimation 5s forwards; _x000D_
    animation: cssAnimation 5s forwards;_x000D_
}_x000D_
@keyframes cssAnimation {_x000D_
    0%   {opacity: 1;}_x000D_
    90%  {opacity: 1;}_x000D_
    100% {opacity: 0;}_x000D_
}_x000D_
@-webkit-keyframes cssAnimation {_x000D_
    0%   {opacity: 1;}_x000D_
    90%  {opacity: 1;}_x000D_
    100% {opacity: 0;}_x000D_
}
_x000D_
<div>_x000D_
<div id='container'>_x000D_
    <div id='hideMe'>Wait for it...</div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Making the remaining 0.5 seconds to animate the opacity attribute. Just make sure to do the math if you're changing the length, in this case, 90% of 5 seconds leaves us 0.5 seconds to animate the opacity.

How to run mvim (MacVim) from Terminal?

If you have homeBrew installed, this is all you have to do:

brew install macvim
brew linkapps

Then type mvim in your terminal to run MacVim.

How do I get an apk file from an Android device?

This will help for someone who is looking for a non technical answer

This is simple hack

Download the application App Share/Send Pro from google play store. Select the app you want to send and method send application.

I usually use Bluetooth to send applications to my pc or another phone.

Rotating x axis labels in R for barplot

Rotate the x axis labels with angle equal or smaller than 90 degrees using base graphics. Code adapted from the R FAQ:

par(mar = c(7, 4, 2, 2) + 0.2) #add room for the rotated labels

#use mtcars dataset to produce a barplot with qsec colum information
mtcars = mtcars[with(mtcars, order(-qsec)), ] #order mtcars data set by column "qsec"

end_point = 0.5 + nrow(mtcars) + nrow(mtcars) - 1 #this is the line which does the trick (together with barplot "space = 1" parameter)

barplot(mtcars$qsec, col = "grey50", 
        main = "",
        ylab = "mtcars - qsec", ylim = c(0,5 + max(mtcars$qsec)),
        xlab = "",
        space = 1)
#rotate 60 degrees (srt = 60)
text(seq(1.5, end_point, by = 2), par("usr")[3]-0.25, 
     srt = 60, adj = 1, xpd = TRUE,
     labels = paste(rownames(mtcars)), cex = 0.65)

enter image description here

Python: convert string from UTF-8 to Latin-1

Can you provide more details about what you are trying to do? In general, if you have a unicode string, you can use encode to convert it into string with appropriate encoding. Eg:

>>> a = u"\u00E1"
>>> type(a)
<type 'unicode'>
>>> a.encode('utf-8')
'\xc3\xa1'
>>> a.encode('latin-1')
'\xe1'

Deserialize JSON string to c# object

Use this code:

var result=JsonConvert.DeserializeObject<List<yourObj>>(jsonString);

mysql.h file can't be found

For CentOS/RHEL:

yum install mysql-devel -y

Oracle Date TO_CHAR('Month DD, YYYY') has extra spaces in it

try this:-

select to_char(to_date('01/10/2017','dd/mm/yyyy'),'fmMonth fmDD,YYYY') from dual;

select to_char(sysdate,'fmMonth fmDD,YYYY') from dual;

Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio?

In SSMS, "Query" menu item... "Results to"... "Results to File"

Shortcut = CTRL+shift+F

You can set it globally too

"Tools"... "Options"... "Query Results"... "SQL Server".. "Default destination" drop down

Edit: after comment

In SSMS, "Query" menu item... "SQLCMD" mode

This allows you to run "command line" like actions.

A quick test in my SSMS 2008

:OUT c:\foo.txt
SELECT * FROM sys.objects

Edit, Sep 2012

:OUT c:\foo.txt
SET NOCOUNT ON;SELECT * FROM sys.objects

How to debug Google Apps Script (aka where does Logger.log log to?)

2017 Update: Stackdriver Logging is now available for Google Apps Script. From the menu bar in the script editor, goto: View > Stackdriver Logging to view or stream the logs.

console.log() will write DEBUG level messages

Example onEdit() logging:

function onEdit (e) {
  var debug_e = {
    authMode:  e.authMode,  
    range:  e.range.getA1Notation(),    
    source:  e.source.getId(),
    user:  e.user,   
    value:  e.value,
    oldValue: e. oldValue
  }

  console.log({message: 'onEdit() Event Object', eventObject: debug_e});
}

Then check the logs in the Stackdriver UI labeled onEdit() Event Object to see the output

Excel VBA: AutoFill Multiple Cells with Formulas

The approach you're looking for is FillDown. Another way so you don't have to kick your head off every time is to store formulas in an array of strings. Combining them gives you a powerful method of inputting formulas by the multitude. Code follows:

Sub FillDown()

    Dim strFormulas(1 To 3) As Variant

    With ThisWorkbook.Sheets("Sheet1")
        strFormulas(1) = "=SUM(A2:B2)"
        strFormulas(2) = "=PRODUCT(A2:B2)"
        strFormulas(3) = "=A2/B2"

        .Range("C2:E2").Formula = strFormulas
        .Range("C2:E11").FillDown
    End With

End Sub

Screenshots:

Result as of line: .Range("C2:E2").Formula = strFormulas:

enter image description here

Result as of line: .Range("C2:E11").FillDown:

enter image description here

Of course, you can make it dynamic by storing the last row into a variable and turning it to something like .Range("C2:E" & LRow).FillDown, much like what you did.

Hope this helps!

How to change MySQL data directory?

I wanted to keep a database on my machine, but also have a data on my external hard drive, and switch between using the two.

If you are on a Mac, and installed MySQL using Homebrew, this should work for you. Otherwise, you will just need to substitute the appropriate locations for the MySQL datadir on your machine.

#cd to my data dir location
cd /usr/local/var/

#copy contents of local data directory to the new location
cp -r mysql/ /Volumes/myhd/mydatadir/

#temporarily move the old datadir
mv mysql mysql.local

#symlink to the new location
ln -s /Volumes/myhd/mydatadir mysql

Then to when you want to switch back simply do:

mv mysql mysql.remote

mv mysql.local mysql

and you are using your local database again. Hope that helps.

How do I undo a checkout in git?

You probably want git checkout master, or git checkout [branchname].

selecting from multi-index pandas

You can also use query which is very readable in my opinion and straightforward to use:

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [10, 20, 50, 80], 'C': [6, 7, 8, 9]})
df = df.set_index(['A', 'B'])

      C
A B    
1 10  6
2 20  7
3 50  8
4 80  9

For what you had in mind you can now simply do:

df.query('A == 1')

      C
A B    
1 10  6

You can also have more complex queries using and

df.query('A >= 1 and B >= 50')

      C
A B    
3 50  8
4 80  9

and or

df.query('A == 1 or B >= 50')

      C
A B    
1 10  6
3 50  8
4 80  9

You can also query on different index levels, e.g.

df.query('A == 1 or C >= 8')

will return

      C
A B    
1 10  6
3 50  8
4 80  9

If you want to use variables inside your query, you can use @:

b_threshold = 20
c_threshold = 8

df.query('B >= @b_threshold and C <= @c_threshold')

      C
A B    
2 20  7
3 50  8

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

you can't call sendRedirect(), after you have already used forward(). So, you get that exception.

How do I prevent mails sent through PHP mail() from going to spam?

Try PHP Mailer library.
Or Send mail through SMTP filter it before sending it.
Also Try to give all details like FROM, return-path.

How to send 500 Internal Server Error error from a PHP script

Your code should look like:

<?php
if ( that_happened ) {
    header("HTTP/1.0 500 Internal Server Error");
    die();
}

if ( something_else_happened ) {
    header("HTTP/1.0 500 Internal Server Error");
    die();
}

// Your function should return FALSE if something goes wrong
if ( !update_database() ) {
    header("HTTP/1.0 500 Internal Server Error");
    die();
}

// the script can also fail on the above line
// e.g. a mysql error occurred


header('HTTP/1.1 200 OK');
?>

I assume you stop execution if something goes wrong.

Unstage a deleted file in git

I tried the above solutions and I was still having difficulties. I had other files staged with two files that were deleted accidentally.

To undo the two deleted files I had to unstage all of the files:

git reset HEAD .

At that point I was able to do the checkout of the deleted items:

git checkout -- WorkingFolder/FileName.ext

Finally I was able to restage the rest of the files and continue with my commit.

Return anonymous type results?

Now I realize that the compiler won't let me return a set of anonymous types since it's expecting Dogs, but is there a way to return this without having to create a custom type?

Use use object to return a list of Anonymous types without creating a custom type. This will work without the compiler error (in .net 4.0). I returned the list to the client and then parsed it on JavaScript:

public object GetDogsWithBreedNames()
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
                 join b in db.Breeds on d.BreedId equals b.BreedId
                 select new
                        {
                            Name = d.Name,
                            BreedName = b.BreedName
                        };
    return result;
}

YouTube embedded video: set different thumbnail

This tool gave me following results which helps me achieve the task as following code.

<div onclick="play();" id="vidwrap" style="height:315px;width:560px;background: black url('http://example.com/image.jpg') no-repeat center;overflow:hidden;cursor:pointer;"></div>
<script type="text/javascript">
    function play(){
        document.getElementById('vidwrap').innerHTML = '<iframe width="560" height="315" src="http://www.youtube.com/embed/xxxxxxxxx?autoplay=1" frameborder="0"></iframe>';
    }
</script>

Lock, mutex, semaphore... what's the difference?

It is a general vision. Details are depended on real language realisation

lock - thread synchronization tool. When thread get a lock it becomes a single thread which is able to execute a block of code. All others thread are blocked. Only thread which owns by lock can unlock it

mutex - mutual exclusion lock. It is a kind of lock. On some languages it is inter-process mechanism, on some languages it is a synonym of lock. For example Java uses lock in synchronised and java.util.concurrent.locks.Lock

semaphore - allows a number of threads to access a shared resource. You can find that mutex also can be implemented by semaphore. It is a standalone object which manage an access to shared resource. You can find that any thread can signal and unblock. Also it is used for signalling

[iOS lock, mutex, semaphore]

Best way to check for nullable bool in a condition expression (if ...)

I think its up to you. I certainly think the .HasValue approach is more readable, especially with developers not familiar with the ?? syntax.

The other point of a nullable boolean type is that it is tristate, so you may want to do something else when it is just null, and not default to false.

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

The route engine uses the same sequence as you add rules into it. Once it gets the first matched rule, it will stop checking other rules and take this to search for controller and action.

So, you should:

  1. Put your specific rules ahead of your general rules(like default), which means use RouteTable.Routes.MapHttpRoute to map "WithActionApi" first, then "DefaultApi".

  2. Remove the defaults: new { id = System.Web.Http.RouteParameter.Optional } parameter of your "WithActionApi" rule because once id is optional, url like "/api/{part1}/{part2}" will never goes into "DefaultApi".

  3. Add an named action to your "DefaultApi" to tell the route engine which action to enter. Otherwise once you have more than one actions in your controller, the engine won't know which one to use and throws "Multiple actions were found that match the request: ...". Then to make it matches your Get method, use an ActionNameAttribute.

So your route should like this:

// Map this rule first
RouteTable.Routes.MapRoute(
     "WithActionApi",
     "api/{controller}/{action}/{id}"
 );

RouteTable.Routes.MapRoute(
    "DefaultApi",
    "api/{controller}/{id}",
    new { action="DefaultAction", id = System.Web.Http.RouteParameter.Optional }
);

And your controller:

[ActionName("DefaultAction")] //Map Action and you can name your method with any text
public string Get(int id)
{
    return "object of id id";
}        

[HttpGet]
public IEnumerable<string> ByCategoryId(int id)
{
    return new string[] { "byCategory1", "byCategory2" };
}

A potentially dangerous Request.Form value was detected from the client

The other solutions here are nice, however it's a bit of a royal pain in the rear to have to apply [AllowHtml] to every single Model property, especially if you have over 100 models on a decent sized site.

If like me, you want to turn this (IMHO pretty pointless) feature off site wide you can override the Execute() method in your base controller (if you don't already have a base controller I suggest you make one, they can be pretty useful for applying common functionality).

    protected override void Execute(RequestContext requestContext)
    {
        // Disable requestion validation (security) across the whole site
        ValidateRequest = false;
        base.Execute(requestContext);
    }

Just make sure that you are HTML encoding everything that is pumped out to the views that came from user input (it's default behaviour in ASP.NET MVC 3 with Razor anyway, so unless for some bizarre reason you are using Html.Raw() you shouldn't require this feature.

How can I Remove .DS_Store files from a Git repository?

If you are unable to remove the files because they have changes staged use:

git rm --cached -f *.DS_Store

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

This feature has been built-in into Atom editor (see: symbols-view package), but you need to generate ctags symbols file for your project GH-9, GH-20.

To do that, install ctags command (e.g. brew install ctags on macOS), then:

  1. Append, link or copy ctags-config to your ~/.ctags, example on macOS:

    ln -vs "$(find /Applications/Atom.app -name ctags-config -print -quit)" ~/.ctags
    
  2. Go to your project folder and run:

    cd your/project/directory
    ctags -R .
    
  3. Restart Atom editor.


Alternatively you can use symbol-gen package to generate ctags symbols file for your project based on the options found in .ctags file. You can install it from Atom Package Manager by: apm install symbol-gen. Then hit CMD-Alt-G to generate tags file for your project.


After following above, you can use Go To Declaration option from the context menu.

On macOS you can use also use the following keyboard shortcuts:

  • CMD-R to jump to a function/method in the current ,editor
  • Alt-CMD-Down to go to declaration.

How to process each output line in a loop?

Without any iteration with the --line-buffered grep option:

your_command | grep --line-buffered "your search"

Real life exemple with a Symfony PHP Framework router debug command ouput, to grep all "api" related routes:

php bin/console d:r | grep --line-buffered "api"

pandas: best way to select all columns whose names start with X

Just perform a list comprehension to create your columns:

In [28]:

filter_col = [col for col in df if col.startswith('foo')]
filter_col
Out[28]:
['foo.aa', 'foo.bars', 'foo.fighters', 'foo.fox', 'foo.manchu']
In [29]:

df[filter_col]
Out[29]:
   foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu
0     1.0         0             0        2         NA
1     2.1         0             1        4          0
2     NaN         0           NaN        1          0
3     4.7         0             0        0          0
4     5.6         0             0        0          0
5     6.8         1             0        5          0

Another method is to create a series from the columns and use the vectorised str method startswith:

In [33]:

df[df.columns[pd.Series(df.columns).str.startswith('foo')]]
Out[33]:
   foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu
0     1.0         0             0        2         NA
1     2.1         0             1        4          0
2     NaN         0           NaN        1          0
3     4.7         0             0        0          0
4     5.6         0             0        0          0
5     6.8         1             0        5          0

In order to achieve what you want you need to add the following to filter the values that don't meet your ==1 criteria:

In [36]:

df[df[df.columns[pd.Series(df.columns).str.startswith('foo')]]==1]
Out[36]:
   bar.baz  foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu nas.foo
0      NaN       1       NaN           NaN      NaN        NaN     NaN
1      NaN     NaN       NaN             1      NaN        NaN     NaN
2      NaN     NaN       NaN           NaN        1        NaN     NaN
3      NaN     NaN       NaN           NaN      NaN        NaN     NaN
4      NaN     NaN       NaN           NaN      NaN        NaN     NaN
5      NaN     NaN         1           NaN      NaN        NaN     NaN

EDIT

OK after seeing what you want the convoluted answer is this:

In [72]:

df.loc[df[df[df.columns[pd.Series(df.columns).str.startswith('foo')]] == 1].dropna(how='all', axis=0).index]
Out[72]:
   bar.baz  foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu nas.foo
0      5.0     1.0         0             0        2         NA      NA
1      5.0     2.1         0             1        4          0       0
2      6.0     NaN         0           NaN        1          0       1
5      6.8     6.8         1             0        5          0       0

jQuery prevent change for select

I was looking for "javascript prevent select change" on Google and this question comes at first result. At the end my solution was:

const $select = document.querySelector("#your_select_id");
let lastSelectedIndex = $select.selectedIndex;
// We save the last selected index on click
$select.addEventListener("click", function () {
    lastSelectedIndex = $select.selectedIndex;
});

// And then, in the change, we select it if the user does not confirm
$select.addEventListener("change", function (e) {
    if (!confirm("Some question or action")) {
        $select.selectedIndex = lastSelectedIndex;
        return;
    }
    // Here do whatever you want; the user has clicked "Yes" on the confirm
    // ...
});

I hope it helps to someone who is looking for this and does not have jQuery :)

ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

I also face the similar Issue. Nothing programmer has to do to resolve this error. I informed to my oracle DBA team. They kill the session and worked like a charm.

how to remove json object key and value.?

There are several ways to do this, lets see them one by one:

  1. delete method: The most common way

_x000D_
_x000D_
const myObject = {_x000D_
    "employeeid": "160915848",_x000D_
    "firstName": "tet",_x000D_
    "lastName": "test",_x000D_
    "email": "[email protected]",_x000D_
    "country": "Brasil",_x000D_
    "currentIndustry": "aaaaaaaaaaaaa",_x000D_
    "otherIndustry": "aaaaaaaaaaaaa",_x000D_
    "currentOrganization": "test",_x000D_
    "salary": "1234567"_x000D_
};_x000D_
_x000D_
delete myObject['currentIndustry'];_x000D_
// OR delete myObject.currentIndustry;_x000D_
  _x000D_
console.log(myObject);
_x000D_
_x000D_
_x000D_

  1. By making key value undefined: Alternate & a faster way:

_x000D_
_x000D_
let myObject = {_x000D_
    "employeeid": "160915848",_x000D_
    "firstName": "tet",_x000D_
    "lastName": "test",_x000D_
    "email": "[email protected]",_x000D_
    "country": "Brasil",_x000D_
    "currentIndustry": "aaaaaaaaaaaaa",_x000D_
    "otherIndustry": "aaaaaaaaaaaaa",_x000D_
    "currentOrganization": "test",_x000D_
    "salary": "1234567"_x000D_
  };_x000D_
_x000D_
myObject.currentIndustry = undefined;_x000D_
myObject = JSON.parse(JSON.stringify(myObject));_x000D_
_x000D_
console.log(myObject);
_x000D_
_x000D_
_x000D_

  1. With es6 spread Operator:

_x000D_
_x000D_
const myObject = {_x000D_
    "employeeid": "160915848",_x000D_
    "firstName": "tet",_x000D_
    "lastName": "test",_x000D_
    "email": "[email protected]",_x000D_
    "country": "Brasil",_x000D_
    "currentIndustry": "aaaaaaaaaaaaa",_x000D_
    "otherIndustry": "aaaaaaaaaaaaa",_x000D_
    "currentOrganization": "test",_x000D_
    "salary": "1234567"_x000D_
};_x000D_
_x000D_
_x000D_
const {currentIndustry, ...filteredObject} = myObject;_x000D_
console.log(filteredObject);
_x000D_
_x000D_
_x000D_

Or if you can use omit() of underscore js library:

const filteredObject = _.omit(currentIndustry, 'myObject');
console.log(filteredObject);

When to use what??

If you don't wanna create a new filtered object, simply go for either option 1 or 2. Make sure you define your object with let while going with the second option as we are overriding the values. Or else you can use any of them.

hope this helps :)

Running the new Intel emulator for Android

Not every processor is supporting the virtualization!

To find out your chipset abilities go to http://ark.intel.com/, insert the name of your processor in the search line and check out the resolve.

Advanced Technologies: ...

Intel® Virtualization Technology (VT-x) = ???

If you see "No", you can forget HAXM!

Select rows which are not present in other table

There are basically 4 techniques for this task, all of them standard SQL.

NOT EXISTS

Often fastest in Postgres.

SELECT ip 
FROM   login_log l 
WHERE  NOT EXISTS (
   SELECT  -- SELECT list mostly irrelevant; can just be empty in Postgres
   FROM   ip_location
   WHERE  ip = l.ip
   );

Also consider:

LEFT JOIN / IS NULL

Sometimes this is fastest. Often shortest. Often results in the same query plan as NOT EXISTS.

SELECT l.ip 
FROM   login_log l 
LEFT   JOIN ip_location i USING (ip)  -- short for: ON i.ip = l.ip
WHERE  i.ip IS NULL;

EXCEPT

Short. Not as easily integrated in more complex queries.

SELECT ip 
FROM   login_log

EXCEPT ALL  -- "ALL" keeps duplicates and makes it faster
SELECT ip
FROM   ip_location;

Note that (per documentation):

duplicates are eliminated unless EXCEPT ALL is used.

Typically, you'll want the ALL keyword. If you don't care, still use it because it makes the query faster.

NOT IN

Only good without NULL values or if you know to handle NULL properly. I would not use it for this purpose. Also, performance can deteriorate with bigger tables.

SELECT ip 
FROM   login_log
WHERE  ip NOT IN (
   SELECT DISTINCT ip  -- DISTINCT is optional
   FROM   ip_location
   );

NOT IN carries a "trap" for NULL values on either side:

Similar question on dba.SE targeted at MySQL:

TypeError: string indices must be integers, not str // working with dict

Actually I think that more general approach to loop through dictionary is to use iteritems():

# get tuples of term, courses
for term, term_courses in courses.iteritems():
    # get tuples of course number, info
    for course, info in term_courses.iteritems():
        # loop through info
        for k, v in info.iteritems():
            print k, v

output:

assistant Peter C.
prereq cs101
...
name Programming a Robotic Car
teacher Sebastian

Or, as Matthias mentioned in comments, if you don't need keys, you can just use itervalues():

for term_courses in courses.itervalues():
    for info in term_courses.itervalues():
        for k, v in info.iteritems():
            print k, v

How can I decrypt a password hash in PHP?

The passwords cannot be decrypted as will makes a vulnerability for users. So, you can simply use password_verify() method to compare the passwords.

if(password_verify($upass, $userRow['user_pass'])){
     //code for redirecting to login screen }

where, $upass is password entered by user and $userRow['user_pass'] is user_pass field in database which is encrypted by password_hash() function.

"SetPropertiesRule" warning message when starting Tomcat from Eclipse

From Eclipse Newsgroup:

The warning about the source property is new with Tomcat 6.0.16 and may be ignored. WTP adds a "source" attribute to identify which project in the workspace is associated with the context. The fact that the Context object in Tomcat has no corresponding source property doesn't cause any problems.

I realize that this doesn't answer how to get rid of the warning, but I hope it helps.

Numpy Resize/Rescale Image

For people coming here from Google looking for a fast way to downsample images in numpy arrays for use in Machine Learning applications, here's a super fast method (adapted from here ). This method only works when the input dimensions are a multiple of the output dimensions.

The following examples downsample from 128x128 to 64x64 (this can be easily changed).

Channels last ordering

# large image is shape (128, 128, 3)
# small image is shape (64, 64, 3)
input_size = 128
output_size = 64
bin_size = input_size // output_size
small_image = large_image.reshape((output_size, bin_size, 
                                   output_size, bin_size, 3)).max(3).max(1)

Channels first ordering

# large image is shape (3, 128, 128)
# small image is shape (3, 64, 64)
input_size = 128
output_size = 64
bin_size = input_size // output_size
small_image = large_image.reshape((3, output_size, bin_size, 
                                      output_size, bin_size)).max(4).max(2)

For grayscale images just change the 3 to a 1 like this:

Channels first ordering

# large image is shape (1, 128, 128)
# small image is shape (1, 64, 64)
input_size = 128
output_size = 64
bin_size = input_size // output_size
small_image = large_image.reshape((1, output_size, bin_size,
                                      output_size, bin_size)).max(4).max(2)

This method uses the equivalent of max pooling. It's the fastest way to do this that I've found.

Apache redirect to another port

Try this one-

<VirtualHost *:80> 
  ProxyPreserveHost On
  ProxyRequests Off
  ServerName www.adminbackend.example.com
  ServerAlias adminbackend.example.com
  ProxyPass / http://localhost:6000/
  ProxyPassReverse / http://localhost:6000/
  ErrorLog ${APACHE_LOG_DIR}/error.log
  CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost> 

Where can I find jenkins restful api reference?

Jenkins has a link to their REST API in the bottom right of each page. This link appears on every page of Jenkins and points you to an API output for the exact page you are browsing. That should provide some understanding into how to build the API URls.

You can additionally use some wrapper, like I do, in Python, using http://jenkinsapi.readthedocs.io/en/latest/

Here is their website: https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API

ERROR: ld.so: object LD_PRELOAD cannot be preloaded: ignored

It means the path you input caused an error. In your LD_PRELOAD command, modify the path like the error tips:

/usr/lib/liblunar-calendar-preload.so

Is there an "exists" function for jQuery?

I just like to use plain vanilla javascript to do this.

function isExists(selector){
  return document.querySelectorAll(selector).length>0;
}

In C# check that filename is *possibly* valid (not that it exists)

I've had luck using regular expressions as others have shown.

One thing to keep in mind is that Windows at least prohibits some filenames that otherwise containlegal characters. A few come to mind: com, nul, prn.

I don't have it with me now, but I have a regex that takes these filename into consideration. If you want I can post it, otherwise I'm sure you can find it the same way I did: Google.

-Jay

How to remove line breaks from a file in Java?

As noted in other answers, your code is not working primarily because String.replace(...) does not change the target String. (It can't - Java strings are immutable!) What replace actually does is to create and return a new String object with the characters changed as required. But your code then throws away that String ...


Here are some possible solutions. Which one is most correct depends on what exactly you are trying to do.

// #1
text = text.replace("\n", "");

Simply removes all the newline characters. This does not cope with Windows or Mac line terminations.

// #2
text = text.replace(System.getProperty("line.separator"), "");

Removes all line terminators for the current platform. This does not cope with the case where you are trying to process (for example) a UNIX file on Windows, or vice versa.

// #3
text = text.replaceAll("\\r|\\n", "");

Removes all Windows, UNIX or Mac line terminators. However, if the input file is text, this will concatenate words; e.g.

Goodbye cruel
world.

becomes

Goodbye cruelworld.

So you might actually want to do this:

// #4
text = text.replaceAll("\\r\\n|\\r|\\n", " ");

which replaces each line terminator with a space1. Since Java 8 you can also do this:

// #5
text = text.replaceAll("\\R", " ");

And if you want to replace multiple line terminator with one space:

// #6
text = text.replaceAll("\\R+", " ");

1 - Note there is a subtle difference between #3 and #4. The sequence \r\n represents a single (Windows) line terminator, so we need to be careful not to replace it with two spaces.

Can't install any package with node npm

If anyone is specifically getting Unexpected token <, and your package.json is fine, check your npm-shrinkwrap.json file! I had unresolved merge issues in mine, and fixing that resolved everything.

What are passive event listeners?

Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.

It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.

Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart and touchmove handlers, which may prevent the scroll entirely by calling preventDefault() on the event.

Solution: {passive: true}

By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

document.addEventListener("touchstart", function(e) {
    console.log(e.defaultPrevented);  // will be false
    e.preventDefault();   // does nothing since the listener is passive
    console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);

DOM Spec , Demo Video , Explainer Doc

ProgressDialog spinning circle

Just change from ProgressDialog to ProgressBar in a layout:

res/layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        //Your content here
     </LinearLayout>

        <ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:visibility="gone"
            android:indeterminateDrawable="@drawable/progress" >
        </ProgressBar>
</RelativeLayout>

src/yourPackage/YourActivity.java

public class YourActivity extends Activity{

private ProgressBar bar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout);
    bar = (ProgressBar) this.findViewById(R.id.progressBar);
    new ProgressTask().execute();
}
private class ProgressTask extends AsyncTask <Void,Void,Void>{
    @Override
    protected void onPreExecute(){
        bar.setVisibility(View.VISIBLE);
    }

    @Override
    protected Void doInBackground(Void... arg0) {   
           //my stuff is here
    }

    @Override
    protected void onPostExecute(Void result) {
          bar.setVisibility(View.GONE);
    }
}
}

drawable/progress.xml This is a custom ProgressBar that i use to change the default colors.

<?xml version="1.0" encoding="utf-8"?>

<!-- 
    Duration = 1 means that one rotation will be done in 1 second. leave it.
    If you want to speed up the rotation, increase duration value. 
    in example 1080 shows three times faster revolution. 
    make the value multiply of 360, or the ring animates clunky 
-->
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="1"
    android:toDegrees="360" >

    <shape
        android:innerRadiusRatio="3"
        android:shape="ring"
        android:thicknessRatio="8"
        android:useLevel="false" >
        <size
            android:height="48dip"
            android:width="48dip" />

        <gradient
            android:centerColor="@color/color_preloader_center"
            android:centerY="0.50"
            android:endColor="@color/color_preloader_end"
            android:startColor="@color/color_preloader_start"
            android:type="sweep"
            android:useLevel="false" />
    </shape>

</rotate>

How is CountDownLatch used in Java Multithreading?

NikolaB explained it very well, However example would be helpful to understand, So here is one simple example...

 import java.util.concurrent.*;


  public class CountDownLatchExample {

  public static class ProcessThread implements Runnable {

    CountDownLatch latch;
    long workDuration;
    String name;

    public ProcessThread(String name, CountDownLatch latch, long duration){
        this.name= name;
        this.latch = latch;
        this.workDuration = duration;
    }


    public void run() {
        try {
            System.out.println(name +" Processing Something for "+ workDuration/1000 + " Seconds");
            Thread.sleep(workDuration);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name+ "completed its works");
        //when task finished.. count down the latch count...

        // basically this is same as calling lock object notify(), and object here is latch
        latch.countDown();
    }
}


public static void main(String[] args) {
    // Parent thread creating a latch object
    CountDownLatch latch = new CountDownLatch(3);

    new Thread(new ProcessThread("Worker1",latch, 2000)).start(); // time in millis.. 2 secs
    new Thread(new ProcessThread("Worker2",latch, 6000)).start();//6 secs
    new Thread(new ProcessThread("Worker3",latch, 4000)).start();//4 secs


    System.out.println("waiting for Children processes to complete....");
    try {
        //current thread will get notified if all chidren's are done 
        // and thread will resume from wait() mode.
        latch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println("All Process Completed....");

    System.out.println("Parent Thread Resuming work....");



     }
  }

FIFO class in Java

Queues are First In First Out structures. You request is pretty vague, but I am guessing that you need only the basic functionality which usually comes out with Queue structures. You can take a look at how you can implement it here.

With regards to your missing package, it is most likely because you will need to either download or create the package yourself by following that tutorial.

Pandas: Subtracting two date columns and the result being an integer

How about:

df_test['Difference'] = (df_test['First_Date'] - df_test['Second Date']).dt.days

This will return difference as int if there are no missing values(NaT) and float if there is.

What is the curl error 52 "empty reply from server"?

this error also can happen if the server is processing the data. It usually happens to me when I do post some files to REST API websites that have many entries and take long for the records creation and return

Put Excel-VBA code in module or sheet?

In my experience it's best to put as much code as you can into well-named modules, and only put as much code as you need to into the actual worksheet objects.

Example: Any code that uses worksheet events like Worksheet_SelectionChange or Worksheet_Calculate.

PHP call Class method / function

Create object for the class and call, if you want to call it from other pages.

$obj = new Functions();

$var = $obj->filter($_GET['params']);

Or inside the same class instances [ methods ], try this.

$var = $this->filter($_GET['params']);

Angular2 *ngIf check object array length in template

You can use

<div class="col-sm-12" *ngIf="event.attendees?.length">

Without event.attendees?.length > 0 or even event.attendees?length != 0

Because ?.length already return boolean value.

If in array will be something it will display it else not.

How to get the first day of the current week and month?

Get First date of next month:-

SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy");
String selectedDate="MM-dd-yyyy like 07-02-2018";
Date dt = df.parse(selectedDate);`enter code here`
calendar = Calendar.getInstance();
calendar.setTime(dt);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH) + 1);

String firstDate = df.format(calendar.getTime());
System.out.println("firstDateof next month ==>" + firstDate);

FIND_IN_SET() vs IN()

To get the all related companies name, not based on particular Id.

SELECT 
    (SELECT GROUP_CONCAT(cmp.cmpny_name) 
    FROM company cmp 
    WHERE FIND_IN_SET(cmp.CompanyID, odr.attachedCompanyIDs)
    ) AS COMPANIES
FROM orders odr

Meaning of - <?xml version="1.0" encoding="utf-8"?>

An XML declaration is not required in all XML documents; however XHTML document authors are strongly encouraged to use XML declarations in all their documents. Such a declaration is required when the character encoding of the document is other than the default UTF-8 or UTF-16 and no encoding was determined by a higher-level protocol. Here is an example of an XHTML document. In this example, the XML declaration is included.

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE html 
 PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Virtual Library</title>
  </head>
  <body>
    <p>Moved to <a href="http://example.org/">example.org</a>.</p>
 </body>
</html>

Please refer to the W3 standards for XML.

Assignment makes pointer from integer without cast

  • 1) Don't use gets! You're introducing a buffer-overflow vulnerability. Use fgets(..., stdin) instead.

  • 2) In strToLower you're returning a char instead of a char-array. Either return char* as Autopulated suggested, or just return void since you're modifying the input anyway. As a result, just write

 

 strToLower(cString1);
 strToLower(cString2);
  • 3) To compare case-insensitive strings, you can use strcasecmp (Linux & Mac) or stricmp (Windows).

PHP substring extraction. Get the string before the first '/' or the whole string

You can try using a regex like this:

$s = preg_replace('|/.*$|', '', $s);

sometimes, regex are slower though, so if performance is an issue, make sure to benchmark this properly and use an other alternative with substrings if it's more suitable for you.

Xcode doesn't see my iOS device but iTunes does

To others who might have the same issue and the answers above don't work: Make sure that the iOS version installed on your device matches the iOS SDK version you have installed on your mac. If these don't match you are unable to build to the device.

Change bootstrap navbar background color and font color

Most likely these classes are already defined by Bootstrap, make sure that your CSS file that you want to override the classes with is called AFTER the Bootstrap CSS.

<link rel="stylesheet" href="css/bootstrap.css" /> <!-- Call Bootstrap first -->
<link rel="stylesheet" href="css/bootstrap-override.css" /> <!-- Call override CSS second -->

Otherwise, you can put !important at the end of your CSS like this: color:#ffffff!important; but I would advise against using !important at all costs.

ReactJS: Warning: setState(...): Cannot update during an existing state transition

Looks like you're accidentally calling the handleButtonChange method in your render method, you probably want to do onClick={() => this.handleButtonChange(false)} instead.

If you don't want to create a lambda in the onClick handler, I think you'll need to have two bound methods, one for each parameter.

In the constructor:

this.handleButtonChangeRetour = this.handleButtonChange.bind(this, true);
this.handleButtonChangeSingle = this.handleButtonChange.bind(this, false);

And in the render method:

<Button href="#" active={!this.state.singleJourney} onClick={this.handleButtonChangeSingle} >Retour</Button>
<Button href="#" active={this.state.singleJourney} onClick={this.handleButtonChangeRetour}>Single Journey</Button>

How to retrieve the first word of the output of a command in bash?

echo "word1 word2 word3" | { read first rest ; echo $first ; }

This has the advantage that is not using external commands and leaves the $1, $2, etc. variables intact.

Is having an 'OR' in an INNER JOIN condition a bad idea?

I use following code for get different result from condition That worked for me.


Select A.column, B.column
FROM TABLE1 A
INNER JOIN
TABLE2 B
ON A.Id = (case when (your condition) then b.Id else (something) END)

How to style the UL list to a single line

in bootstrap use .list-inline css class

<ul class="list-inline">
    <li>Coffee</li>
    <li>Tea</li>
    <li>Milk</li>
</ul>

Ref: https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_txt_list-inline&stacked=h

Inserting the iframe into react component

You can use property dangerouslySetInnerHTML, like this

_x000D_
_x000D_
const Component = React.createClass({_x000D_
  iframe: function () {_x000D_
    return {_x000D_
      __html: this.props.iframe_x000D_
    }_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <div dangerouslySetInnerHTML={ this.iframe() } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

also, you can copy all attributes from the string(based on the question, you get iframe as a string from a server) which contains <iframe> tag and pass it to new <iframe> tag, like that

_x000D_
_x000D_
/**_x000D_
 * getAttrs_x000D_
 * returns all attributes from TAG string_x000D_
 * @return Object_x000D_
 */_x000D_
const getAttrs = (iframeTag) => {_x000D_
  var doc = document.createElement('div');_x000D_
  doc.innerHTML = iframeTag;_x000D_
_x000D_
  const iframe = doc.getElementsByTagName('iframe')[0];_x000D_
  return [].slice_x000D_
    .call(iframe.attributes)_x000D_
    .reduce((attrs, element) => {_x000D_
      attrs[element.name] = element.value;_x000D_
      return attrs;_x000D_
    }, {});_x000D_
}_x000D_
_x000D_
const Component = React.createClass({_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <iframe {...getAttrs(this.props.iframe) } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"><div>
_x000D_
_x000D_
_x000D_

react-router - pass props to handler component

I have answered this already here.

Here are few ways you can pass props to a route component.

With the react-router v5, we can create routes by wrapping with a component, so that we can easily pass props to the desired component like this.

<Route path="/">
    <Home name="Sai" />
</Route>

Similarly, you can use the children prop in v5.

<Route path="/" children={ <Home name="Sai" />} />

If you are using react-router v4, you can pass it using the render prop.

<Route path="/" render={() => <Home name="Sai" />} />

(originally posted at https://reactgo.com/react-router-pass-props/)

Auto-refreshing div with jQuery - setTimeout or another method?

function update() {
  $("#notice_div").html('Loading..'); 
  $.ajax({
    type: 'GET',
    url: 'jbede.php',
    timeout: 2000,
    success: function(data) {
      $("#some_div").html(data);
      $("#notice_div").html(''); 
      window.setTimeout(update, 10000);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      $("#notice_div").html('Timeout contacting server..');
      window.setTimeout(update, 60000);
    }
});
}
$(document).ready(function() {
    update();
});

This is Better Code

mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)

Please check the following file

%SystemRoot%\system32\drivers\etc\host

The line which bind the host name with ip is probably missing a line which bind them togather

127.0.0.1  localhost

If the given line is missing. Add the line in the file


Could you also check your MySQL database's user table and tell us the host column value for the user which you are using. You should have user privilege for both the host "127.0.0.1" and "localhost" and use % as it is a wild char for generic host name.

Git - What is the difference between push.default "matching" and "simple"

git push can push all branches or a single one dependent on this configuration:

Push all branches

git config --global push.default matching

It will push all the branches to the remote branch and would merge them. If you don't want to push all branches, you can push the current branch if you fully specify its name, but this is much is not different from default.

Push only the current branch if its named upstream is identical

git config --global push.default simple

So, it's better, in my opinion, to use this option and push your code branch by branch. It's better to push branches manually and individually.

Unit testing with Spring Security

I would take a look at Spring's abstract test classes and mock objects which are talked about here. They provide a powerful way of auto-wiring your Spring managed objects making unit and integration testing easier.

How to refresh a Page using react-route Link

I ended up keeping Link and adding the reload to the Link's onClick event with a timeout like this:

function refreshPage() {
    setTimeout(()=>{
        window.location.reload(false);
    }, 500);
    console.log('page to reload')
}

<Link to={{pathname:"/"}} onClick={refreshPage}>Home</Link>

without the timeout, the refresh function would run first

Android Studio doesn't recognize my device

Try swapping the USB port the cable is plugged into.

Sounds crazy but after 20 minutes of debugging this worked for me.

Count number of vector values in range with R

Use which:

 set.seed(1)
 x <- sample(10, 50, replace = TRUE)
 length(which(x > 3 & x < 5))
 # [1]  6

See line breaks and carriage returns in editor

Just to clarify why :set list won't show CR's as ^M without e ++ff=unix and why :set list has nothing to do with ^M's.

Internally when Vim reads a file into its buffer, it replaces all line-ending characters with its own representation (let's call it $'s). To determine what characters should be removed, it firstly detects in what format line endings are stored in a file. If there are only CRLF '\r\n' or only CR '\r' or only LF '\n' line-ending characters, then the 'fileformat' is set to dos, mac and unix respectively.

When list option is set, Vim displays $ character when the line break occurred no matter what fileformat option has been detected. It uses its own internal representation of line-breaks and that's what it displays.

Now when you write buffer to the disc, Vim inserts line-ending characters according to what fileformat options has been detected, essentially converting all those internal $'s with appropriate characters. If the fileformat happened to be unix then it will simply write \n in place of its internal line-break.

The trick is to force Vim to read a dos encoded file as unix one. The net effect is that it will remove all \n's leaving \r's untouched and display them as ^M's in your buffer. Setting :set list will additionally show internal line-endings as $. After all, you see ^M$ in place of dos encoded line-breaks.

Also notice that :set list has nothing to do with showing ^M's. You can check it by yourself (make sure you have disabled list option first) by inserting single CR using CTRL-V followed by Enter in insert mode. After writing buffer to disc and opening it again you will see ^M despite list option being set to 0.

You can find more about file formats on http://vim.wikia.com/wiki/File_format or by typing:help 'fileformat' in Vim.

Remove duplicates from a list of objects based on property in Java 8

Try this code:

Collection<Employee> nonDuplicatedEmployees = employees.stream()
   .<Map<Integer, Employee>> collect(HashMap::new,(m,e)->m.put(e.getId(), e), Map::putAll)
   .values();

UL or DIV vertical scrollbar

You need to set a height on the DIV. Otherwise it will keep expanding indefinitely.

How to save a spark DataFrame as csv on disk?

Apache Spark does not support native CSV output on disk.

You have four available solutions though:

  1. You can convert your Dataframe into an RDD :

    def convertToReadableString(r : Row) = ???
    df.rdd.map{ convertToReadableString }.saveAsTextFile(filepath)
    

    This will create a folder filepath. Under the file path, you'll find partitions files (e.g part-000*)

    What I usually do if I want to append all the partitions into a big CSV is

    cat filePath/part* > mycsvfile.csv
    

    Some will use coalesce(1,false) to create one partition from the RDD. It's usually a bad practice, since it may overwhelm the driver by pulling all the data you are collecting to it.

    Note that df.rdd will return an RDD[Row].

  2. With Spark <2, you can use databricks spark-csv library:

    • Spark 1.4+:

      df.write.format("com.databricks.spark.csv").save(filepath)
      
    • Spark 1.3:

      df.save(filepath,"com.databricks.spark.csv")
      
  3. With Spark 2.x the spark-csv package is not needed as it's included in Spark.

    df.write.format("csv").save(filepath)
    
  4. You can convert to local Pandas data frame and use to_csv method (PySpark only).

Note: Solutions 1, 2 and 3 will result in CSV format files (part-*) generated by the underlying Hadoop API that Spark calls when you invoke save. You will have one part- file per partition.

Laravel Eloquent Join vs Inner Join?

I'm sure there are other ways to accomplish this, but one solution would be to use join through the Query Builder.

If you have tables set up something like this:

users
    id
    ...

friends
    id
    user_id
    friend_id
    ...

votes, comments and status_updates (3 tables)
    id
    user_id
    ....

In your User model:

class User extends Eloquent {
    public function friends()
    {
        return $this->hasMany('Friend');
    }
}

In your Friend model:

class Friend extends Eloquent {
    public function user()
    {
        return $this->belongsTo('User');
    }
}

Then, to gather all the votes for the friends of the user with the id of 1, you could run this query:

$user = User::find(1);
$friends_votes = $user->friends()
    ->with('user') // bring along details of the friend
    ->join('votes', 'votes.user_id', '=', 'friends.friend_id')
    ->get(['votes.*']); // exclude extra details from friends table

Run the same join for the comments and status_updates tables. If you would like votes, comments, and status_updates to be in one chronological list, you can merge the resulting three collections into one and then sort the merged collection.


Edit

To get votes, comments, and status updates in one query, you could build up each query and then union the results. Unfortunately, this doesn't seem to work if we use the Eloquent hasMany relationship (see comments for this question for a discussion of that problem) so we have to modify to queries to use where instead:

$friends_votes = 
    DB::table('friends')->where('friends.user_id','1')
    ->join('votes', 'votes.user_id', '=', 'friends.friend_id');

$friends_comments = 
    DB::table('friends')->where('friends.user_id','1')
    ->join('comments', 'comments.user_id', '=', 'friends.friend_id');

$friends_status_updates = 
    DB::table('status_updates')->where('status_updates.user_id','1')
    ->join('friends', 'status_updates.user_id', '=', 'friends.friend_id');

$friends_events = 
    $friends_votes
    ->union($friends_comments)
    ->union($friends_status_updates)
    ->get();

At this point, though, our query is getting a bit hairy, so a polymorphic relationship with and an extra table (like DefiniteIntegral suggests below) might be a better idea.

Pair/tuple data type in Go

You can do this. It looks more wordy than a tuple, but it's a big improvement because you get type checking.

Edit: Replaced snippet with complete working example, following Nick's suggestion. Playground link: http://play.golang.org/p/RNx_otTFpk

package main

import "fmt"

func main() {
    queue := make(chan struct {string; int})
    go sendPair(queue)
    pair := <-queue
    fmt.Println(pair.string, pair.int)
}

func sendPair(queue chan struct {string; int}) {
    queue <- struct {string; int}{"http:...", 3}
}

Anonymous structs and fields are fine for quick and dirty solutions like this. For all but the simplest cases though, you'd do better to define a named struct just like you did.

Object of class stdClass could not be converted to string

What I was looking for is a way to fetch the data

so I used this $data = $this->db->get('table_name')->result_array();

and then fetched my data just as you operate on array objects.

$data[0]['field_name']

No need to worry about type casting or anything just straight to the point.

So it worked for me.

DOS: find a string, if found then run another script

As the answer is marked correct then it's a Windows Dos prompt script and this will work too:

find "string" status.txt >nul && call "my batch file.bat"

Creating a REST API using PHP

Trying to write a REST API from scratch is not a simple task. There are many issues to factor and you will need to write a lot of code to process requests and data coming from the caller, authentication, retrieval of data and sending back responses.

Your best bet is to use a framework that already has this functionality ready and tested for you.

Some suggestions are:

Phalcon - REST API building - Easy to use all in one framework with huge performance

Apigility - A one size fits all API handling framework by Zend Technologies

Laravel API Building Tutorial

and many more. Simple searches on Bitbucket/Github will give you a lot of resources to start with.

Change div height on button click

You have to set height as a string value when you use pixels.

document.getElementById('chartdiv').style.height = "200px"

Also try adding a DOCTYPE to your HTML for Internet Explorer.

<!DOCTYPE html>
<html> ...

Getting "conflicting types for function" in C, why?

You didn't declare it before you used it.

You need something like

char *do_something(char *, const char *);

before the printf.

Example:

#include <stdio.h>
char *do_something(char *, const char *);
char dest[5];
char src[5] = "test";
int main ()
{
printf("String: %s\n", do_something(dest, src));
 return 0;
}

char *do_something(char *dest, const char *src)
{
return dest;
}

Alternatively, you can put the whole do_something function before the printf.

Why not use tables for layout in HTML?

Also, don't forget, tables don't quite render well on mobile browsers. Sure, the iPhone has a kick-ass browser but everyone doesn't have an iPhone. Table rendering can be peanuts for modern browsers, but it's a bunch of watermelons for mobile browsers.

I have personally found that many people use too many <div> tags, but in moderation, it can be extremely clean and easy to read. You mention that folks have a harder time reading CSS than tables; in terms of 'code' that maybe true; but in terms of reading content (view > source) it is a heck of a lot easier to understand the structure with stylesheets than with tables.

How do I tokenize a string in C++?

you can take advantage of boost::make_find_iterator. Something similar to this:

template<typename CH>
inline vector< basic_string<CH> > tokenize(
    const basic_string<CH> &Input,
    const basic_string<CH> &Delimiter,
    bool remove_empty_token
    ) {

    typedef typename basic_string<CH>::const_iterator string_iterator_t;
    typedef boost::find_iterator< string_iterator_t > string_find_iterator_t;

    vector< basic_string<CH> > Result;
    string_iterator_t it = Input.begin();
    string_iterator_t it_end = Input.end();
    for(string_find_iterator_t i = boost::make_find_iterator(Input, boost::first_finder(Delimiter, boost::is_equal()));
        i != string_find_iterator_t();
        ++i) {
        if(remove_empty_token){
            if(it != i->begin())
                Result.push_back(basic_string<CH>(it,i->begin()));
        }
        else
            Result.push_back(basic_string<CH>(it,i->begin()));
        it = i->end();
    }
    if(it != it_end)
        Result.push_back(basic_string<CH>(it,it_end));

    return Result;
}

Cursor adapter and sqlite example

CursorAdapter Example with Sqlite

...
DatabaseHelper helper = new DatabaseHelper(this);
aListView = (ListView) findViewById(R.id.aListView);
Cursor c = helper.getAllContacts();
CustomAdapter adapter = new CustomAdapter(this, c);
aListView.setAdapter(adapter);
...

class CustomAdapter extends CursorAdapter {
    // CursorAdapter will handle all the moveToFirst(), getCount() logic for you :)

    public CustomAdapter(Context context, Cursor c) {
        super(context, c);
    }

    public void bindView(View view, Context context, Cursor cursor) {
        String id = cursor.getString(0);
        String name = cursor.getString(1);
        // Get all the values
        // Use it however you need to
        TextView textView = (TextView) view;
        textView.setText(name);
    }

    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        // Inflate your view here.
        TextView view = new TextView(context);
        return view;
    }
}

private final class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "db_name";
    private static final int DATABASE_VERSION = 1;
    private static final String CREATE_TABLE_TIMELINE = "CREATE TABLE IF NOT EXISTS table_name (_id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar);";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_TIMELINE);
        db.execSQL("INSERT INTO ddd (name) VALUES ('One')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Two')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Three')");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public Cursor getAllContacts() {
        String selectQuery = "SELECT  * FROM table_name;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        return cursor;
    }
}

Appending values to dictionary in Python

how do i append a number into the drug_dictionary?

Do you wish to add "a number" or a set of values?

I use dictionaries to build associative arrays and lookup tables quite a bit.

Since python is so good at handling strings, I often use a string and add the values into a dict as a comma separated string

drug_dictionary = {} 

drug_dictionary={'MORPHINE':'',
         'OXYCODONE':'',
         'OXYMORPHONE':'',
         'METHADONE':'',
         'BUPRENORPHINE':'',
         'HYDROMORPHONE':'',
         'CODEINE':'',
         'HYDROCODONE':''}


drug_to_update = 'MORPHINE'

try: 
   oldvalue = drug_dictionary[drug_to_update] 
except: 
   oldvalue = ''

# to increment a value

   try: 
      newval = int(oldval) 
      newval += 1
   except: 
      newval = 1 


   drug_dictionary[drug_to_update] = "%s" % newval

# to append a value  

   try: 
      newval = int(oldval) 
      newval += 1
   except: 
      newval = 1 


   drug_dictionary[drug_to_update] = "%s,%s" % (oldval,newval) 

The Append method allows for storing a list of values but leaves you will a trailing comma

which you can remove with

drug_dictionary[drug_to_update][:-1]

the result of the appending the values as a string means that you can append lists of values as you need too and

print "'%s':'%s'" % ( drug_to_update, drug_dictionary[drug_to_update]) 

can return

'MORPHINE':'10,5,7,42,12,'

how to enable sqlite3 for php?

Only use:

sudo apt-get install php5-sqlite

and later

sudo service apache2 restart

How to base64 encode image in linux bash / shell

Base 64 for html:

file="DSC_0251.JPG"
type=$(identify -format "%m" "$file" | tr '[A-Z]' '[a-z]')
echo "data:image/$type;base64,$(base64 -w 0 "$file")"

How do I clear all variables in the middle of a Python script?

In the idle IDE there is Shell/Restart Shell. Cntrl-F6 will do it.

How to read specific lines from a file (by line number)?

If you want to read specific lines, such as line starting after some threshold line then you can use the following codes, file = open("files.txt","r") lines = file.readlines() ## convert to list of lines datas = lines[11:] ## raed the specific lines

What does operator "dot" (.) mean?

The dot itself is not an operator, .^ is.

The .^ is a pointwise¹ (i.e. element-wise) power, as .* is the pointwise product.

.^ Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. The sizes of A and B must be the same or be compatible.

C.f.

¹) Hence the dot.

Extracting specific columns from a data frame

You can subset using a vector of column names. I strongly prefer this approach over those that treat column names as if they are object names (e.g. subset()), especially when programming in functions, packages, or applications.

# data for reproducible example
# (and to avoid confusion from trying to subset `stats::df`)
df <- setNames(data.frame(as.list(1:5)), LETTERS[1:5])
# subset
df[c("A","B","E")]

Note there's no comma (i.e. it's not df[,c("A","B","C")]). That's because df[,"A"] returns a vector, not a data frame. But df["A"] will always return a data frame.

str(df["A"])
## 'data.frame':    1 obs. of  1 variable:
## $ A: int 1
str(df[,"A"])  # vector
##  int 1

Thanks to David Dorchies for pointing out that df[,"A"] returns a vector instead of a data.frame, and to Antoine Fabri for suggesting a better alternative (above) to my original solution (below).

# subset (original solution--not recommended)
df[,c("A","B","E")]  # returns a data.frame
df[,"A"]             # returns a vector

Save base64 string as PDF at client side with JavaScript

you can use this function to download file from base64.

function downloadPDF(pdf) {
const linkSource = `data:application/pdf;base64,${pdf}`;
const downloadLink = document.createElement("a");
const fileName = "abc.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();}

This code will made an anchor tag with href and download file. if you want to use button then you can call click method on your button click.

i hope this will help of you thanks

How to install Intellij IDEA on Ubuntu?

Since Ubuntu 18.04 installing Intellij IDEA is easy! You just need to search "IDEA" in Software Center. Also you're able to choose a branch to install (I use EAP). enter image description here

For earlier versions:

According to this (snap) and this (umake) articles the most comfortable ways are:

  • to use snap-packages (since versions IDEA 2017.3 & Ubuntu 14.04):

    1. install snapd system. Since Ubuntu 16.04 you already have it.

    2. install IDEA snap-package or even EAP build

  • to use ubuntu-make (for Ubuntu versions earlier than 16.04 use apt-get command instead apt):

    1. Add PPA ubuntu-desktop/ubuntu-make (if you install ubuntu-make from standard repo you'll see only a few IDE's):

      $ sudo add-apt-repository ppa:ubuntu-desktop/ubuntu-make
      
    2. Install ubuntu-make:

      $ sudo apt update
      $ sudo apt install ubuntu-make
      
    3. install preffered ide (IDEA, for this question):

      $ umake ide idea
      

      or even ultimate version if you need:

      $ umake ide idea-ultimate
      
    4. I upgrade Intellij IDEA via reinstalling it:

      $ umake -r ide idea-ultimate

      $ umake ide idea-ultimate
      

Return values from the row above to the current row

Easier way for me is to switch to R1C1 notation and just use R[-1]C1 and switch back when done.

The import org.junit cannot be resolved

If you are using eclipse and working on a maven project, then also the above steps work.

Right-click on your root folder.

Properties -> Java Build Path -> Libraries -> Add Library -> JUnit -> Junit 3/4

Step By Step Instructions here

Add/delete row from a table

jQuery has a nice function for removing elements from the DOM.

The closest() function is cool because it will "get the first element that matches the selector by testing the element itself and traversing up through its ancestors."

$(this).closest("tr").remove();

Each delete button could run that very succinct code with a function call.

CSS Change List Item Background Color with Class

The ul.nav li is more restrictive and so takes precedence, try this:

ul.nav li.selected {  
  background-color:red; 
}

Standard Android Button with a different color

values\styles.xml

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

<style name="RedAccentButton" parent="ThemeOverlay.AppCompat.Light">
    <item name="colorAccent">#ff0000</item>
</style>

then:

<Button
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="text" />

<Button
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:enabled="false"
    android:text="text" />

<Button
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="text"
    android:theme="@style/RedAccentButton" />

<Button
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:enabled="false"
    android:text="text"
    android:theme="@style/RedAccentButton" />

result

Extracting extension from filename in Python

worth adding a lower in there so you don't find yourself wondering why the JPG's aren't showing up in your list.

os.path.splitext(filename)[1][1:].strip().lower()

"rm -rf" equivalent for Windows?

rmdir /S /Q %DIRNAME%

How to automate browsing using python?

Selenium2 includes webdriver, which has python bindings and allows one to use the headless htmlUnit driver, or switch to firefox or chrome for graphical debugging.

Inversion of Control vs Dependency Injection

In short, IoC is a much broader term that includes, but is not limited to, DI

The term Inversion of Control (IoC) originally meant any sort of programming style where an overall framework or run-time controlled the program flow

Before DI had a name, people started to refer to frameworks that manage Dependencies as Inversion of Control Containers, and soon, the meaning of IoC gradually drifted towards that particular meaning: Inversion of Control over Dependencies.

Inversion of Control (IoC) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source (for example, an xml configuration file).

Dependency Injection (DI) means that this is done without the object intervention, usually by a framework component that passes constructor parameters and set properties.

Export data from Chrome developer tool

I came across the same problem, and found that easier way is to undock the developer tool's video to a separate window! (Using the right hand top corner toolbar button of developer tools window) and in the new window , simply say select all and copy and paste to excel!!