Programs & Examples On #Fivestar

How to fix height of TR?

Tables are iffy (at least, in IE) when it comes to fixing heights and not wrapping text. I think you'll find that the only solution is to put the text inside a div element, like so:

_x000D_
_x000D_
td.container > div {_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    overflow:hidden;_x000D_
}_x000D_
td.container {_x000D_
    height: 20px;_x000D_
}
_x000D_
<table>_x000D_
    <tr>_x000D_
        <td class="container">_x000D_
            <div>This is a long line of text designed not to wrap _x000D_
                 when the container becomes too small.</div>_x000D_
        </td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

This way, the div's height is that of the containing cell and the text cannot grow the div, keeping the cell/row the same height no matter what the window size is.

Using the HTML5 "required" attribute for a group of checkboxes?

HTML5 does not directly support requiring only one/at least one checkbox be checked in a checkbox group. Here is my solution using Javascript:

HTML

<input class='acb' type='checkbox' name='acheckbox[]' value='1' onclick='deRequire("acb")' required> One
<input class='acb' type='checkbox' name='acheckbox[]' value='2' onclick='deRequire("acb")' required> Two

JAVASCRIPT

       function deRequireCb(elClass) {
            el=document.getElementsByClassName(elClass);

            var atLeastOneChecked=false;//at least one cb is checked
            for (i=0; i<el.length; i++) {
                if (el[i].checked === true) {
                    atLeastOneChecked=true;
                }
            }

            if (atLeastOneChecked === true) {
                for (i=0; i<el.length; i++) {
                    el[i].required = false;
                }
            } else {
                for (i=0; i<el.length; i++) {
                    el[i].required = true;
                }
            }
        }

The javascript will ensure at least one checkbox is checked, then de-require the entire checkbox group. If the one checkbox that is checked becomes un-checked, then it will require all checkboxes, again!

How to create threads in nodejs

There is also now https://github.com/xk/node-threads-a-gogo, though I'm not sure about project status.

Simple http post example in Objective-C?

 NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:@"name" forKey:@"email"];
[contentDictionary setValue:@"name" forKey:@"username"];
[contentDictionary setValue:@"name" forKey:@"password"];
[contentDictionary setValue:@"name" forKey:@"firstName"];
[contentDictionary setValue:@"name" forKey:@"lastName"];

NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:data
                                          encoding:NSUTF8StringEncoding];
NSLog(@"%@",jsonStr);

NSString *urlString = [NSString stringWithFormat:@"http://testgcride.com:8081/v1/users"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
   [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];


[request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"moinsam" password:@"cheese"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:<block> failure:<block>];

Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

you could try

$('*').not('#div').bind('touchmove', false);

add this if necessary

$('#div').bind('touchmove');

note that everything is fixed except #div

Change location of log4j.properties

Refer to this example taken from - http://www.dzone.com/tutorials/java/log4j/sample-log4j-properties-file-configuration-1.html

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class HelloWorld {

    static final Logger logger = Logger.getLogger(HelloWorld.class);
    static final String path = "src/resources/log4j.properties";

    public static void main(String[] args) {

        PropertyConfigurator.configure(path);
        logger.debug("Sample debug message");
        logger.info("Sample info message");
        logger.warn("Sample warn message");
        logger.error("Sample error message");
        logger.fatal("Sample fatal message");
    }
}

To change the logger levels - Logger.getRootLogger().setLevel(Level.INFO);

Get user profile picture by Id

Through the Javascript SDK (v2.12 - April, 2017) you can get the details of the picture request this way:

FB.api("/" + uid + "/picture?redirect=0", function (response) {
  console.log(response);

  // prints the following:
  //data: {
  //  height: 50
  //  is_silhouette: false
  //  url: "https://lookaside.facebook.com/platform/profilepic/?asid=…&height=50&width=50&ext=…&hash…"
  //  width: 50
  //}

  if (response && !response.error) {
    // change the src attribute of img elements
    [...document.getElementsByClassName('fb-user-img')].forEach(
      i => i.src = response.data.url
    );

    // OR redirect to the URL above
    location.assign(response.data.url);
  }
});

For getting the JSON response the parameter redirect with 0 (zero) as value is important since the request redirects to the image by default. You may still add other parameters in the same URL. Examples:

  • "/" + uid + "/picture?redirect=0&width=100&height=100": a 100x100 image will be returned;
  • "/" + uid + "/picture?redirect=0&type=large": a 200x200 image is returned. Other possible type values include: small, normal, album, and square.

Set Encoding of File to UTF8 With BOM in Sublime Text 3

Into the Preferences > Setting - Default

You will have the next by default:

// Display file encoding in the status bar
    "show_encoding": false

You could change it or like cdesmetz said set your user settings.

Retrieving an element from array list in Android?

I have a list of positions of array to retrieve ,This worked for me.

  public void create_list_to_add_group(ArrayList<Integer> arrayList_loc) {
     //In my case arraylist_loc is the list of positions to retrive from 
    // contact_names 
    //arraylist and phone_number arraylist

    ArrayList<String> group_members_list = new ArrayList<>();
    ArrayList<String> group_members_phone_list = new ArrayList<>();

    int size = arrayList_loc.size();

    for (int i = 0; i < size; i++) {

        try {

            int loc = arrayList_loc.get(i);
            group_members_list.add(contact_names_list.get(loc));
            group_members_phone_list.add(phone_num_list.get(loc));


        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    Log.e("Group memnbers list", " " + group_members_list);
    Log.e("Group memnbers num list", " " + group_members_phone_list);

}

Delete all the queues from RabbitMQ?

Okay, important qualifier for this answer: The question does ask to use either rabbitmqctl OR rabbitmqadmin to solve this, my answer needed to use both. Also, note that this was tested on MacOS 10.12.6 and the versions of the rabbitmqctl and rabbitmqadmin that are installed when installing rabbitmq with Homebrew and which is identified with brew list --versions as rabbitmq 3.7.0

rabbitmqctl list_queues -p <VIRTUAL_HOSTNAME> name | sed 1,2d | xargs -I qname rabbitmqadmin --vhost <VIRTUAL_HOSTNAME> delete queue name=qname

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

Inside ContentPlaceholder, put the placeholder control.For Example like this,

<asp:Content ID="header" ContentPlaceHolderID="head" runat="server">
       <asp:PlaceHolder ID="metatags" runat="server">
        </asp:PlaceHolder>
</asp:Content>

Code Behind:

HtmlMeta hm1 = new HtmlMeta();
hm1.Name = "Description";
hm1.Content = "Content here";
metatags.Controls.Add(hm1);

How to fix "The ConnectionString property has not been initialized"

I found that when I create Sqlconnection = new SqlConnection(), I forgot to pass my connectionString variable. So that is why I changed the way I initialize my connectionString (and nothing changed).

And if you like me just don't forget to pass your string connection into SqlConnection parameters.

Sqlconnection = new SqlConnection("ConnString")

How to make script execution wait until jquery is loaded

Check this:

https://jsfiddle.net/neohunter/ey2pqt5z/

It will create a fake jQuery object, that allows you to use the onload methods of jquery, and they will be executed as soon as jquery is loaded.

It's not perfect.

_x000D_
_x000D_
// This have to be on <HEAD> preferibly inline_x000D_
var delayed_jquery = [];_x000D_
jQuery = function() {_x000D_
  if (typeof arguments[0] == "function") {_x000D_
    jQuery(document).ready(arguments[0]);_x000D_
  } else {_x000D_
    return {_x000D_
      ready: function(fn) {_x000D_
        console.log("registering function");_x000D_
        delayed_jquery.push(fn);_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
};_x000D_
$ = jQuery;_x000D_
var waitForLoad = function() {_x000D_
  if (typeof jQuery.fn != "undefined") {_x000D_
    console.log("jquery loaded!!!");_x000D_
    for (k in delayed_jquery) {_x000D_
      delayed_jquery[k]();_x000D_
    }_x000D_
  } else {_x000D_
    console.log("jquery not loaded..");_x000D_
    window.setTimeout(waitForLoad, 500);_x000D_
  }_x000D_
};_x000D_
window.setTimeout(waitForLoad, 500);_x000D_
// end_x000D_
_x000D_
_x000D_
_x000D_
// now lets use jQuery (the fake version)_x000D_
jQuery(document).ready(function() {_x000D_
  alert('Jquery now exists!');_x000D_
});_x000D_
_x000D_
jQuery(function() {_x000D_
  alert('Jquery now exists, this is using an alternative call');_x000D_
})_x000D_
_x000D_
// And lets load the real jquery after 3 seconds.._x000D_
window.setTimeout(function() {_x000D_
  var newscript = document.createElement('script');_x000D_
  newscript.type = 'text/javascript';_x000D_
  newscript.async = true;_x000D_
  newscript.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js';_x000D_
  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(newscript);_x000D_
}, 3000);
_x000D_
_x000D_
_x000D_

Min and max value of input in angular4 application

Most simple approach in Template driven forms for min/max validation with out using reactive forms and building any directive, would be to use pattern attribute of html. This has already been explained and answered here please look https://stackoverflow.com/a/63312336/14069524

How to convert an Array to a Set in Java

Quickly : you can do :

// Fixed-size list
List list = Arrays.asList(array);

// Growable list
list = new LinkedList(Arrays.asList(array));

// Duplicate elements are discarded
Set set = new HashSet(Arrays.asList(array));

and to reverse

// Create an array containing the elements in a list
Object[] objectArray = list.toArray();
MyClass[] array = (MyClass[])list.toArray(new MyClass[list.size()]);

// Create an array containing the elements in a set
objectArray = set.toArray();
array = (MyClass[])set.toArray(new MyClass[set.size()]);

Find max and second max salary for a employee table MySQL

Try like this

SELECT (select max(Salary) from Employee) as MAXinmum),(max(salary) FROM Employee WHERE salary NOT IN (SELECT max(salary)) FROM Employee);

(Or)

Try this, n would be the nth item you would want to return

 SELECT DISTINCT(Salary) FROM table ORDER BY Salary DESC LIMIT n,1

In your case

 SELECT DISTINCT(column_name) FROM table_name ORDER BY column_name DESC limit 2,1;

How to change the colors of a PNG image easily?

If you are going to be programming an application to do all of this, the process will be something like this:

  1. Convert image from RGB to HSV
  2. adjust H value
  3. Convert image back to RGB
  4. Save image

How to write to Console.Out during execution of an MSTest test

You better setup a single test and create a performance test from this test. This way you can monitor the progress using the default tool set.

Reset push notification settings for app

Another just for testing solution to this is by simply changing your bundle id. Just don't forget to change it back once you're done!

Paste MS Excel data to SQL Server

If the interface works the way it did last I used it, you can select the region in Excel, copy it, open SQL Server and paste the data into the table as you would with Access.

Or you could setup an ODBC link between Excel and SQL Server.

Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

I'm not quite sure what you're asking, but maybe this can help:

window.onload = function(){
    // Code. . .

}

Or:

window.onload = main;

function main(){
    // Code. . .

}

How to build a Horizontal ListView with RecyclerView?

It's for both for Horizontal and for Vertical.

RecyclerView recyclerView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_recycler);
    recyclerView = (RecyclerView)findViewById(R.id.recyclerViewId);

    RecyclAdapter adapter = new RecyclAdapter();

    //Vertical RecyclerView
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(mLayoutManager);

    //Horizontal RecyclerView
    //recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.HORIZONTAL,false));

    recyclerView.setAdapter(adapter);

}

Close a div by clicking outside

An other way which makes then your jsfiddle less buggy (needed double click on open).

This doesn't use any delegated event to body level

Set tabindex="-1" to DIV .popup ( and for style CSS outline:0 )

DEMO

$(".link").click(function(e){
    e.preventDefault();
    $(".popup").fadeIn(300,function(){$(this).focus();});
});

$('.close').click(function() {
   $(".popup").fadeOut(300);
});
$(".popup").on('blur',function(){
    $(this).fadeOut(300);
});

'True' and 'False' in Python

From 6.11. Boolean operations:

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

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

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

"Eliminate render-blocking CSS in above-the-fold content"

Few tips that may help:

  • I came across this article in CSS optimization yesterday: CSS profiling for ... optimization
    A lot of useful info on CSS and what CSS causes the most performance drains.

  • I saw the following presentation on jQueryUK on "hidden secrets" in Googe Chrome (Canary) Dev Tools: DevTools Can do that. Check out the sections on Time to First Paint, repaints and costly CSS.

  • Also, if you are using a loader like requireJS you could have a look at one of the CSS loader plugins, called require-CSS, which uses CSSO - a optimzer that also does structural optimization, eg. merging blocks with identical properties. I used it a few times and it can save quite a lot of CSS from case to case.

Off the question: I second @Enzino in creating a sprite for all the small icons you are loading. The file sizes are so small it does not really warrant a server roundtrip for each icon. Also keep in mind the total number of concurrent http requests are browser can do. So requests for a larger number of small icons are "render-blocking" as well. Although an empty page compare to yours, I like how duckduckgo loads for example.

How to generate serial version UID in Intellij

Without any plugins:

You just need to enable highlight: (Idea v.2016, 2017 and 2018, previous versions may have same or similar settings)

File -> Settings -> Editor -> Inspections -> Java -> Serialization issues -> Serializable class without 'serialVersionUID' - set flag and click 'OK'. (For Macs, Settings is under IntelliJ IDEA -> Preferences...)

Now, if your class implements Serializable, you will see highlight and alt+Enter on class name will ask you to generate private static final long serialVersionUID.

UPD: a faster way to find this setting - you might use hotkey Ctrl+Shift+A (find action), type Serializable class without 'serialVersionUID' - the first is the one.

How to allow only integers in a textbox?

Try this:

Note:This is using Ajax Toolkit

First add Ajax Script Manager and use the below Code

<asp:FilteredTextBoxExtender ID="TextBox1_FilteredTextBoxExtender" runat="server"
Enabled="True" TargetControlID="TextBox1" FilterType="Numbers">
</asp:FilteredTextBoxExtender>

How to remove indentation from an unordered list item?

Live demo: https://jsfiddle.net/h8uxmoj4/

ol, ul {
  padding-left: 0;
}

li {
  list-style: none;
  padding-left: 1.25rem;
  position: relative;
}

li::before {
  left: 0;
  position: absolute;
}

ol {
  counter-reset: counter;
}

ol li::before {
  content: counter(counter) ".";
  counter-increment: counter;
}

ul li::before {
  content: "?";
}

Since the original question is unclear about its requirements, I attempted to solve this problem within the guidelines set by other answers. In particular:

  • Align list bullets with outside paragraph text
  • Align multiple lines within the same list item

I also wanted a solution that didn't rely on browsers agreeing on how much padding to use. I've added an ordered list for completeness.

Convert output of MySQL query to utf8

Addition:

When using the MySQL client library, then you should prevent a conversion back to your connection's default charset. (see mysql_set_character_set()[1])

In this case, use an additional cast to binary:

SELECT column1, CAST(CONVERT(column2 USING utf8) AS binary)
FROM my_table
WHERE my_condition;

Otherwise, the SELECT statement converts to utf-8, but your client library converts it back to a (potentially different) default connection charset.

Setting new value for an attribute using jQuery

Works fine for me

See example here. http://jsfiddle.net/blowsie/c6VAy/

Make sure your jquery is inside $(document).ready function or similar.

Also you can improve your code by using jquery data

$('#amount').data('min','1000');

<div id="amount" data-min=""></div>

Update,

A working example of your full code (pretty much) here. http://jsfiddle.net/blowsie/c6VAy/3/

How to pass ArrayList<CustomeObject> from one activity to another?

In First activity:

ArrayList<ContactBean> fileList = new ArrayList<ContactBean>();
Intent intent = new Intent(MainActivity.this, secondActivity.class);
intent.putExtra("FILES_TO_SEND", fileList);
startActivity(intent);

In receiver activity:

ArrayList<ContactBean> filelist =  (ArrayList<ContactBean>)getIntent().getSerializableExtra("FILES_TO_SEND");`

How to copy files across computers using SSH and MAC OS X Terminal

First zip or gzip the folders:
Use the following command:

zip -r NameYouWantForZipFile.zip foldertozip/

or

tar -pvczf BackUpDirectory.tar.gz /path/to/directory

for gzip compression use SCP:

scp [email protected]:~/serverpath/public_html ~/Desktop

Test if a vector contains a given element

Also to find the position of the element "which" can be used as

pop <- c(3,4,5,7,13)

which(pop==13)

and to find the elements which are not contained in the target vector, one may do this:

pop <- c(1,2,4,6,10)

Tset <- c(2,10,7)   # Target set

pop[which(!(pop%in%Tset))]

Get the _id of inserted document in Mongo database in NodeJS

Now you can use insertOne method and in promise's result.insertedId

How line ending conversions work with git core.autocrlf between different operating systems

The issue of EOLs in mixed-platform projects has been making my life miserable for a long time. The problems usually arise when there are already files with different and mixed EOLs already in the repo. This means that:

  1. The repo may have different files with different EOLs
  2. Some files in the repo may have mixed EOL, e.g. a combination of CRLF and LF in the same file.

How this happens is not the issue here, but it does happen.

I ran some conversion tests on Windows for the various modes and their combinations.
Here is what I got, in a slightly modified table:

                 | Resulting conversion when       | Resulting conversion when 
                 | committing files with various   | checking out FROM repo - 
                 | EOLs INTO repo and              | with mixed files in it and
                 |  core.autocrlf value:           | core.autocrlf value:           
--------------------------------------------------------------------------------
File             | true       | input      | false | true       | input | false
--------------------------------------------------------------------------------
Windows-CRLF     | CRLF -> LF | CRLF -> LF | as-is | as-is      | as-is | as-is
Unix -LF         | as-is      | as-is      | as-is | LF -> CRLF | as-is | as-is
Mac  -CR         | as-is      | as-is      | as-is | as-is      | as-is | as-is
Mixed-CRLF+LF    | as-is      | as-is      | as-is | as-is      | as-is | as-is
Mixed-CRLF+LF+CR | as-is      | as-is      | as-is | as-is      | as-is | as-is

As you can see, there are 2 cases when conversion happens on commit (3 left columns). In the rest of the cases the files are committed as-is.

Upon checkout (3 right columns), there is only 1 case where conversion happens when:

  1. core.autocrlf is true and
  2. the file in the repo has the LF EOL.

Most surprising for me, and I suspect, the cause of many EOL problems is that there is no configuration in which mixed EOL like CRLF+LF get normalized.

Note also that "old" Mac EOLs of CR only also never get converted.
This means that if a badly written EOL conversion script tries to convert a mixed ending file with CRLFs+LFs, by just converting LFs to CRLFs, then it will leave the file in a mixed mode with "lonely" CRs wherever a CRLF was converted to CRCRLF.
Git will then not convert anything, even in true mode, and EOL havoc continues. This actually happened to me and messed up my files really badly, since some editors and compilers (e.g. VS2010) don't like Mac EOLs.

I guess the only way to really handle these problems is to occasionally normalize the whole repo by checking out all the files in input or false mode, running a proper normalization and re-committing the changed files (if any). On Windows, presumably resume working with core.autocrlf true.

regular expression for finding 'href' value of a <a> link

Try this :

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var res = Find(html);
        }

        public static List<LinkItem> Find(string file)
        {
            List<LinkItem> list = new List<LinkItem>();

            // 1.
            // Find all matches in file.
            MatchCollection m1 = Regex.Matches(file, @"(<a.*?>.*?</a>)",
                RegexOptions.Singleline);

            // 2.
            // Loop over each match.
            foreach (Match m in m1)
            {
                string value = m.Groups[1].Value;
                LinkItem i = new LinkItem();

                // 3.
                // Get href attribute.
                Match m2 = Regex.Match(value, @"href=\""(.*?)\""",
                RegexOptions.Singleline);
                if (m2.Success)
                {
                    i.Href = m2.Groups[1].Value;
                }

                // 4.
                // Remove inner tags from text.
                string t = Regex.Replace(value, @"\s*<.*?>\s*", "",
                RegexOptions.Singleline);
                i.Text = t;

                list.Add(i);
            }
            return list;
        }

        public struct LinkItem
        {
            public string Href;
            public string Text;

            public override string ToString()
            {
                return Href + "\n\t" + Text;
            }
        }

    }  

Input:

  string html = "<a href=\"www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a> 2.<a href=\"http://www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a> "; 

Result:

[0] = {www.aaa.xx/xx.zz?id=xxxx&name=xxxx}
[1] = {http://www.aaa.xx/xx.zz?id=xxxx&name=xxxx}

C# Scraping HTML Links

Scraping HTML extracts important page elements. It has many legal uses for webmasters and ASP.NET developers. With the Regex type and WebClient, we implement screen scraping for HTML.

Edited

Another easy way:you can use a web browser control for getting href from tag a,like this:(see my example)

 public Form1()
        {
            InitializeComponent();
            webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            webBrowser1.DocumentText = "<a href=\"www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a><a href=\"http://www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a><a href=\"https://www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a><a href=\"www.aaa.xx/xx.zz/xxx\" ....></a>";
        }

        void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            List<string> href = new List<string>();
            foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("a"))
            {
                href.Add(el.GetAttribute("href"));
            }
        }

Concatenating null strings in Java

The second line is transformed to the following code:

s = (new StringBuilder()).append((String)null).append("hello").toString();

The append methods can handle null arguments.

What is the correct "-moz-appearance" value to hide dropdown arrow of a <select> element

This is it guys! FIXED!


Wait and see: https://bugzilla.mozilla.org/show_bug.cgi?id=649849

or workaround


For those wondering:

https://bugzilla.mozilla.org/show_bug.cgi?id=649849#c59

First, because the bug has a lot of hostile spam in it, it creates a hostile workplace for anyone who gets assigned to this.

Secondly, the person who has the ability to do this (which includes rewriting ) has been allocated to another project (b2g) for the time being and wont have time until that project get nearer to completion.

Third, even when that person has the time again, there is no guarantee that this will be a priority because, despite webkit having this, it breaks the spec for how is supposed to work (This is what I was told, I do not personally know the spec)

Now see https://wiki.mozilla.org/B2G/Schedule_Roadmap ;)


The page no longer exists and the bug hasn't be fixed but an acceptable workaround came from João Cunha, you guys can thank him for now!

Go build: "Cannot find package" (even though GOPATH is set)

Edit: since you meant GOPATH, see fasmat's answer (upvoted)

As mentioned in "How do I make go find my package?", you need to put a package xxx in a directory xxx.

See the Go language spec:

package math

A set of files sharing the same PackageName form the implementation of a package.
An implementation may require that all source files for a package inhabit the same directory.

The Code organization mentions:

When building a program that imports the package "widget" the go command looks for src/pkg/widget inside the Go root, and then—if the package source isn't found there—it searches for src/widget inside each workspace in order.

(a "workspace" is a path entry in your GOPATH: that variable can reference multiple paths for your 'src, bin, pkg' to be)


(Original answer)

You also should set GOPATH to ~/go, not GOROOT, as illustrated in "How to Write Go Code".

The Go path is used to resolve import statements. It is implemented by and documented in the go/build package.

The GOPATH environment variable lists places to look for Go code.
On Unix, the value is a colon-separated string.
On Windows, the value is a semicolon-separated string.
On Plan 9, the value is a list.

That is different from GOROOT:

The Go binary distributions assume they will be installed in /usr/local/go (or c:\Go under Windows), but it is possible to install them in a different location.
If you do this, you will need to set the GOROOT environment variable to that directory when using the Go tools.

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

This is happening because this is a dynamic component and you didn't add it to entryComponents under @NgModule.

Simply add it there:

@NgModule({
  /* ----------------- */
  entryComponents: [ DialogResultExampleDialog ] // <---- Add it here

Look at how the Angular team talks about entryComponents:

entryComponents?: Array<Type<any>|any[]>

Specifies a list of components that should be compiled when this module is defined. For each component listed here, Angular will create a ComponentFactory and store it in the ComponentFactoryResolver.

Also, this is the list of the methods on @NgModule including entryComponents...

As you can see, all of them are optional (look at the question marks), including entryComponents which accept an array of components:

@NgModule({ 
  providers?: Provider[]
  declarations?: Array<Type<any>|any[]>
  imports?: Array<Type<any>|ModuleWithProviders|any[]>
  exports?: Array<Type<any>|any[]>
  entryComponents?: Array<Type<any>|any[]>
  bootstrap?: Array<Type<any>|any[]>
  schemas?: Array<SchemaMetadata|any[]>
  id?: string
})

How do I fire an event when a iframe has finished loading in jQuery?

I'm pretty certain that it cannot be done.

Pretty much anything else than PDF works, even Flash. (Tested on Safari, Firefox 3, IE 7)

Too bad.

Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed

In my case. I installed the release-version app. And after uninstall the app from my device. Thing works fine.

An efficient compression algorithm for short text strings

Any algorithm/library that supports a preset dictionary, e.g. zlib.

This way you can prime the compressor with the same kind of text that is likely to appear in the input. If the files are similar in some way (e.g. all URLs, all C programs, all StackOverflow posts, all ASCII-art drawings) then certain substrings will appear in most or all of the input files.

Every compression algorithm will save space if the same substring is repeated multiple times in one input file (e.g. "the" in English text or "int" in C code.)

But in the case of URLs certain strings (e.g. "http://www.", ".com", ".html", ".aspx" will typically appear once in each input file. So you need to share them between files somehow rather than having one compressed occurrence per file. Placing them in a preset dictionary will achieve this.

Elastic Search: how to see the indexed data

Probably the easiest way to explore your ElasticSearch cluster is to use elasticsearch-head.

You can install it by doing:

cd elasticsearch/
./bin/plugin -install mobz/elasticsearch-head

Then (assuming ElasticSearch is already running on your local machine), open a browser window to:

http://localhost:9200/_plugin/head/

Alternatively, you can just use curl from the command line, eg:

Check the mapping for an index:

curl -XGET 'http://127.0.0.1:9200/my_index/_mapping?pretty=1' 

Get some sample docs:

curl -XGET 'http://127.0.0.1:9200/my_index/_search?pretty=1' 

See the actual terms stored in a particular field (ie how that field has been analyzed):

curl -XGET 'http://127.0.0.1:9200/my_index/_search?pretty=1'  -d '
 {
    "facets" : {
       "my_terms" : {
          "terms" : {
             "size" : 50,
             "field" : "foo"
          }
       }
    }
 }

More available here: http://www.elasticsearch.org/guide

UPDATE : Sense plugin in Marvel

By far the easiest way of writing curl-style commands for Elasticsearch is the Sense plugin in Marvel.

It comes with source highlighting, pretty indenting and autocomplete.

Note: Sense was originally a standalone chrome plugin but is now part of the Marvel project.

npm install error - MSB3428: Could not load the Visual C++ component "VCBuild.exe"

It's mentioned in the Documentation clearly as below: https://github.com/nodejs/node-gyp#installation

Option 1: Install all the required tools and configurations using Microsoft's windows-build-tools using npm install --global --production windows-build-tools from an elevated PowerShell or CMD.exe (run as Administrator).

npm install --global --production windows-build-tools 

Running CMD command in PowerShell

Try this:

& "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe" PCNAME

To PowerShell a string "..." is just a string and PowerShell evaluates it by echoing it to the screen. To get PowerShell to execute the command whose name is in a string, you use the call operator &.

Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

I know its too late now. However even today if you are having trouble accessing cross thread controls? This is the shortest answer till date :P

Invoke(new Action(() =>
                {
                    label1.Text = "WooHoo!!!";
                }));

This is how i access any form control from a thread.

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

I had the same as well.Making the Id (0) doing "(your Model value).setId(0)" solved my problem.

Php - testing if a radio button is selected and get the value

<?php
if (isset($_POST['submit']) and ! empty($_POST['submit'])) {
    if (isset($_POST['radio'])) {
        $radio_input = $_POST['radio'];
        echo $radio_input;
    }
} else {

}
?>
<form action="radio.php" method="post">
   <input type="radio" name="radio" value="v1"/>
   <input type="radio" name="radio" value="v2"/>
   <input type="radio" name="radio" value="v3"/>
   <input type="radio" name="radio" value="v4"/>
   <input type="radio" name="radio" value="v5"/>
   <input type= "submit" name="submit"value="submit"/>
</form>

How do I divide so I get a decimal value?

@recursive's solusion (The accepted answer) is 100% right. I am just adding a sample code for your reference.

My case is to display price with two decimal digits.This is part of back-end response: "price": 2300, "currencySymbol": "CD", ....

This is my helper class:

public class CurrencyUtils
{
    private static final String[] suffix = { "", "K", "M" };

    public static String getCompactStringForDisplay(final int amount)
    {
        int suffixIndex;
        if (amount >= 1_000_000) {
            suffixIndex = 2;
        } else if (amount >= 1_000) {
            suffixIndex = 1;
        } else {
            suffixIndex = 0;
        }

        int quotient;
        int remainder;
        if (amount >= 1_000_000) {
            quotient = amount / 1_000_000;
            remainder = amount % 1_000_000;
        } else if (amount >= 1_000) {
            quotient = amount / 1_000;
            remainder = amount % 1_000;
        } else {
            return String.valueOf(amount);
        }

        if (remainder == 0) {
            return String.valueOf(quotient) + suffix[suffixIndex];
        }

        // Keep two most significant digits
        if (remainder >= 10_000) {
            remainder /= 10_000;
        } else if (remainder >= 1_000) {
            remainder /= 1_000;
        } else if (remainder >= 100) {
            remainder /= 10;
        }

        return String.valueOf(quotient) + '.' + String.valueOf(remainder) + suffix[suffixIndex];
    }
}

This is my test class (based on Junit 4):

public class CurrencyUtilsTest {

    @Test
    public void getCompactStringForDisplay() throws Exception {
        int[] numbers = {0, 5, 999, 1_000, 5_821, 10_500, 101_800, 2_000_000, 7_800_000, 92_150_000, 123_200_000, 9_999_999};
        String[] expected = {"0", "5", "999", "1K", "5.82K", "10.50K", "101.80K", "2M", "7.80M", "92.15M", "123.20M", "9.99M"};

        for (int i = 0; i < numbers.length; i++) {
            int n = numbers[i];
            String formatted = CurrencyUtils.getCompactStringForDisplay(n);
            System.out.println(n + " => " + formatted);

            assertEquals(expected[i], formatted);
        }
    }

}

Are strongly-typed functions as parameters possible in TypeScript?

In TS we can type functions in the in the following manners:

Functions types/signatures

This is used for real implementations of functions/methods it has the following syntax:

(arg1: Arg1type, arg2: Arg2type) : ReturnType

Example:

function add(x: number, y: number): number {
    return x + y;
}

class Date {
  setTime(time: number): number {
   // ...
  }

}

Function Type Literals

Function type literals are another way to declare the type of a function. They're usually applied in the function signature of a higher-order function. A higher-order function is a function which accepts functions as parameters or which returns a function. It has the following syntax:

(arg1: Arg1type, arg2: Arg2type) => ReturnType

Example:

type FunctionType1 = (x: string, y: number) => number;

class Foo {
    save(callback: (str: string) => void) {
       // ...
    }

    doStuff(callback: FunctionType1) {
       // ...
    }

}

How can I read a whole file into a string variable

This is how I did it:

package main

import (
  "fmt"
  "os"
  "bytes"
  "log"
)

func main() {
   filerc, err := os.Open("filename")
   if err != nil{
     log.Fatal(err)
   }
   defer filerc.Close()

   buf := new(bytes.Buffer)
   buf.ReadFrom(filerc)
   contents := buf.String()

   fmt.Print(contents) 

}    

Dealing with multiple Python versions and PIP?

This is probably the completely wrong thing to do (I'm a python noob), but I just went in and edited the pip file

#!/usr/bin/env python3 <-- I changed this line.

# -*- coding: utf-8 -*-
import re
import sys

from pip._internal import main

if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
    sys.exit(main())

Can the Android layout folder contain subfolders?

I think the most elegant solution to this problem (given that subfolders are not allowed) is to prepend the file names with the name of the folder you would have placed it inside of. For example, if you have a bunch of layouts for an Activity, Fragment, or just general view called "places" then you should just prepend it with places_my_layout_name. At least this solves the problem of organizing them in a way that they are easier to find within the IDE. It's not the most awesome solution, but it's better than nothing.

Using the Jersey client to do a POST operation

Simplest:

Form form = new Form();
form.add("id", "1");    
form.add("name", "supercobra");
ClientResponse response = webResource
  .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
  .post(ClientResponse.class, form);

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

I do some quick tests and have the following findings:

1) if using SynchronousQueue:

After the threads reach the maximum size, any new work will be rejected with the exception like below.

Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@3fee733d rejected from java.util.concurrent.ThreadPoolExecutor@5acf9800[Running, pool size = 3, active threads = 3, queued tasks = 0, completed tasks = 0]

at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)

2) if using LinkedBlockingQueue:

The threads never increase from minimum size to maximum size, meaning the thread pool is fixed size as the minimum size.

laravel the requested url was not found on this server

This looks like you have to enable .htaccess by adding this to your vhost:

<Directory /var/www/html/public/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

If that doesn't work, make sure you have mod_rewrite enabled.

Don't forget to restart apache after making the changes! (service apache2 restart)

Check if AJAX response data is empty/blank/null/undefined/0

//if(data="undefined"){

This is an assignment statement, not a comparison. Also, "undefined" is a string, it's a property. Checking it is like this: if (data === undefined) (no quotes, otherwise it's a string value)

If it's not defined, you may be returning an empty string. You could try checking for a falsy value like if (!data) as well

Column count doesn't match value count at row 1

You should also look at new triggers.

MySQL doesn't show the table name in the error, so you're really left in a lurch. Here's a working example:

use test;
create table blah (id int primary key AUTO_INCREMENT, data varchar(100));
create table audit_blah (audit_id int primary key AUTO_INCREMENT, action enum('INSERT','UPDATE','DELETE'), id int, data varchar(100) null);
insert into audit_blah(action, id, data) values ('INSERT', 1, 'a');
select * from blah;
select * from audit_blah;
truncate table audit_blah;

delimiter //
/* I've commented out "id" below, so the insert fails with an ambiguous error: */
create trigger ai_blah after insert on blah for each row 
begin 
  insert into audit_blah (action, /*id,*/ data) values ('INSERT', /*NEW.id,*/ NEW.data);
end;//

/* This insert is valid, but you'll get an exception from the trigger: */
insert into blah (data) values ('data1');

Missing .map resource?

I had similar expirience like yours. I have Denwer server. When I loaded my http://new.new local site without using via script src jquery.min.js file at index.php in Chrome I got error 500 jquery.min.map in console. I resolved this problem simply - I disabled extension Wunderlist in Chrome and voila - I never see this error more. Although, No, I found this error again - when Wunderlist have been on again. So, check your extensions and try to disable all of them or some of them or one by one. Good luck!

RestSharp JSON Parameter Posting

Here is complete console working application code. Please install RestSharp package.

using RestSharp;
using System;

namespace RESTSharpClient
{
    class Program
    {
        static void Main(string[] args)
        {
        string url = "https://abc.example.com/";
        string jsonString = "{" +
                "\"auth\": {" +
                    "\"type\" : \"basic\"," +
                    "\"password\": \"@P&p@y_10364\"," +
                    "\"username\": \"prop_apiuser\"" +
                "}," +
                "\"requestId\" : 15," +
                "\"method\": {" +
                    "\"name\": \"getProperties\"," +
                    "\"params\": {" +
                        "\"showAllStatus\" : \"0\"" +
                    "}" +
                "}" +
            "}";

        IRestClient client = new RestClient(url);
        IRestRequest request = new RestRequest("api/properties", Method.POST, DataFormat.Json);
        request.AddHeader("Content-Type", "application/json; CHARSET=UTF-8");
        request.AddJsonBody(jsonString);

        var response = client.Execute(request);
        Console.WriteLine(response.Content);
        //TODO: do what you want to do with response.
    }
  }
}

How can the size of an input text box be defined in HTML?

You can set the width in pixels via inline styling:

<input type="text" name="text" style="width: 195px;">

You can also set the width with a visible character length:

<input type="text" name="text" size="35">

Disable HttpClient logging

For me, the below lines in the log4j.properties file cleaned up all the mess that came from HttpClient logging... Hurray!!! :)

log4j.logger.org.apache.http.headers=ERROR
log4j.logger.org.apache.http.wire=ERROR
log4j.logger.org.apache.http.impl.conn.PoolingHttpClientConnectionManager=ERROR
log4j.logger.org.apache.http.impl.conn.DefaultManagedHttpClientConnection=ERROR
log4j.logger.org.apache.http.conn.ssl.SSLConnectionSocketFactory=ERROR
log4j.logger.org.springframework.web.client.RestTemplate=ERROR
log4j.logger.org.apache.http.client.protocol.RequestAddCookies=ERROR
log4j.logger.org.apache.http.client.protocol.RequestAuthCache=ERROR
log4j.logger.org.apache.http.impl.execchain.MainClientExec=ERROR
log4j.logger.org.apache.http.impl.conn.DefaultHttpClientConnectionOperator=ERROR

Can I use an HTML input type "date" to collect only a year?

Add this code structure to your page code

<?php
echo '<label>Admission Year:</label><br><select name="admission_year" data-component="date">';
for($year=1900; $year<=date('Y'); $year++){
echo '<option value="'.$year.'">'.$year.'</option>';
}
?>

It works perfectly and can be reverse engineered

<?php
echo '<label>Admission Year:</label><br><select name="admission_year" data-component="date">';
for($year=date('Y'); $year>=1900; $year++){
echo '<option value="'.$year.'">'.$year.'</option>';
}
?>

With this you are good to go.

SQL Left Join first match only

After careful consideration this dillema has a few different solutions:

Aggregate Everything Use an aggregate on each column to get the biggest or smallest field value. This is what I am doing since it takes 2 partially filled out records and "merges" the data.

http://sqlfiddle.com/#!3/59cde/1

SELECT
  UPPER(IDNo) AS user_id
, MAX(FirstName) AS name_first
, MAX(LastName) AS name_last
, MAX(entry) AS row_num
FROM people P
GROUP BY 
  IDNo

Get First (or Last record)

http://sqlfiddle.com/#!3/59cde/23

-- ------------------------------------------------------
-- Notes
-- entry: Auto-Number primary key some sort of unique PK is required for this method
-- IDNo:  Should be primary key in feed, but is not, we are making an upper case version
-- This gets the first entry to get last entry, change MIN() to MAX()
-- ------------------------------------------------------

SELECT 
   PC.user_id
  ,PData.FirstName
  ,PData.LastName
  ,PData.entry
FROM (
  SELECT 
      P2.user_id
     ,MIN(P2.entry) AS rownum
  FROM (
    SELECT
        UPPER(P.IDNo) AS user_id 
      , P.entry 
    FROM people P
  ) AS P2
  GROUP BY 
    P2.user_id
) AS PC
LEFT JOIN people PData
ON PData.entry = PC.rownum
ORDER BY 
   PData.entry

In STL maps, is it better to use map::insert than []?

When you write

map[key] = value;

there's no way to tell if you replaced the value for key, or if you created a new key with value.

map::insert() will only create:

using std::cout; using std::endl;
typedef std::map<int, std::string> MyMap;
MyMap map;
// ...
std::pair<MyMap::iterator, bool> res = map.insert(MyMap::value_type(key,value));
if ( ! res.second ) {
    cout << "key " <<  key << " already exists "
         << " with value " << (res.first)->second << endl;
} else {
    cout << "created key " << key << " with value " << value << endl;
}

For most of my apps, I usually don't care if I'm creating or replacing, so I use the easier to read map[key] = value.

How to concat a string to xsl:value-of select="...?

Use:

<a href="wantedText{/*/properties/property[@name='report']/@value)}"></a>

ExpressJS - throw er Unhandled error event

In my case the issue was caused by forgetting to call next() in an expressjs `use' method call.

If the current middleware does not end the request-response cycle, it must call next() to pass control to the next middleware, otherwise the request will be left hanging.

http://expressjs.com/guide/using-middleware.html

Is it good practice to use the xor operator for boolean checks?

If the usage pattern justifies it, why not? While your team doesn't recognize the operator right away, with time they could. Humans learn new words all the time. Why not in programming?

The only caution I might state is that "^" doesn't have the short circuit semantics of your second boolean check. If you really need the short circuit semantics, then a static util method works too.

public static boolean xor(boolean a, boolean b) {
    return (a && !b) || (b && !a);
}

How can I remove the top and right axis in matplotlib?

Alternatively, this

def simpleaxis(ax):
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()

seems to achieve the same effect on an axis without losing rotated label support.

(Matplotlib 1.0.1; solution inspired by this).

How to change background color in the Notepad++ text editor?

If anyone wants to enable dark mode, you may follow the below steps

  • Open your Notepad++, and select “Settings” on the menu bar, and choose “Style configurator”.
  • Select theme “Obsidian” (you can choose other dark themes)
  • Click on Save&Colse

enter image description here

Python: Making a beep noise

The cross-platform way:

import time
import sys
for i in range(1,6):
    sys.stdout.write('\r\a{i}'.format(i=i))
    sys.stdout.flush()
    time.sleep(1)
sys.stdout.write('\n')

Mongoose.js: Find user by username LIKE value

Here my code with expressJS:

router.route('/wordslike/:word')
    .get(function(request, response) {
            var word = request.params.word;       
            Word.find({'sentence' : new RegExp(word, 'i')}, function(err, words){
               if (err) {response.send(err);}
               response.json(words);
            });
         });

Hide/Show Action Bar Option Menu Item for different fragments

This will work for sure I guess...

// Declare
Menu menu;
MenuItem menuDoneItem;

// Then in your onCreateOptionMenu() method write the following...
@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        this.menu=menu;
        inflater.inflate(R.menu.secutity, menu);
            }

// In your onOptionItemSelected() method write the following...
@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.done_item:
                this.menuDoneItem=item;
                someOperation();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

// Now Making invisible any menu item...
public void menuInvisible(){
setHasOptionsMenu(true);// Take part in populating the action bar menu
            menuDoneItem=(MenuItem)menu.findItem(R.id.done_item);
                menuRefresh.setVisible(false); // make true to make the menu item visible.
}

//Use the above method whenever you need to make your menu item visible or invisiable

You can also refer this link for more details, it is a very useful one.

How to count the number of set bits in a 32-bit integer?

if you're using C++ another option is to use template metaprogramming:

// recursive template to sum bits in an int
template <int BITS>
int countBits(int val) {
        // return the least significant bit plus the result of calling ourselves with
        // .. the shifted value
        return (val & 0x1) + countBits<BITS-1>(val >> 1);
}

// template specialisation to terminate the recursion when there's only one bit left
template<>
int countBits<1>(int val) {
        return val & 0x1;
}

usage would be:

// to count bits in a byte/char (this returns 8)
countBits<8>( 255 )

// another byte (this returns 7)
countBits<8>( 254 )

// counting bits in a word/short (this returns 1)
countBits<16>( 256 )

you could of course further expand this template to use different types (even auto-detecting bit size) but I've kept it simple for clarity.

edit: forgot to mention this is good because it should work in any C++ compiler and it basically just unrolls your loop for you if a constant value is used for the bit count (in other words, I'm pretty sure it's the fastest general method you'll find)

How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

I ran across a site a few weeks back. This is a working example of the first column locked but it is not browser compatible with Firefox. I didn't do a lot of checking around but it seems it only works in IE. There are some notes the author provided along with it that you can read.

Lock the First column: http://home.tampabay.rr.com/bmerkey/examples/locked-column-csv.html

Let me know if you need the Javascript to lock the Table headers too.

intellij idea - Error: java: invalid source release 1.9

Sometimes the problem occurs because of the incorrect version of the project bytecode.

So verify it : File -> Settings -> Build, Execution, Deployment -> Compiler -> Java Compiler -> Project bytecode version and set its value to 8

Example

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

I had this issue and tried both, but had to settle for removing crap like "pageEditState", but not removing user info lest I have to look it up again.

public static void RemoveEverythingButUserInfo()
{
    foreach (String o in HttpContext.Current.Session.Keys)
    {
        if (o != "UserInfoIDontWantToAskForAgain")
            keys.Add(o);
    }
}

Warning :-Presenting view controllers on detached view controllers is discouraged

It depends if you want to show your alert or something similar in anywhere of kind UIViewController.

You can use this code example:

UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Alert" message:@"Example" preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:nil];

[alert addAction:cancelAction];


[[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alert animated:true completion:nil];

How to install Intellij IDEA on Ubuntu?

Recent IntelliJ versions allows automatic creation of desktop entry. See this gist

  1. Launch from commandline. If launching for the first time, setup will ask about creating a desktop launcher icon; say yes. Or else after launching (ie. from the commandline) any time, use the IDEA menu Configure > Create Desktop Entry . That should create /usr/share/applications/intellij-idea-community.desktop
  2. Trigger the Ubuntu desktop search (ie. Windows key), find the Intellij IDEA you used to create the desktop entry.
  3. Drag the icon it's showing into the Ubuntu Launcher.

Changing three.js background to transparent or other color

For transparency, this is also mandatory: renderer = new THREE.WebGLRenderer( { alpha: true } ) via Transparent background with three.js

Split string on the first white space occurrence

Late to the game, I know but there seems to be a very simple way to do this:

_x000D_
_x000D_
const str = "72 tocirah sneab";_x000D_
const arr = str.split(/ (.*)/);_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

This will leave arr[0] with "72" and arr[1] with "tocirah sneab". Note that arr[2] will be empty, but you can just ignore it.

For reference:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split#Capturing_parentheses

How to fix "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" error?

Try this:

 Select 
    Id, 
    Salt, 
    Password, 
    BannedEndDate, 
    (Select Count(*) 
        From LoginFails 
        Where username = '" + LoginModel.Username + "' And IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "')
 From Users 
 Where username = '" + LoginModel.Username + "'

And I recommend you strongly to use parameters in your query to avoid security risks with sql injection attacks!

Hope that helps!

is there a post render callback for Angular JS directive?

Following the fact that the load order cannot be anticipated, a simple solution can be used.

Let's look at the directive-'user of directive' relationship. Usually the user of the directive will supply some data to the directive or use some functionality ( functions ) the directive supplies. The directive on the other hand expects some variables to be defined on its scope.

If we can make sure that all players have all their action requirements fulfilled before they attempt to execute those actions - everything should be well.

And now the directive:

app.directive('aDirective', function () {
    return {
        scope: {
            input: '=',
            control: '='
        },
        link: function (scope, element) {
            function functionThatNeedsInput(){
                //use scope.input here
            }
            if ( scope.input){ //We already have input 
                functionThatNeedsInput();
            } else {
                scope.control.init = functionThatNeedsInput;
            }
          }

        };
})

and now the user of the directive html

<a-directive control="control" input="input"></a-directive>

and somewhere in the controller of the component that uses the directive:

$scope.control = {};
...
$scope.input = 'some data could be async';
if ( $scope.control.functionThatNeedsInput){
    $scope.control.functionThatNeedsInput();
}

That's about it. There is a lot of overhead but you can lose the $timeout. We also assume that the component that uses the directive is instantiated before the directive because we depend on the control variable to exist when the directive is instantiated.

How to get first 5 characters from string

For single-byte strings (e.g. US-ASCII, ISO 8859 family, etc.) use substr and for multi-byte strings (e.g. UTF-8, UTF-16, etc.) use mb_substr:

// singlebyte strings
$result = substr($myStr, 0, 5);
// multibyte strings
$result = mb_substr($myStr, 0, 5);

How to get the text of the selected value of a dropdown list?

The easiest way is through css3 $("select option:selected") and then use the .text() or .html() function. depending on what you want to have.

Div width 100% minus fixed amount of pixels

While Guffa's answer works in many situations, in some cases you may not want the left and/or right pieces of padding to be the parent of the center div. In these cases, you can use a block formatting context on the center and float the padding divs left and right. Here's the code

The HTML:

<div class="container">
    <div class="left"></div>
    <div class="right"></div>
    <div class="center"></div>
</div>

The CSS:

.container {
    width: 100px;
    height: 20px;
}

.left, .right {
    width: 20px;
    height: 100%;
    float: left;
    background: black;   
}

.right {
    float: right;
}

.center {
    overflow: auto;
    height: 100%;
    background: blue;
}

I feel that this element hierarchy is more natural when compared to nested nested divs, and better represents what's on the page. Because of this, borders, padding, and margin can be applied normally to all elements (ie: this 'naturality' goes beyond style and has ramifications).

Note that this only works on divs and other elements that share its 'fill 100% of the width by default' property. Inputs, tables, and possibly others will require you to wrap them in a container div and add a little more css to restore this quality. If you're unlucky enough to be in that situation, contact me and I'll dig up the css.

jsfiddle here: jsfiddle.net/RgdeQ

Enjoy!

How can I select records ONLY from yesterday?

Use:

AND oh.tran_date BETWEEN TRUNC(SYSDATE - 1) AND TRUNC(SYSDATE) - 1/86400

Reference: TRUNC

Calling a function on the tran_date means the optimizer won't be able to use an index (assuming one exists) associated with it. Some databases, such as Oracle, support function based indexes which allow for performing functions on the data to minimize impact in such situations, but IME DBAs won't allow these. And I agree - they aren't really necessary in this instance.

pytest cannot import module while python can

I solved my problem by setting the PYTHONPATH in Environment Variables for the specific configuration I'm running my tests with.

While you're viewing the test file on PyCharm:

  1. Ctrl + Shift + A
  2. Type Edit Configurations
  3. Set your PYTHONPATH under Environment > Environment variables.

Bootstrap 3: How to get two form inputs on one line and other inputs on individual lines?

You can code like two input box inside one div

<div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
            <input style="width:50% " class="form-control " placeholder="first name"  name="firstname" type="text" />
            <input style="width:50% " class="form-control " placeholder="lastname"  name="lastname" type="text" />
        </div>

How to check if a user likes my Facebook Page or URL using Facebook's API

You can do it in JavaScript like so (Building off of @dwarfy's response to a similar question):

<html>
  <head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <style type="text/css">
      div#container_notlike, div#container_like {
        display: none;
      }
    </style>
  </head>
  <body>
    <div id="fb-root"></div>
    <script>
      window.fbAsyncInit = function() {
        FB.init({
          appId      : 'YOUR_APP_ID', // App ID
          channelUrl : 'http(s)://YOUR_APP_DOMAIN/channel.html', // Channel File
          status     : true, // check login status
          cookie     : true, // enable cookies to allow the server to access the session
          xfbml      : true  // parse XFBML
        });

        FB.getLoginStatus(function(response) {
          var page_id = "YOUR_PAGE_ID";
          if (response && response.authResponse) {
            var user_id = response.authResponse.userID;
            var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
            FB.Data.query(fql_query).wait(function(rows) {
              if (rows.length == 1 && rows[0].uid == user_id) {
                console.log("LIKE");
                $('#container_like').show();
              } else {
                console.log("NO LIKEY");
                $('#container_notlike').show();
              }
            });
          } else {
            FB.login(function(response) {
              if (response && response.authResponse) {
                var user_id = response.authResponse.userID;
                var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
                FB.Data.query(fql_query).wait(function(rows) {
                  if (rows.length == 1 && rows[0].uid == user_id) {
                    console.log("LIKE");
                    $('#container_like').show();
                  } else {
                    console.log("NO LIKEY");
                    $('#container_notlike').show();
                  }
                });
              } else {
                console.log("NO LIKEY");
                $('#container_notlike').show();
              }
            }, {scope: 'user_likes'});
          }
        });
      };

      // Load the SDK Asynchronously
      (function(d){
        var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
        js = d.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        d.getElementsByTagName('head')[0].appendChild(js);
      }(document));
    </script>

    <div id="container_notlike">
      YOU DON'T LIKE ME :(
    </div>

    <div id="container_like">
      YOU LIKE ME :)
    </div>

  </body>
</html>

Where the channel.html file on your server just contains the line:

 <script src="//connect.facebook.net/en_US/all.js"></script>

There is a little code duplication in there, but you get the idea. This will pop up a login dialog the first time the user visits the page (which isn't exactly ideal, but works). On subsequent visits nothing should pop up though.

How to remove "rows" with a NA value?

dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))

na.omit(dat)
  x1  x2
1  1 100
3  3 300
5  5 500

Getting multiple keys of specified value of a generic Dictionary?

The "simple" bidirectional dictionary solution proposed here is complex and may be be difficult to understand, maintain or extend. Also the original question asked for "the key for a value", but clearly there could be multiple keys (I've since edited the question). The whole approach is rather suspicious.

Software changes. Writing code that is easy to maintain should be given priority other "clever" complex workarounds. The way to get keys back from values in a dictionary is to loop. A dictionary isn't designed to be bidirectional.

insert data from one table to another in mysql

  INSERT INTO mt_magazine_subscription ( 
      magazine_subscription_id, 
      subscription_name, 
      magazine_id, 
      status ) 
  VALUES ( 
      (SELECT magazine_subscription_id, 
              subscription_name, 
              magazine_id,'1' as status
       FROM tbl_magazine_subscription 
       ORDER BY magazine_subscription_id ASC))

Serializing to JSON in jQuery

I've been using jquery-json for 6 months and it works great. It's very simple to use:

var myObj = {foo: "bar", "baz": "wockaflockafliz"};
$.toJSON(myObj);

// Result: {"foo":"bar","baz":"wockaflockafliz"}

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

Here is an official answer to this:

If Git prompts you for a username and password every time you try to interact with GitHub, you're probably using the HTTPS clone URL for your repository.

Using an HTTPS remote URL has some advantages: it's easier to set up than SSH, and usually works through strict firewalls and proxies. However, it also prompts you to enter your GitHub credentials every time you pull or push a repository.

You can configure Git to store your password for you. If you'd like to set that up, read all about setting up password caching.

How do I undo 'git add' before commit?

You can undo git add before commit with

git reset <file>

which will remove it from the current index (the "about to be committed" list) without changing anything else.

You can use

git reset

without any file name to unstage all due changes. This can come in handy when there are too many files to be listed one by one in a reasonable amount of time.

In old versions of Git, the above commands are equivalent to git reset HEAD <file> and git reset HEAD respectively, and will fail if HEAD is undefined (because you haven't yet made any commits in your repository) or ambiguous (because you created a branch called HEAD, which is a stupid thing that you shouldn't do). This was changed in Git 1.8.2, though, so in modern versions of Git you can use the commands above even prior to making your first commit:

"git reset" (without options or parameters) used to error out when you do not have any commits in your history, but it now gives you an empty index (to match non-existent commit you are not even on).

Documentation: git reset

How to automatically update your docker containers, if base-images are updated

There are a lot of answers here, but none of them suited my needs. I wanted an actual answer to the asker's #1 question. How do I know when an image is updated on hub.docker.com?

The below script can be run daily. On first run, it gets a baseline of the tags and update dates from the HUB registry and saves them locally. From then out, every time it is run it checks the registry for new tags and update dates. Since this changes every time a new image exists, it tells us if the base image has changed. Here is the script:

#!/bin/bash

DATAPATH='/data/docker/updater/data'

if [ ! -d "${DATAPATH}" ]; then
        mkdir "${DATAPATH}";
fi
IMAGES=$(docker ps --format "{{.Image}}")
for IMAGE in $IMAGES; do
        ORIGIMAGE=${IMAGE}
        if [[ "$IMAGE" != *\/* ]]; then
                IMAGE=library/${IMAGE}
        fi
        IMAGE=${IMAGE%%:*}
        echo "Checking ${IMAGE}"
        PARSED=${IMAGE//\//.}
        if [ ! -f "${DATAPATH}/${PARSED}" ]; then
                # File doesn't exist yet, make baseline
                echo "Setting baseline for ${IMAGE}"
                curl -s "https://registry.hub.docker.com/v2/repositories/${IMAGE}/tags/" > "${DATAPATH}/${PARSED}"
        else
                # File does exist, do a compare
                NEW=$(curl -s "https://registry.hub.docker.com/v2/repositories/${IMAGE}/tags/")
                OLD=$(cat "${DATAPATH}/${PARSED}")
                if [[ "${VAR1}" == "${VAR2}" ]]; then
                        echo "Image ${IMAGE} is up to date";
                else
                        echo ${NEW} > "${DATAPATH}/${PARSED}"
                        echo "Image ${IMAGE} needs to be updated";
                        H=`hostname`
                        ssh -i /data/keys/<KEYFILE> <USER>@<REMOTEHOST>.com "{ echo \"MAIL FROM: root@${H}\"; echo \"RCPT TO: <USER>@<EMAILHOST>.com\"; echo \"DATA\"; echo \"Subject: ${H} - ${IMAGE} needs update\"; echo \"\"; echo -e \"\n${IMAGE} needs update.\n\ndocker pull ${ORIGIMAGE}\"; echo \"\"; echo \".\"; echo \"quit\"; sleep 1; } | telnet <SMTPHOST> 25"
                fi

        fi
done;

You will want to alter the DATAPATH variable at the top, and alter the email notification command at the end to suit your needs. For me, I have it SSH into a server on another network where my SMTP is located. But you could easily use the mail command, too.

Now, you also want to check for updated packages inside the containers themselves. This is actually probably more effective than doing a "pull" once your containers are working. Here's the script to pull that off:

#!/bin/bash


function needsUpdates() {
        RESULT=$(docker exec ${1} bash -c ' \
                if [[ -f /etc/apt/sources.list ]]; then \
                grep security /etc/apt/sources.list > /tmp/security.list; \
                apt-get update > /dev/null; \
                apt-get upgrade -oDir::Etc::Sourcelist=/tmp/security.list -s; \
                fi; \
                ')
        RESULT=$(echo $RESULT)
        GOODRESULT="Reading package lists... Building dependency tree... Reading state information... Calculating upgrade... 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded."
        if [[ "${RESULT}" != "" ]] && [[ "${RESULT}" != "${GOODRESULT}" ]]; then
                return 0
        else
                return 1
        fi
}

function sendEmail() {
        echo "Container ${1} needs security updates";
        H=`hostname`
        ssh -i /data/keys/<KEYFILE> <USRER>@<REMOTEHOST>.com "{ echo \"MAIL FROM: root@${H}\"; echo \"RCPT TO: <USER>@<EMAILHOST>.com\"; echo \"DATA\"; echo \"Subject: ${H} - ${1} container needs security update\"; echo \"\"; echo -e \"\n${1} container needs update.\n\n\"; echo -e \"docker exec ${1} bash -c 'grep security /etc/apt/sources.list > /tmp/security.list; apt-get update > /dev/null; apt-get upgrade -oDir::Etc::Sourcelist=/tmp/security.list -s'\n\n\"; echo \"Remove the -s to run the update\"; echo \"\"; echo \".\"; echo \"quit\"; sleep 1; } | telnet <SMTPHOST> 25"
}

CONTAINERS=$(docker ps --format "{{.Names}}")
for CONTAINER in $CONTAINERS; do
        echo "Checking ${CONTAINER}"
        if needsUpdates $CONTAINER; then
                sendEmail $CONTAINER
        fi
done

Scrollview vertical and horizontal in android

I found a better solution.

XML: (design.xml)

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

Java Code:

public class Example extends Activity {
  private RelativeLayout container;
  private int currentX;
  private int currentY;

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.design);

    container = (RelativeLayout)findViewById(R.id.container);

    int top = 0;
    int left = 0;

    ImageView image1 = ...
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(left, top, 0, 0);               
    container.addView(image1, layoutParams);

    ImageView image2 = ...
    left+= 100;
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(left, top, 0, 0);               
    container.addView(image2, layoutParams);

    ImageView image3 = ...
    left= 0;
    top+= 100;
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(left, top, 0, 0);               
    container.addView(image3, layoutParams);

    ImageView image4 = ...
    left+= 100;     
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(left, top, 0, 0);               
    container.addView(image4, layoutParams);
  }     

  @Override 
  public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN: {
            currentX = (int) event.getRawX();
            currentY = (int) event.getRawY();
            break;
        }

        case MotionEvent.ACTION_MOVE: {
            int x2 = (int) event.getRawX();
            int y2 = (int) event.getRawY();
            container.scrollBy(currentX - x2 , currentY - y2);
            currentX = x2;
            currentY = y2;
            break;
        }   
        case MotionEvent.ACTION_UP: {
            break;
        }
    }
      return true; 
  }
}

That's works!!!

If you want to load other layout or control, the structure is the same.

Android DialogFragment vs Dialog

Yes, use DialogFragment and in onCreateDialog you can simply use an AlertDialog builder anyway to create a simple AlertDialog with Yes/No confirmation buttons. Not very much code at all.

With regards handling events in your fragment there would be various ways of doing it but I simply define a message Handler in my Fragment, pass it into the DialogFragment via its constructor and then pass messages back to my fragment's handler as approprirate on the various click events. Again various ways of doing that but the following works for me.

In the dialog hold a message and instantiate it in the constructor:

private Message okMessage;
...
okMessage = handler.obtainMessage(MY_MSG_WHAT, MY_MSG_OK);

Implement the onClickListener in your dialog and then call the handler as appropriate:

public void onClick(.....
    if (which == DialogInterface.BUTTON_POSITIVE) {
        final Message toSend = Message.obtain(okMessage);
        toSend.sendToTarget();
    }
 }

Edit

And as Message is parcelable you can save it out in onSaveInstanceState and restore it

outState.putParcelable("okMessage", okMessage);

Then in onCreate

if (savedInstanceState != null) {
    okMessage = savedInstanceState.getParcelable("okMessage");
}

Find the PID of a process that uses a port on Windows

This helps to find PID using port number.

lsof -i tcp:port_number

Reload chart data via JSON with Highcharts

If you are using push to push the data to the option.series dynamically .. just use

options.series = [];  

to clear it.

options.series = [];
$("#change").click(function(){
}

Execution sequence of Group By, Having and Where clause in SQL Server?

In below Order

  1. FROM & JOIN
  2. WHERE
  3. GROUP BY
  4. HAVING
  5. SELECT
  6. ORDER BY
  7. LIMIT

How to get first character of string?

In JavaScript you can do this:

_x000D_
_x000D_
const x = 'some string';_x000D_
console.log(x.substring(0, 1));
_x000D_
_x000D_
_x000D_

MVC Calling a view from a different controller

You can move you read.aspx view to Shared folder. It is standard way in such circumstances

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

A very simple solution is to search your file(s) for non-ascii characters using a regular expression. This will nicely highlight all the spots where they are found with a border.

Search for [^\x00-\x7F] and check the box for Regex.

The result will look like this (in dark mode):

zero width space made visible

Pandas: drop a level from a multi-level column index?

Another way to do this is to reassign df based on a cross section of df, using the .xs method.

>>> df

    a
    b   c
0   1   2
1   3   4

>>> df = df.xs('a', axis=1, drop_level=True)

    # 'a' : key on which to get cross section
    # axis=1 : get cross section of column
    # drop_level=True : returns cross section without the multilevel index

>>> df

    b   c
0   1   2
1   3   4

What is cURL in PHP?

cURL is a way you can hit a URL from your code to get a HTML response from it. It's used for command line cURL from the PHP language.

<?php
// Step 1
$cSession = curl_init(); 
// Step 2
curl_setopt($cSession,CURLOPT_URL,"http://www.google.com/search?q=curl");
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false); 
// Step 3
$result=curl_exec($cSession);
// Step 4
curl_close($cSession);
// Step 5
echo $result;
?> 

Step 1: Initialize a curl session using curl_init().

Step 2: Set option for CURLOPT_URL. This value is the URL which we are sending the request to. Append a search term curl using parameter q=. Set option for CURLOPT_RETURNTRANSFER. True will tell curl to return the string instead of print it out. Set option for CURLOPT_HEADER, false will tell curl to ignore the header in the return value.

Step 3: Execute the curl session using curl_exec().

Step 4: Close the curl session we have created.

Step 5: Output the return string.

public function curlCall($apiurl, $auth, $rflag)
{
    $ch = curl_init($apiurl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    if($auth == 'auth') { 
        curl_setopt($ch, CURLOPT_USERPWD, "passw:passw");
    } else {
        curl_setopt($ch, CURLOPT_USERPWD, "ss:ss1");
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $dt = curl_exec($ch);        
    curl_close($ch);
    if($rflag != 1) {
        $dt = json_decode($dt,true);        
    }
    return $dt;
}

This is also used for authentication. We can also set the username and password for authentication.

For more functionality, see the user manual or the following tutorial:

http://php.net/manual/en/ref.curl.php
http://www.startutorial.com/articles/view/php-curl

What is the difference between i++ & ++i in a for loop?

Both i++ and ++i are short-hand for i = i + 1.

In addition to changing the value of i, they also return the value of i, either before adding one (i++) or after adding one (++i).

In a loop the third component is a piece of code that is executed after each iteration.

for (int i=0; i<10; i++)

The value of that part is not used, so the above is just the same as

for(int i=0; i<10; i = i+1)

or

for(int i=0; i<10; ++i)

Where it makes a difference (between i++ and ++i )is in these cases

while(i++ < 10)

for (int i=0; i++ < 10; )

How to print current date on python3?

I always use this code, which print the year to second in a tuple

import datetime

now = datetime.datetime.now()

time_now = (now.year, now.month, now.day, now.hour, now.minute, now.second)

print(time_now)

SmtpException: Unable to read data from the transport connection: net_io_connectionclosed

Does your SMTP library supports encrypted connection ? The mail server might be expecting secure TLS connection and hence closing the connection in absence of a TLS handshake

Global constants file in Swift

Or just in GlobalConstants.swift:

import Foundation

let someNotification = "aaaaNotification"

Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

A simple way to enable polymorphic serialization / deserialization via Jackson library is to globally configure the Jackson object mapper (jackson.databind.ObjectMapper) to add information, such as the concrete class type, for certain kinds of classes, such as abstract classes.

To do that, just make sure your mapper is configured correctly. For example:

Option 1: Support polymorphic serialization / deserialization for abstract classes (and Object typed classes)

jacksonObjectMapper.enableDefaultTyping(
    ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE); 

Option 2: Support polymorphic serialization / deserialization for abstract classes (and Object typed classes), and arrays of those types.

jacksonObjectMapper.enableDefaultTyping(
    ObjectMapper.DefaultTyping.NON_CONCRETE_AND_ARRAYS); 

Reference: https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization

Adding a Method to an Existing Object Instance

You can use lambda to bind a method to an instance:

def run(self):
    print self._instanceString

class A(object):
    def __init__(self):
        self._instanceString = "This is instance string"

a = A()
a.run = lambda: run(a)
a.run()

Output:

This is instance string

Java - Search for files in a directory

Using Java 8+ features we can write the code in few lines:

protected static Collection<Path> find(String fileName, String searchDirectory) throws IOException {
    try (Stream<Path> files = Files.walk(Paths.get(searchDirectory))) {
        return files
                .filter(f -> f.getFileName().toString().equals(fileName))
                .collect(Collectors.toList());

    }
}

Files.walk returns a Stream<Path> which is "walking the file tree rooted at" the given searchDirectory. To select the desired files only a filter is applied on the Stream files. It compares the file name of a Path with the given fileName.

Note that the documentation of Files.walk requires

This method must be used within a try-with-resources statement or similar control structure to ensure that the stream's open directories are closed promptly after the stream's operations have completed.

I'm using the try-resource-statement.


For advanced searches an alternative is to use a PathMatcher:

protected static Collection<Path> find(String searchDirectory, PathMatcher matcher) throws IOException {
    try (Stream<Path> files = Files.walk(Paths.get(searchDirectory))) {
        return files
                .filter(matcher::matches)
                .collect(Collectors.toList());

    }
}

An example how to use it to find a certain file:

public static void main(String[] args) throws IOException {
    String searchDirectory = args[0];
    String fileName = args[1];
    PathMatcher matcher = FileSystems.getDefault().getPathMatcher("regex:.*" + fileName);
    Collection<Path> find = find(searchDirectory, matcher);
    System.out.println(find);
}

More about it: Oracle Finding Files tutorial

Should I learn C before learning C++?

I love this question - it's like asking "what should I learn first, snowboarding or skiing"? I think it depends if you want to snowboard or to ski. If you want to do both, you have to learn both.

In both sports, you slide down a hill on snow using devices that are sufficiently similar to provoke this question. However, they are also sufficiently different so that learning one does not help you much with the other. Same thing with C and C++. While they appear to be languages sufficiently similar in syntax, the mind set that you need for writing OO code vs procedural code is sufficiently different so that you pretty much have to start from the beginning, whatever language you learn second.

Fastest way to check if a string matches a regexp in ruby?

Depending on how complicated your regular expression is, you could possibly just use simple string slicing. I'm not sure about the practicality of this for your application or whether or not it would actually offer any speed improvements.

'testsentence'['stsen']
=> 'stsen' # evaluates to true
'testsentence'['koala']
=> nil # evaluates to false

Data at the root level is invalid

I found that the example I was using had an xml document specification on the first line. I was using a stylesheet I got at this blog entry and the first line was

<?xmlversion="1.0"encoding="utf-8"?>

which was causing the error. When I removed that line, so that the stylesheet started with the line

<xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

my transform worked. By the way, that blog post was the first good, easy-to follow example I have found for trying to get information from the XML definition of an SSIS package, but I did have to modify the paths in the example for my SSIS 2008 packages, so you might too. I also created a version to extract the "flow" from the precedence constraints. My final one looks like this:

    <xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" encoding="utf-8" />
    <xsl:template match="/">
    <xsl:text>From,To~</xsl:text>
    <xsl:text>
</xsl:text>
    <xsl:for-each select="//DTS:PrecedenceConstraints/DTS:PrecedenceConstraint">
      <xsl:value-of select="@DTS:From"/>
      <xsl:text>,</xsl:text>
      <xsl:value-of select="@DTS:To"/>
       <xsl:text>~</xsl:text>
      <xsl:text>
</xsl:text>
    </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

and gave me a CSV with the tilde as my line delimiter. I replaced that with a line feed in my text editor then imported into excel to get a with look at the data flow in the package.

Get/pick an image from Android's built-in Gallery app programmatically

Additional to previous answers, if you are having problems with getting the right path(like AndroZip) you can use this:

  public String getPath(Uri uri ,ContentResolver contentResolver) {
        String[] projection = {  MediaStore.MediaColumns.DATA};
        Cursor cursor;
        try{
            cursor = contentResolver.query(uri, projection, null, null, null);
        } catch (SecurityException e){
            String path = uri.getPath();
            String result = tryToGetStoragePath(path);
            return  result;
        }
        if(cursor != null) {
            //HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
            //THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
            String filePath = cursor.getString(columnIndex);
            cursor.close();
            return filePath;
        }
        else
            return uri.getPath();               // FOR OI/ASTRO/Dropbox etc
    }

    private String tryToGetStoragePath(String path) {
        int actualPathStart = path.indexOf("//storage");
        String result = path;

        if(actualPathStart!= -1 && actualPathStart< path.length())
            result = path.substring(actualPathStart+1 , path.length());

        return result;
    }

How to use Global Variables in C#?

There's no such thing as a global variable in C#. Period.

You can have static members if you want:

public static class MyStaticValues
{
   public static bool MyStaticBool {get;set;}
}

How to convert a char array to a string?

The string class has a constructor that takes a NULL-terminated C-string:

char arr[ ] = "This is a test";

string str(arr);


//  You can also assign directly to a string.
str = "This is another string";

// or
str = arr;

How to clear a chart from a canvas so that hover events cannot be triggered?

Since destroy kind of destroys "everything", a cheap and simple solution when all you really want is to just "reset the data". Resetting your datasets to an empty array will work perfectly fine as well. So, if you have a dataset with labels, and an axis on each side:

window.myLine2.data.labels = [];
window.myLine2.data.datasets[0].data = [];
window.myLine2.data.datasets[1].data = [];

After this, you can simply call:

window.myLine2.data.labels.push(x);
window.myLine2.data.datasets[0].data.push(y);

or, depending whether you're using a 2d dataset:

window.myLine2.data.datasets[0].data.push({ x: x, y: y});

It'll be a lot more lightweight than completely destroying your whole chart/dataset, and rebuilding everything.

How do I setup a SSL certificate for an express.js server?

I was able to get SSL working with the following boilerplate code:

var fs = require('fs'),
    http = require('http'),
    https = require('https'),
    express = require('express');

var port = 8000;

var options = {
    key: fs.readFileSync('./ssl/privatekey.pem'),
    cert: fs.readFileSync('./ssl/certificate.pem'),
};

var app = express();

var server = https.createServer(options, app).listen(port, function(){
  console.log("Express server listening on port " + port);
});

app.get('/', function (req, res) {
    res.writeHead(200);
    res.end("hello world\n");
});

Save child objects automatically using JPA Hibernate

I tried the above but I'm getting a database error complaining that the foreign key field in the Child table can not be NULL. Is there a way to tell JPA to automatically set this foreign key into the Child object so it can automatically save children objects?

Well, there are two things here.

First, you need to cascade the save operation (but my understanding is that you are doing this or you wouldn't get a FK constraint violation during inserts in the "child" table)

Second, you probably have a bidirectional association and I think that you're not setting "both sides of the link" correctly. You are supposed to do something like this:

Parent parent = new Parent();
...
Child c1 = new Child();
...
c1.setParent(parent);

List<Child> children = new ArrayList<Child>();
children.add(c1);
parent.setChildren(children);

session.save(parent);

A common pattern is to use link management methods:

@Entity
public class Parent {
    @Id private Long id;

    @OneToMany(mappedBy="parent")
    private List<Child> children = new ArrayList<Child>();

    ...

    protected void setChildren(List<Child> children) {
        this.children = children;
    }

    public void addToChildren(Child child) {
        child.setParent(this);
        this.children.add(child);
    }
}

And the code becomes:

Parent parent = new Parent();
...
Child c1 = new Child();
...

parent.addToChildren(c1);

session.save(parent);
References

Can I connect to SQL Server using Windows Authentication from Java EE webapp?

Unless you have some really compelling reason not to, I suggest ditching the MS JDBC driver.

Instead, use the jtds jdbc driver. Read the README.SSO file in the jtds distribution on how to configure for single-sign-on (native authentication) and where to put the native DLL to ensure it can be loaded by the JVM.

Parameterize an SQL IN clause

The only winning move is not to play.

No infinite variability for you. Only finite variability.

In the SQL you have a clause like this:

and ( {1}==0 or b.CompanyId in ({2},{3},{4},{5},{6}) )

In the C# code you do something like this:

  int origCount = idList.Count;
  if (origCount > 5) {
    throw new Exception("You may only specify up to five originators to filter on.");
  }
  while (idList.Count < 5) { idList.Add(-1); }  // -1 is an impossible value
  return ExecuteQuery<PublishDate>(getValuesInListSQL, 
               origCount,   
               idList[0], idList[1], idList[2], idList[3], idList[4]);

So basically if the count is 0 then there is no filter and everything goes through. If the count is higher than 0 the then the value must be in the list, but the list has been padded out to five with impossible values (so that the SQL still makes sense)

Sometimes the lame solution is the only one that actually works.

Is there a way to add/remove several classes in one single instruction with classList?

I found a very simple method which is more modern and elegant way.


const el = document.querySelector('.m-element');

// To toggle
['class1', 'class2'].map((e) => el.classList.toggle(e));

// To add
['class1', 'class2'].map((e) => el.classList.add(e));

// To remove
['class1', 'class2'].map((e) => el.classList.remove(e));

Good thing is you can extend the class array or use any coming from API easily.

C++ convert string to hexadecimal and vice versa

Using lookup tables and the like works, but is just overkill, here are some very simple ways of taking a string to hex and hex back to a string:

#include <stdexcept>
#include <sstream>
#include <iomanip>
#include <string>
#include <cstdint>

std::string string_to_hex(const std::string& in) {
    std::stringstream ss;

    ss << std::hex << std::setfill('0');
    for (size_t i = 0; in.length() > i; ++i) {
        ss << std::setw(2) << static_cast<unsigned int>(static_cast<unsigned char>(in[i]));
    }

    return ss.str(); 
}

std::string hex_to_string(const std::string& in) {
    std::string output;

    if ((in.length() % 2) != 0) {
        throw std::runtime_error("String is not valid length ...");
    }

    size_t cnt = in.length() / 2;

    for (size_t i = 0; cnt > i; ++i) {
        uint32_t s = 0;
        std::stringstream ss;
        ss << std::hex << in.substr(i * 2, 2);
        ss >> s;

        output.push_back(static_cast<unsigned char>(s));
    }

    return output;
}

How to deselect a selected UITableView cell?

Swift 3

I've run into this as well - when you navigate or unwind back to the table view it usually doesn't deselect the previously selected row for you. I put this code in the table view controller & it works well:

override func viewDidAppear(_ animated: Bool) {
    if let lastSelectedRow = tableView.indexPathForSelectedRow {
        tableView.deselectRow(at: lastSelectedRow, animated: true)
    }
}

The identity used to sign the executable is no longer valid

Found another way this occurs today. When you edit your provisioning profile after a certificate change you can see the certificates selected says 2 of 1 certificates selected (if you just use 1 certificate). Just by unselecting and reselecting the certificate you can regenerate and install the profile and it solves the problem.

How do I pass named parameters with Invoke-Command?

My solution to this was to write the script block dynamically with [scriptblock]:Create:

# Or build a complex local script with MARKERS here, and do substitutions
# I was sending install scripts to the remote along with MSI packages
# ...for things like Backup and AV protection etc.

$p1 = "good stuff"; $p2 = "better stuff"; $p3 = "best stuff"; $etc = "!"
$script = [scriptblock]::Create("MyScriptOnRemoteServer.ps1 $p1 $p2 $etc")
#strings get interpolated/expanded while a direct scriptblock does not

# the $parms are now expanded in the script block itself
# ...so just call it:
$result = invoke-command $computer -script $script

Passing arguments was very frustrating, trying various methods, e.g.,
-arguments, $using:p1, etc. and this just worked as desired with no problems.

Since I control the contents and variable expansion of the string which creates the [scriptblock] (or script file) this way, there is no real issue with the "invoke-command" incantation.

(It shouldn't be that hard. :) )

How to add a named sheet at the end of all Excel sheets?

Try this:

Public Enum iSide
iBefore
iAfter
End Enum
Private Function addSheet(ByRef inWB As Workbook, ByVal inBeforeOrAfter As iSide, ByRef inNamePrefix As String, ByVal inName As String) As Worksheet
    On Error GoTo the_dark

    Dim wsSheet As Worksheet
    Dim bFoundWS As Boolean
    bFoundWS = False
    If inNamePrefix <> "" Then
        Set wsSheet = findWS(inWB, inNamePrefix, bFoundWS)
    End If

    If inBeforeOrAfter = iAfter Then
        If wsSheet Is Nothing Or bFoundWS = False Then
            Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = inName
        Else
            Worksheets.Add(After:=wsSheet).Name = inName
        End If
    Else
        If wsSheet Is Nothing Or bFoundWS = False Then
            Worksheets.Add(Before:=Worksheets(1)).Name = inName
        Else
            Worksheets.Add(Before:=wsSheet).Name = inName
        End If
    End If

    Set addSheet = findWS(inWB, inName, bFoundWS)         ' just to confirm it exists and gets it handle

    the_light:
    Exit Function
    the_dark:
    MsgBox "addSheet: " & inName & ": " & Err.Description, vbOKOnly, "unexpected error"
    Err.Clear
    GoTo the_light
End Function

Remove all elements contained in another array

I just implemented as:

Array.prototype.exclude = function(list){
        return this.filter(function(el){return list.indexOf(el)<0;})
}

Use as:

myArray.exclude(toRemove);

Rename multiple files in a folder, add a prefix (Windows)

Based on @ofer.sheffer answer this command will mass rename and append the current date to the filename. ie "file.txt" becomes "20180329 - file.txt" for all files in the current folder

for %a in (*.*) do ren "%a" "%date:~-4,4%%date:~-7,2%%date:~-10,2% - %a"

Spring: How to get parameters from POST body?

In class do like this

@RequestMapping(value = "/saveData", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Boolean> saveData(
    HttpServletResponse response,
    Bean beanName
) throws MyException {
    return new ResponseEntity<Boolean>(uiRequestProcessor.saveData(a), HttpStatus.OK);
}

In page do like this:

<form enctype="multipart/form-data" action="<%=request.getContextPath()%>/saveData" method="post" name="saveForm" id="saveForm">
<input type="text" value="${beanName.userName }" id="username" name="userName" />

</from>

iPhone 5 CSS media query

iPhone 5 in portrait & landscape

@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 568px) {

/* styles*/
}

iPhone 5 in landscape

@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 568px) 
and (orientation : landscape) { 
/* styles*/

}

iPhone 5 in portrait

@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 568px) 
and (orientation : portrait) { 
 /* styles*/

}

Git Pull is Not Possible, Unmerged Files

I got solved with git remove the unmerged file locally.

$ git rm <the unmerged file name>
$ git reset --hard
$ git pull --rebase
$ git rebase --skip
$ git pull
Already up-to-date.

When I send git commit afterward:

$ git commit . -m "my send commit"
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working directory clean

Log4net does not write the log in the log file

Your config file seems correct. Then, you have to register your Log4net config file to application. So you can use below code:

var logRepo = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepo, new FileInfo("log4net.config"));

After registering process, you can call below definition to call logger:

private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

log.Error("Sample log");

Check If array is null or not in php

Right code of two ppl before ^_^

/* return true if values of array are empty
*/
function is_array_empty($arr){
   if(is_array($arr)){
      foreach($arr as $value){
         if(!empty($value)){
            return false;
         }
      }
   }
   return true;
}

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

Got this error because I had the Data Source Name in User DSN instead of System DSN enter image description here

Matching an optional substring in a regex

You can do this:

([0-9]+) (\([^)]+\))? Z

This will not work with nested parens for Y, however. Nesting requires recursion which isn't strictly regular any more (but context-free). Modern regexp engines can still handle it, albeit with some difficulties (back-references).

How to change already compiled .class file without decompile?

I added some codes and save .class file.

What you see in JD EClipse Decompiler is decompiled representation of byte code in the .class file. Even though you change the text it won't affect the byte code.

Java: How to check if object is null?

Just to give some ideas to oracle Java source developer :-)

The solution already exists in .Net and is more very more readable !

In Visual Basic .Net

Drawable drawable 
    = If(Common.getDrawableFromUrl(this, product.getMapPath())
        ,getRandomDrawable()
        )

In C#

Drawable drawable 
    = Common.getDrawableFromUrl(this, product.getMapPath() 
        ?? getRandomDrawable();

These solutions are powerful as Optional Java solution (default string is only evaluated if original value is null) without using lambda expression, just in adding a new operator.

Just to see quickly the difference with Java solution, I have added the 2 Java solutions

Using Optional in Java

Drawable drawable = 
    Optional.ofNullable(Common.getDrawableFromUrl(this, product.getMapPath()))
        .orElseGet(() -> getRandomDrawable());

Using { } in Java

Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (drawable != null)
    {
    drawable = getRandomDrawable();
    }

Personally, I like VB.Net but I prefer ?? C# or if {} solution in Java ... and you ?

dropdownlist set selected value in MVC3 Razor

To have the IT department selected, when the departments are loaded from tblDepartment table, use the following overloaded constructor of SelectList class. Notice that we are passing a value of 1 for selectedValue parameter.

ViewBag.Departments = new SelectList(db.Departments, "Id", "Name", "1");

How do I simulate a hover with a touch in touch enabled browsers?

Try this:

<script>
document.addEventListener("touchstart", function(){}, true);
</script>

And in your CSS:

element:hover, element:active {
-webkit-tap-highlight-color: rgba(0,0,0,0);
-webkit-user-select: none;
-webkit-touch-callout: none /*only to disable context menu on long press*/
}

With this code you don't need an extra .hover class!

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

Annotation-driven indicates to Spring that it should scan for annotated beans, and to not just rely on XML bean configuration. Component-scan indicates where to look for those beans.

Here's some doc: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-enable

How to Add a Dotted Underline Beneath HTML Text

It's impossible without CSS. In fact, the <u> tag is simply adding text-decoration:underline to the text with the browser's built-in CSS.

Here's what you can do:

<html>
<head>
<!-- Other head stuff here, like title or meta -->

<style type="text/css">
u {    
    border-bottom: 1px dotted #000;
    text-decoration: none;
}
</style>
</head>
<!-- Body, content here -->
</html>

How to select all and copy in vim?

In normal mode:

gg"+yG

In ex mode:

:%y+

How to get css background color on <tr> tag to span entire row

Have you tried setting the spacing to zero?

/*alternating row*/
table, tr, td, th {margin:0;border:0;padding:0;spacing:0;}
tr.rowhighlight {background-color:#f0f8ff;margin:0;border:0;padding:0;spacing:0;}

Git keeps asking me for my ssh key passphrase

Once you have started the SSH agent with:

eval $(ssh-agent)

Do either:

  1. To add your private key to it:

     ssh-add
    

    This will ask you your passphrase just once, and then you should be allowed to push, provided that you uploaded the public key to Github.

  2. To add and save your key permanently on macOS:

     ssh-add -K  
    

    This will persist it after you close and re-open it by storing it in user's keychain.

  3. To add and save your key permanently on Ubuntu (or equivalent):

      ssh-add ~/.ssh/id_rsa
    

Android simple alert dialog

No my friend its very simple, try using this:

AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create();
alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage("Welcome to dear user.");
alertDialog.setIcon(R.drawable.welcome);

alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
    }
});

alertDialog.show();

This tutorial shows how you can create custom dialog using xml and then show them as an alert dialog.

Disable future dates in jQuery UI Datepicker

$('#thedate,#dateid').datepicker({
     changeMonth:true,
         changeYear:true,
         yearRange:"-100:+0",
         dateFormat:"dd/mm/yy" ,
         maxDate: '0',
     });
});

UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)

Just putting .encode('utf-8') at the end of object will do the job in recent versions of Python.

an htop-like tool to display disk activity in linux

You could use iotop. It doesn't rely on a kernel patch. It Works with stock Ubuntu kernel

There is a package for it in the Ubuntu repos. You can install it using

sudo apt-get install iotop

iotop

PHP Fatal error: Class 'PDO' not found

I solved it with library PHP_PDO , because my hosting provider didn't accept my requirement for installation of PDO driver to apache server.

Drop Down Menu/Text Field in one

I like jQuery Token input. Actually prefer the UI over some of the other options mentioned above.

http://loopj.com/jquery-tokeninput/

Also see: http://railscasts.com/episodes/258-token-fields for an explanation

How to prevent scrollbar from repositioning web page?

My approach is to make the track transparent. The scroll bar thumb color is #C1C1C1 to match the default scrollbar thumb color. You can make it anything you prefer :)

Try this:

html {
    overflow-y: scroll;
}

body::-webkit-scrollbar {
    width: 0.7em;
    background-color: transparent;
}

body::-webkit-scrollbar-thumb {
    background: #C1C1C1;
    height:30px;
}

body::-webkit-scrollbar-track-piece
{
    display:none;
}

In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

I think your best option would just be to include the readonly attribute in your template rendered in a <span> or <p> rather than include it in the form if it's readonly.

Forms are for collecting data, not displaying it. That being said, the options to display in a readonly widget and scrub POST data are fine solutions.

Error message "Unable to install or run the application. The application requires stdole Version 7.0.3300.0 in the GAC"

I my case, I solved this issue going to the Publish tab in the project properties and then select the Application Files button. Then just:

Note: Before you apply this solution, make sure that you have already (as I did), checked all your solution's projects and found no references to stdole.dll assembly.

1 - Located stdole.dll file;

2 - Changed its Publish status to Exclude

3 - After that you need to republish your application.

This issue happened on a Visual Studio 2012, after its migration from Visual Studio 2010.

Hope it helps.

Python Timezone conversion

Python 3.9 adds the zoneinfo module so now only the the standard library is needed!

>>> from zoneinfo import ZoneInfo
>>> from datetime import datetime

>>> d = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo('America/Los_Angeles'))
>>> d.astimezone(ZoneInfo('Europe/Berlin'))  # 12:00 in Cali will be 20:00 in Berlin
datetime.datetime(2020, 10, 31, 20, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))

Wikipedia list of available time zones


Some functions such as now() and utcnow() return timezone-unaware datetimes, meaning they contain no timezone information. I recommend only requesting timezone-aware values from them using the keyword tz=ZoneInfo('localtime').

If astimezone gets a timezone-unaware input, it will assume it is local time, which can lead to errors:

>>> datetime.utcnow()  # UTC -- NOT timezone-aware!!
datetime.datetime(2020, 6, 1, 22, 39, 57, 376479)
>>> datetime.now()     # Local time -- NOT timezone-aware!!
datetime.datetime(2020, 6, 2, 0, 39, 57, 376675)

>>> datetime.now(tz=ZoneInfo('localtime'))  # timezone-aware
datetime.datetime(2020, 6, 2, 0, 39, 57, 376806, tzinfo=zoneinfo.ZoneInfo(key='localtime'))
>>> datetime.now(tz=ZoneInfo('Europe/Berlin'))  # timezone-aware
datetime.datetime(2020, 6, 2, 0, 39, 57, 376937, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))
>>> datetime.utcnow().astimezone(ZoneInfo('Europe/Berlin'))  # WRONG!!
datetime.datetime(2020, 6, 1, 22, 39, 57, 377562, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))

Windows has no system time zone database, so here an extra package is needed:

pip install tzdata  

There is a backport to allow use in Python 3.6 to 3.8:

sudo pip install backports.zoneinfo

Then:

from backports.zoneinfo import ZoneInfo

Powershell Get-ChildItem most recent file in directory

You could try to sort descending "sort LastWriteTime -Descending" and then "select -first 1." Not sure which one is faster

Convert all first letter to upper case, rest lower for each word

Try this technique; It returns the desired result

CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());

And don't forget to use System.Globalization.

Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?

My answer is little late but simple; but may help someone in future; I did experiment with angular versions such as 4.4.3, 5.1+, 6.x, 7.x, 8.x, 9.x and 10.x using $event (latest at the moment)

Template:

<select (change)="onChange($event)">
    <option *ngFor="let v of values" [value]="v.id">{{v.name}}</option>
</select>

TS

export class MyComponent {
  public onChange(event): void {  // event will give you full breif of action
    const newVal = event.target.value;
    console.log(newVal);
  }
}

JavaFX open new window

I use the following method in my JavaFX applications.

newWindowButton.setOnMouseClicked((event) -> {
    try {
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(getClass().getResource("NewWindow.fxml"));
        /* 
         * if "fx:controller" is not set in fxml
         * fxmlLoader.setController(NewWindowController);
         */
        Scene scene = new Scene(fxmlLoader.load(), 600, 400);
        Stage stage = new Stage();
        stage.setTitle("New Window");
        stage.setScene(scene);
        stage.show();
    } catch (IOException e) {
        Logger logger = Logger.getLogger(getClass().getName());
        logger.log(Level.SEVERE, "Failed to create new Window.", e);
    }
});

Timer for Python game

In this example the loop is run every second for ten seconds:

import datetime, time
then = datetime.datetime.now() + datetime.timedelta(seconds=10)
while then > datetime.datetime.now():
    print 'sleeping'
    time.sleep(1)

Get absolute path of initially run script

realpath($_SERVER['SCRIPT_FILENAME'])

For script run under web server $_SERVER['SCRIPT_FILENAME'] will contain the full path to the initially called script, so probably your index.php. realpath() is not required in this case.

For the script run from console $_SERVER['SCRIPT_FILENAME'] will contain relative path to your initially called script from your current working dir. So unless you changed working directory inside your script it will resolve to the absolute path.

Max size of URL parameters in _GET

See What is the maximum length of a URL in different browsers?

The length of the url can't be changed in PHP. The linked question is about the URL size limit, you will find what you want.

Better solution without exluding fields from Binding

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

No need for a custom class. This is all that is needed:

return new JsonResult { Data = Result, MaxJsonLength = Int32.MaxValue };

where Result is that data you wish to serialize.

iFrame src change event detection?

Note: The snippet would only work if the iframe is with the same origin.

Other answers proposed the load event, but it fires after the new page in the iframe is loaded. You might need to be notified immediately after the URL changes, not after the new page is loaded.

Here's a plain JavaScript solution:

_x000D_
_x000D_
function iframeURLChange(iframe, callback) {_x000D_
    var unloadHandler = function () {_x000D_
        // Timeout needed because the URL changes immediately after_x000D_
        // the `unload` event is dispatched._x000D_
        setTimeout(function () {_x000D_
            callback(iframe.contentWindow.location.href);_x000D_
        }, 0);_x000D_
    };_x000D_
_x000D_
    function attachUnload() {_x000D_
        // Remove the unloadHandler in case it was already attached._x000D_
        // Otherwise, the change will be dispatched twice._x000D_
        iframe.contentWindow.removeEventListener("unload", unloadHandler);_x000D_
        iframe.contentWindow.addEventListener("unload", unloadHandler);_x000D_
    }_x000D_
_x000D_
    iframe.addEventListener("load", attachUnload);_x000D_
    attachUnload();_x000D_
}_x000D_
_x000D_
iframeURLChange(document.getElementById("mainframe"), function (newURL) {_x000D_
    console.log("URL changed:", newURL);_x000D_
});
_x000D_
<iframe id="mainframe" src=""></iframe>
_x000D_
_x000D_
_x000D_

This will successfully track the src attribute changes, as well as any URL changes made from within the iframe itself.

Tested in all modern browsers.

I made a gist with this code as well. You can check my other answer too. It goes a bit in-depth into how this works.

scp from Linux to Windows

Try this, it really works.

$ scp username@from_host_ip:/home/ubuntu/myfile /cygdrive/c/Users/Anshul/Desktop

And for copying all files

$ scp -r username@from_host_ip:/home/ubuntu/ *. * /cygdrive/c/Users/Anshul/Desktop

Check line for unprintable characters while reading text file

While it's not hard to do this manually using BufferedReader and InputStreamReader, I'd use Guava:

List<String> lines = Files.readLines(file, Charsets.UTF_8);

You can then do whatever you like with those lines.

EDIT: Note that this will read the whole file into memory in one go. In most cases that's actually fine - and it's certainly simpler than reading it line by line, processing each line as you read it. If it's an enormous file, you may need to do it that way as per T.J. Crowder's answer.

Simplest SOAP example

This is the simplest JavaScript SOAP Client I can create.

<html>
<head>
    <title>SOAP JavaScript Client Test</title>
    <script type="text/javascript">
        function soap() {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.open('POST', 'https://somesoapurl.com/', true);

            // build SOAP request
            var sr =
                '<?xml version="1.0" encoding="utf-8"?>' +
                '<soapenv:Envelope ' + 
                    'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
                    'xmlns:api="http://127.0.0.1/Integrics/Enswitch/API" ' +
                    'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +
                    'xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">' +
                    '<soapenv:Body>' +
                        '<api:some_api_call soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' +
                            '<username xsi:type="xsd:string">login_username</username>' +
                            '<password xsi:type="xsd:string">password</password>' +
                        '</api:some_api_call>' +
                    '</soapenv:Body>' +
                '</soapenv:Envelope>';

            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4) {
                    if (xmlhttp.status == 200) {
                        alert(xmlhttp.responseText);
                        // alert('done. use firebug/console to see network response');
                    }
                }
            }
            // Send the POST request
            xmlhttp.setRequestHeader('Content-Type', 'text/xml');
            xmlhttp.send(sr);
            // send request
            // ...
        }
    </script>
</head>
<body>
    <form name="Demo" action="" method="post">
        <div>
            <input type="button" value="Soap" onclick="soap();" />
        </div>
    </form>
</body>
</html> <!-- typo -->

SSL "Peer Not Authenticated" error with HttpClient 4.1

This is thrown when

... the peer was not able to identify itself (for example; no certificate, the particular cipher suite being used does not support authentication, or no peer authentication was established during SSL handshaking) this exception is thrown.

Probably the cause of this exception (where is the stacktrace) will show you why this exception is thrown. Most likely the default keystore shipped with Java does not contain (and trust) the root certificate of the TTP that is being used.

The answer is to retrieve the root certificate (e.g. from your browsers SSL connection), import it into the cacerts file and trust it using keytool which is shipped by the Java JDK. Otherwise you will have to assign another trust store programmatically.

How to ignore PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException?

I got the same error while executing the below spring-boot + RestAssured simple test.

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static com.jayway.restassured.RestAssured.when;
import static org.apache.http.HttpStatus.SC_OK;

@RunWith(SpringJUnit4ClassRunner.class)
public class GeneratorTest {

@Test
public void generatorEndPoint() {
    when().get("https://bal-bla-bla-bla.com/generators")
            .then().statusCode(SC_OK);
    }
}

The simple fix in my case is to add 'useRelaxedHTTPSValidations()'

RestAssured.useRelaxedHTTPSValidation();

Then the test looks like

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static com.jayway.restassured.RestAssured.when;
import static org.apache.http.HttpStatus.SC_OK;

@RunWith(SpringJUnit4ClassRunner.class)
public class GeneratorTest {

@Before
public void setUp() {
   RestAssured.useRelaxedHTTPSValidation();
}


@Test
public void generatorEndPoint() {
    when().get("https://bal-bla-bla-bla.com/generators")
            .then().statusCode(SC_OK);
    }
}

How to add multiple classes to a ReactJS Component?

Late to the party, but why use third party for such a simple problem?

You could either do it as @Huw Davies mentioned - the best way

1. <i className={`${styles['foo-bar-baz']} fa fa-user fa-2x`}/>
2. <i className={[styles['foo-bar-baz'], 'fa fa-user', 'fa-2x'].join(' ')}

Both are good. But writing can become complex for a large app. To make it optimal, I do the same above things but put it in a helper class

Using my below helper function, allows me to keep the logic separate for future editing, and also gives me multiple ways to add the classes

classNames(styles['foo-bar-baz], 'fa fa-user', 'fa-2x')

or

classNames([styles['foo-bar-baz], 'fa fa-user', 'fa-2x'])

This is my helper function below. I've put it in a helper.js where I keep all my common methods. Being such a simple function, I avoided using 3rd party to keep control

export function classNames (classes) {
    if(classes && classes.constructor === Array) {
        return classes.join(' ')
    } else if(arguments[0] !== undefined) {
        return [...arguments].join(' ')
    }
    return ''
}

WPF C# button style

Here's my attempt. Looks more similar to the OP's sample and provides settable properties for icon (FrameworkElement), title (string) and subtitle (string). The output looks like this:

enter image description here

Here's XAML:

<Button x:Class="Controls.FancyButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:Controls"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300" Width="300" Height="80"
          BorderBrush="{x:Null}" BorderThickness="0">
  <Button.Effect>
    <DropShadowEffect BlurRadius="12" Color="Gray" Direction="270" Opacity=".8" ShadowDepth="3" />
  </Button.Effect>

  <Button.Template>
    <ControlTemplate TargetType="Button">
      <Grid Width="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=ActualWidth}"
        Height="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=ActualHeight}">

        <Border x:Name="MainBorder" CornerRadius="3" Grid.ColumnSpan="2" Margin="0,0,4,4" BorderBrush="Black" BorderThickness="1">
          <Border.Background>
            <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
              <GradientStop Color="#FF5E5E5E" Offset="0" />
              <GradientStop Color="#FF040404" Offset="1" />
            </LinearGradientBrush>
          </Border.Background>

          <Grid >
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="1.2*"/>
              <ColumnDefinition Width="3*"/>
            </Grid.ColumnDefinitions>

            <Border CornerRadius="2" Margin="0" BorderBrush="LightGray" BorderThickness="0,1,0,0" Grid.ColumnSpan="2" Grid.RowSpan="2" />

            <Line X1="10" Y1="0" X2="10" Y2="10" Stretch="Fill" Grid.Column="0" HorizontalAlignment="Right" Stroke="#0C0C0C" Grid.RowSpan="2" />
            <Line X1="10" Y1="0" X2="10" Y2="10" Stretch="Fill" Grid.Column="1" HorizontalAlignment="Left" Grid.RowSpan="2">
              <Line.Stroke>
                <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                  <GradientStop Color="#4D4D4D" Offset="0" />
                  <GradientStop Color="#2C2C2C" Offset="1" />
                </LinearGradientBrush>
              </Line.Stroke>
            </Line>

            <ContentControl HorizontalAlignment="Center" VerticalAlignment="Center" Grid.RowSpan="2">
              <ContentControl.Content>
                <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="Image">
                  <Binding.FallbackValue>
                    <Path Data="M0,0 L30,15 L0,30Z">
                      <Path.Effect>
                        <DropShadowEffect Direction="50" ShadowDepth="2" />
                      </Path.Effect>
                      <Path.Fill>
                        <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
                          <GradientStop Color="#4B86B2" Offset="0" />
                          <GradientStop Color="#477FA8" Offset="1" />
                        </LinearGradientBrush>
                      </Path.Fill>
                    </Path>
                  </Binding.FallbackValue>
                </Binding>
              </ContentControl.Content>
            </ContentControl>


            <Grid Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center">
              <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
              </Grid.RowDefinitions>

              <TextBlock x:Name="Title" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Title, FallbackValue='Watch Now'}" Grid.Column="1" VerticalAlignment="Bottom" FontFamily="Calibri" FontWeight="Bold" FontSize="28" Foreground="White" Margin="20,0,0,0" />
              <TextBlock x:Name="SubTitle" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SubTitle, FallbackValue='Duration: 50 min'}" Grid.Column="1" Grid.Row="1" VerticalAlignment="top" FontFamily="Calibri" FontSize="14" Foreground="White" Margin="20,0,0,0" />
            </Grid>
          </Grid>
        </Border>
      </Grid>

      <ControlTemplate.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
          <Setter TargetName="Title" Property="TextDecorations" Value="Underline" />
          <Setter TargetName="SubTitle" Property="TextDecorations" Value="Underline" />
        </Trigger>
        <Trigger Property="IsPressed" Value="True">
          <Setter TargetName="MainBorder" Property="Background">
            <Setter.Value>
              <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                <GradientStop Color="#FF5E5E5E" Offset="0" />
                <GradientStop Color="#FFA4A4A4" Offset="1" />
              </LinearGradientBrush>
            </Setter.Value>
          </Setter>
        </Trigger>
      </ControlTemplate.Triggers>
    </ControlTemplate>
  </Button.Template>
</Button>

Here's the code-behind:

using System.Windows;
using System.Windows.Controls;

namespace Controls
{
  public partial class FancyButton : Button
  {
    public FancyButton()
    {
      InitializeComponent();
    }

    public string Title
    {
      get { return (string)GetValue(TitleProperty); }
      set { SetValue(TitleProperty, value); }
    }

    public static readonly DependencyProperty TitleProperty =
        DependencyProperty.Register("Title", typeof(string), typeof(FancyButton), new FrameworkPropertyMetadata("Title", FrameworkPropertyMetadataOptions.AffectsRender));

    public string SubTitle
    {
      get { return (string)GetValue(SubTitleProperty); }
      set { SetValue(SubTitleProperty, value); }
    }

    public static readonly DependencyProperty SubTitleProperty =
        DependencyProperty.Register("SubTitle", typeof(string), typeof(FancyButton), new FrameworkPropertyMetadata("SubTitle", FrameworkPropertyMetadataOptions.AffectsRender));

    public FrameworkElement Image
    {
      get { return (FrameworkElement)GetValue(ImageProperty); }
      set { SetValue(ImageProperty, value); }
    }

    public static readonly DependencyProperty ImageProperty =
        DependencyProperty.Register("Image", typeof(FrameworkElement), typeof(FancyButton), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
  }
}

Here is how to use it:

<controls:FancyButton Grid.Row="1" HorizontalAlignment="Right" Margin="3" Title="Watch Now" SubTitle="Duration: 50 min">
  <controls:FancyButton.Image>
    <Path Data="M0,0 L30,15 L0,30Z">
      <Path.Effect>
        <DropShadowEffect Direction="50" ShadowDepth="2" />
      </Path.Effect>
      <Path.Fill>
        <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
          <GradientStop Color="#4B86B2" Offset="0" />
          <GradientStop Color="#477FA8" Offset="1" />
        </LinearGradientBrush>
      </Path.Fill>
    </Path>
  </controls:FancyButton.Image>
</controls:FancyButton>

jQuery limit to 2 decimal places

Here is a working example in both Javascript and jQuery:

http://jsfiddle.net/GuLYN/312/

//In jQuery
$("#calculate").click(function() {
    var num = parseFloat($("#textbox").val());
    var new_num = $("#textbox").val(num.toFixed(2));
});


// In javascript
document.getElementById('calculate').onclick = function() {
    var num = parseFloat(document.getElementById('textbox').value);
    var new_num = num.toFixed(2);
    document.getElementById('textbox').value = new_num;
};
?

Excel Macro : How can I get the timestamp in "yyyy-MM-dd hh:mm:ss" format?

DateTime.Now returns a value of data type Date. Date variables display dates according to the short date format and time format set on your computer.

They may be formatted as a string for display in any valid date format by the Format function as mentioned in aother answers

Format(DateTime.Now, "yyyy-MM-dd hh:mm:ss")

ORA-01036: illegal variable name/number when running query through C#

I just spent several days checking parameters because I have to pass 60 to a stored procedure. It turns out that the one of the variable names (which I load into a list and pass to the Oracle Write method I created) had a space in the name at the end. When comparing to the variables in the stored procedure they were the same, but in the editor I used to compare them, I didnt notice the extra space. Drove me crazy for the last 4 days trying everything I could find, and changing even the .net Oracle driver. Just wanted to throw that out here so it can help someone else. We tend to concentrate on the characters and ignore the spaces. . .

Why, Fatal error: Class 'PHPUnit_Framework_TestCase' not found in ...?

I was running PHPUnit tests on PHP5, and then, I needed to support PHP7 as well. This is what I did:

In composer.json:

"phpunit/phpunit": "~4.8|~5.7"

In my PHPUnit bootstrap file (in my case, /tests/bootstrap.php):

// PHPUnit 6 introduced a breaking change that
// removed PHPUnit_Framework_TestCase as a base class,
// and replaced it with \PHPUnit\Framework\TestCase
if (!class_exists('\PHPUnit_Framework_TestCase') && class_exists('\PHPUnit\Framework\TestCase'))
    class_alias('\PHPUnit\Framework\TestCase', '\PHPUnit_Framework_TestCase');

In other words, this will work for tests written originally for PHPUnit 4 or 5, but then needed to work on PHPUnit 6 as well.

How to Install Font Awesome in Laravel Mix

Try in your webpack.mix.js to add the '*'

.copy('node_modules/font-awesome/fonts/*', 'public/fonts')

Simple dynamic breadcrumb

Here is a great simple dynamic breadcrumb (tweak as needed):

    <?php 
    $docroot = "/zen/index5.php";
    $path =($_SERVER['REQUEST_URI']);
    $names = explode("/", $path); 
    $trimnames = array_slice($names, 1, -1);
    $length = count($trimnames)-1;
    $fixme = array(".php","-","myname");
    $fixes = array(""," ","My<strong>Name</strong>");
    echo '<div id="breadwrap"><ol id="breadcrumb">';
    $url = "";
    for ($i = 0; $i <= $length;$i++){
    $url .= $trimnames[$i]."/";
        if($i>0 && $i!=$length){
            echo '<li><a href="/'.$url.'">'.ucfirst(str_replace($fixme,$fixes,$trimnames[$i]) . ' ').'</a></li>';
    }
    elseif ($i == $length){
        echo '<li class="current">'.ucfirst(str_replace($fixme,$fixes,$trimnames[$i]) . ' ').'</li>';       
    }
    else{
        echo $trimnames[$i]='<li><a href='.$docroot.' id="bread-home"><span>&nbsp;</span></a></li>';
    }
}
echo '</ol>';
?>

How to set the part of the text view is clickable

more generic answer in kotlin

   fun setClickableText(view: TextView, firstSpan: String, secondSpan: String) {
    val context = view.context
    val builder = SpannableStringBuilder()
    val unClickableSpan = SpannableString(firstSpan)
    val span = SpannableString(" "+secondSpan)

    builder.append(unClickableSpan);
    val clickableSpan: ClickableSpan = object : ClickableSpan() {
        override fun onClick(textView: View) {
            val intent = Intent(context, HomeActivity::class.java)
         context.startActivity(intent)
        }

        override fun updateDrawState(ds: TextPaint) {
            super.updateDrawState(ds)
            ds.isUnderlineText = true
            ds.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.ITALIC));
        }
    }
    builder.append(span);
    builder.setSpan(clickableSpan, firstSpan.length, firstSpan.length+secondSpan.length+1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

    view.setText(builder,TextView.BufferType.SPANNABLE)
    view.setMovementMethod(LinkMovementMethod.getInstance());


}

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

Use lapply function after creating your function normally.

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

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

unlist(lapply(a,w))

CSS Cell Margin

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
table{_x000D_
border-spacing: 16px 4px;_x000D_
}_x000D_
_x000D_
 td {_x000D_
    border: 1px solid black;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<table style="width:100%">_x000D_
  <tr>_x000D_
    <td>Jill</td>_x000D_
    <td>Smith</td>  _x000D_
    <td>50</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Eve</td>_x000D_
    <td>Jackson</td>  _x000D_
    <td>94</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>John</td>_x000D_
    <td>Doe</td>  _x000D_
    <td>80</td>_x000D_
  </tr>_x000D_
</table>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Using padding is not correct way of doing it, it may change the look but it is not what you wanted. This may solve your issue.

How to save a Seaborn plot into a file

This works for me

import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline

sns.factorplot(x='holiday',data=data,kind='count',size=5,aspect=1)
plt.savefig('holiday-vs-count.png')

Simple 3x3 matrix inverse code (C++)

//Function for inverse of the input square matrix 'J' of dimension 'dim':

vector<vector<double > > inverseVec33(vector<vector<double > > J, int dim)
{
//Matrix of Minors
 vector<vector<double > > invJ(dim,vector<double > (dim));
for(int i=0; i<dim; i++)
{
    for(int j=0; j<dim; j++)
    {
        invJ[i][j] = (J[(i+1)%dim][(j+1)%dim]*J[(i+2)%dim][(j+2)%dim] -
                      J[(i+2)%dim][(j+1)%dim]*J[(i+1)%dim][(j+2)%dim]);
    }
}

//determinant of the matrix:
double detJ = 0.0;
for(int j=0; j<dim; j++)
{ detJ += J[0][j]*invJ[0][j];}

//Inverse of the given matrix.
 vector<vector<double > > invJT(dim,vector<double > (dim));
 for(int i=0; i<dim; i++)
{
    for(int j=0; j<dim; j++)
    {
        invJT[i][j] = invJ[j][i]/detJ;
    }
}

return invJT;
}

void main()
{
    //given matrix:
vector<vector<double > > Jac(3,vector<double > (3));
Jac[0][0] = 1; Jac[0][1] = 2;  Jac[0][2] = 6;
Jac[1][0] = -3; Jac[1][1] = 4;  Jac[1][2] = 3;
Jac[2][0] = 5; Jac[2][1] = 1;  Jac[2][2] = -4;`

//Inverse of the matrix Jac:
vector<vector<double > > JacI(3,vector<double > (3));
    //call function and store inverse of J as JacI:
JacI = inverseVec33(Jac,3);
}

Watching variables contents in Eclipse IDE

You can use Expressions windows: while debugging, menu window -> Show View -> Expressions, then it has place to type variables of which you need to see contents

How to use particular CSS styles based on screen size / device

Why not use @media-queries? These are designed for that exact purpose. You can also do this with jQuery, but that's a last resort in my book.

var s = document.createElement("script");

//Check if viewport is smaller than 768 pixels
if(window.innerWidth < 768) {
    s.type = "text/javascript";
    s.src = "http://www.example.com/public/assets/css1";
}else { //Else we have a larger screen
    s.type = "text/javascript";
    s.src = "http://www.example.com/public/assets/css2";
}

$(function(){
    $("head").append(s); //Inject stylesheet
})

how do I check in bash whether a file was created more than x time ago?

The find one is good but I think you can use anotherway, especially if you need to now how many seconds is the file old

date -d "now - $( stat -c "%Y" $filename ) seconds" +%s

using GNU date

Easy way to test an LDAP User's Credentials

ldapwhoami -vvv -h <hostname> -p <port> -D <binddn> -x -w <passwd>, where binddn is the DN of the person whose credentials you are authenticating.

On success (i.e., valid credentials), you get Result: Success (0). On failure, you get ldap_bind: Invalid credentials (49).

How to get multiple counts with one SQL query?

One way which works for sure

SELECT a.distributor_id,
    (SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
    (SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
    (SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
FROM (SELECT DISTINCT distributor_id FROM myTable) a ;

EDIT:
See @KevinBalmforth's break down of performance for why you likely don't want to use this method and instead should opt for @Taryn?'s answer. I'm leaving this so people can understand their options.

Can I give a default value to parameters or optional parameters in C# functions?

That is exactly how you do it in C#, but the feature was first added in .NET 4.0

PHP function to build query string from array

Implode will combine an array into a string for you, but to make an SQL query out a kay/value pair you'll have to write your own function.

webpack: Module not found: Error: Can't resolve (with relative path)

Had the same issue with module not found. Turns out I had a component import Picture from './Picture/Picture'; at the very bottom of all the imports. When I moved it below import React, { Component } from 'react';, it worked.