Programs & Examples On #Wsgiserver

Find first element in a sequence that matches a predicate

I don't think there's anything wrong with either solutions you proposed in your question.

In my own code, I would implement it like this though:

(x for x in seq if predicate(x)).next()

The syntax with () creates a generator, which is more efficient than generating all the list at once with [].

What is the height of iPhone's onscreen keyboard?

Do remember that, with iOS 8, the onscreen keyboard's size can vary. Don't assume that the onscreen keyboard will always be visible (with a specific height) or invisible.

Now, with iOS 8, the user can also swipe the text-prediction area on and off... and when they do this, it would kick off an app's keyboardWillShow event again.

This will break a lot of legacy code samples, which recommended writing a keyboardWillShow event, which merely measures the current height of the onscreen keyboard, and shifting your controls up or down on the page by this (absolute) amount.

enter image description here

In other words, if you see any sample code, which just tells you to add a keyboardWillShow event, measure the keyboard height, then resize your controls' heights by this amount, this will no longer always work.

In my example above, I used the sample code from the following site, which animates the vertical constraints constant value.

Practicing AutoLayout

In my app, I added a constraint to my UITextView, set to the bottom of the screen. When the screen first appeared, I stored this initial vertical distance.

Then, whenever my keyboardWillShow event gets kicked off, I add the (new) keyboard height to this original constraint value (so the constraint resizes the control's height).

enter image description here

Yeah. It's ugly.

And I'm a little annoyed/surprised that XCode 6's horribly-painful AutoLayout doesn't just allow us to attach the bottoms of controls to either the bottom of the screen, or the top of onscreen keyboard.

Perhaps I'm missing something.

Other than my sanity.

Best practices for SQL varchar column length

Always check with your business domain expert. If that's you, look for an industry standard. If, for example, the domain in question is a natural person's family name (surname) then for a UK business I'd go to the UK Govtalk data standards catalogue for person information and discover that a family name will be between 1 and 35 characters.

When would you use the different git merge strategies?

Actually the only two strategies you would want to choose are ours if you want to abandon changes brought by branch, but keep the branch in history, and subtree if you are merging independent project into subdirectory of superproject (like 'git-gui' in 'git' repository).

octopus merge is used automatically when merging more than two branches. resolve is here mainly for historical reasons, and for when you are hit by recursive merge strategy corner cases.

Animation CSS3: display + opacity

I had the same problem. I tried using animations instead of transitions - as suggested by @MichaelMullany and @Chris - but it only worked for webkit browsers even if I copy-pasted with "-moz" and "-o" prefixes.

I was able to get around the problem by using visibility instead of display. This works for me because my child element is position: absolute, so document flow isn't being affected. It might work for others too.

This is what the original code would look like using my solution:

.child {
    position: absolute;
    opacity: 0;
    visibility: hidden;

    -webkit-transition: opacity 0.5s ease-in-out;
    -moz-transition: opacity 0.5s ease-in-out;
    transition: opacity 0.5s ease-in-out;
}

.parent:hover .child {
    position: relative;
    opacity: 0.9;
    visibility: visible;
}

Set Culture in an ASP.Net MVC app

protected void Application_AcquireRequestState(object sender, EventArgs e)
        {
            if(Context.Session!= null)
            Thread.CurrentThread.CurrentCulture =
                    Thread.CurrentThread.CurrentUICulture = (Context.Session["culture"] ?? (Context.Session["culture"] = new CultureInfo("pt-BR"))) as CultureInfo;
        }

adding child nodes in treeview

It looks like you are only adding children to the first parent treeView2.Nodes[0].Nodes.Add(yourChildNode)
Depending on how you want it to behave, you need to be explicit about the parent node you wish to add the child to.
For Example, from your screenshot, if you wanted to add the child to the second node you would need:
treeView2.Nodes[1].Nodes.Add(yourChildNode)
If you want to add the children to the currently selected node, get the TreeView.SelectedNode and add the children to it.

Try TreeView to get an idea of how the class operates. Unfortunately the msdn documentation is pretty light on the code samples...

I'm missing a whole lot of safety checks here!

Something like (untested):

private void addChildNode_Click(object sender, EventArgs e) {
  TreeNode ParentNode = treeView2.SelectedNode;  // for ease of debugging!
  if (ParentNode != null) {
    ParentNode.Nodes.Add("Name Of Node");
    treeView2.ExpandAll();   // so you can see what's been added              
    treeView2.Invalidate();  // requests a redraw
  }
}

How to convert Javascript datetime to C# datetime?

I think you can use the TimeZoneInfo....to convert the datetime....

    static void Main(string[] args)
    {
        long time = 1310522400000;
        DateTime dt_1970 = new DateTime(1970, 1, 1);
        long tricks_1970 = dt_1970.Ticks;
        long time_tricks = tricks_1970 + time * 10000;
        DateTime dt = new DateTime(time_tricks);

        Console.WriteLine(dt.ToShortDateString()); // result : 7/13
        dt = TimeZoneInfo.ConvertTimeToUtc(dt);

        Console.WriteLine(dt.ToShortDateString());  // result : 7/12
        Console.Read();
    }

What is the difference between a token and a lexeme?

Token: The kind for (keywords,identifier,punctuation character, multi-character operators) is ,simply, a Token.

Pattern: A rule for formation of token from input characters.

Lexeme : Its a sequence of characters in SOURCE PROGRAM matched by a pattern for a token. Basically, its an element of Token.

Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

Almost all public CDNs are pretty reliably. However, if you are worried about blocked google domain, then you can simply fallback to an alternative jQuery CDN. However, in such a case, you may prefer to do it opposite way and use some other CDN as your preferred option and fallback to Google CDN to avoid failed requests and waiting time:

<script src="https://pagecdn.io/lib/jquery/3.2.1/jquery.min.js"></script>
<script>
   window.jQuery || document.write('<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"><\/script>');
</script>

How to read XML using XPath in Java

Here is an example of processing xpath with vtd-xml... for heavy duty XML processing it is second to none. here is the a recent paper on this subject Processing XML with Java – A Performance Benchmark

import com.ximpleware.*;

public class changeAttrVal {
    public  static  void main(String s[]) throws VTDException,java.io.UnsupportedEncodingException,java.io.IOException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", false))
            return;
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        XMLModifier xm = new XMLModifier(vn);
        ap.selectXPath("/*/place[@id=\"p14\" and   @initialMarking=\"2\"]/@initialMarking");
        int i=0;
        while((i=ap.evalXPath())!=-1){
            xm.updateToken(i+1, "499");// change initial marking from 2 to 499
        }
        xm.output("new.xml");
    }

}

CSS transition shorthand with multiple properties?

Syntax:

transition: <property> || <duration> || <timing-function> || <delay> [, ...];

Note that the duration must come before the delay, if the latter is specified.

Individual transitions combined in shorthand declarations:

-webkit-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
-moz-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
-o-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;

Or just transition them all:

-webkit-transition: all 0.3s ease-out;
-moz-transition: all 0.3s ease-out;
-o-transition: all 0.3s ease-out;
transition: all 0.3s ease-out;

Here is a straightforward example. Here is another one with the delay property.


Edit: previously listed here were the compatibilities and known issues regarding transition. Removed for readability.

Bottom-line: just use it. The nature of this property is non-breaking for all applications and compatibility is now well above 94% globally.

If you still want to be sure, refer to http://caniuse.com/css-transitions

A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm

Generally if something works on various computers but fails on only one computer, then there's something wrong with that computer. Here are a few things to check:
(1) Are you running the same stuff on that computer -- OS including patches, etc.
(2) Does the computer report problems? Where to look depends on the OS, but it looks like you're using linux, so check syslog
(3) Run hardware diagnostics, e.g. the ones recommended here. Start with memory and disk checks in particular.

If you can't turn up any issues, then search for a similar issue in the bug parade for whichever VM you're using. Unfortunately if you're already on the latest version of the VM, then you won't necessarily find a fix.

Finally, one more option is simply to try another VM -- e.g. OpenJDK or JRockit, instead of Oracle's standard.

Where are SQL Server connection attempts logged?

You can enable connection logging. For SQL Server 2008, you can enable Login Auditing. In SQL Server Management Studio, open SQL Server Properties > Security > Login Auditing select "Both failed and successful logins".

Make sure to restart the SQL Server service.

Once you've done that, connection attempts should be logged into SQL's error log. The physical logs location can be determined here.

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

Note that, in addition to number of predictive variables, the Adjusted R-squared formula above also adjusts for sample size. A small sample will give a deceptively large R-squared.

Ping Yin & Xitao Fan, J. of Experimental Education 69(2): 203-224, "Estimating R-squared shrinkage in multiple regression", compares different methods for adjusting r-squared and concludes that the commonly-used ones quoted above are not good. They recommend the Olkin & Pratt formula.

However, I've seen some indication that population size has a much larger effect than any of these formulas indicate. I am not convinced that any of these formulas are good enough to allow you to compare regressions done with very different sample sizes (e.g., 2,000 vs. 200,000 samples; the standard formulas would make almost no sample-size-based adjustment). I would do some cross-validation to check the r-squared on each sample.

#1292 - Incorrect date value: '0000-00-00'

You have 3 options to make your way:
1. Define a date value like '1970-01-01'
2. Select NULL from the dropdown to keep it blank.
3. Select CURRENT_TIMESTAMP to set current datetime as default value.

How to add MVC5 to Visual Studio 2013?

Select web development tools when you install the visual studio 2013. Then it will work properly and show the asp.net web applicaton.

Get the filename of a fileupload in a document through JavaScript

Using code like this in a form I can capture the original source upload filename, copy it to a second simple input field. This is so user can provide an alternate upload filename in submit request since the file upload filename is immutable.

    <input type="file" id="imgup1" name="imagefile">
      onchange="document.getElementsByName('imgfn1')[0].value = document.getElementById('imgup1').value;">
    <input type="text" name="imgfn1" value="">

RegEx for valid international mobile phone number

^\+[1-9]{1}[0-9]{7,11}$ 

The Regular Expression ^\+[1-9]{1}[0-9]{7,11}$ fails for "+290 8000" and similar valid numbers that are shorter than 8 digits.

The longest numbers could be something like 3 digit country code, 3 digit area code, 8 digit subscriber number, making 14 digits.

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

You module and class AthleteList have the same name. Change:

import AthleteList

to:

from AthleteList import AthleteList

This now means that you are importing the module object and will not be able to access any module methods you have in AthleteList

Detecting EOF in C

You want to check the result of scanf() to make sure there was a successful conversion; if there wasn't, then one of three things is true:

  1. scanf() is choking on a character that isn't valid for the %f conversion specifier (i.e., something that isn't a digit, dot, 'e', or 'E');
  2. scanf() has detected EOF;
  3. scanf() has detected an error on reading stdin.

Example:

int moreData = 1;
...
printf("Input no: ");
fflush(stdout);
/**
 * Loop while moreData is true
 */
while (moreData)
{
  errno = 0;
  int itemsRead = scanf("%f", &input);
  if (itemsRead == 1)
  {
    printf("Output: %f\n", input);
    printf("Input no: ");
    fflush(stdout);
  }
  else
  {
    if (feof(stdin))
    {
      printf("Hit EOF on stdin; exiting\n");
      moreData = 0;
    }
    else if (ferror(stdin))
    {
      /**
       * I *think* scanf() sets errno; if not, replace
       * the line below with a regular printf() and
       * a generic "read error" message.
       */
      perror("error during read");
      moreData = 0;
    }
    else
    {
      printf("Bad character stuck in input stream; clearing to end of line\n");
      while (getchar() != '\n')
        ; /* empty loop */
      printf("Input no: ");
      fflush(stdout);
    }
 }

How to get instance variables in Python?

Use vars()

class Foo(object):
    def __init__(self):
        self.a = 1
        self.b = 2

vars(Foo()) #==> {'a': 1, 'b': 2}
vars(Foo()).keys() #==> ['a', 'b']

What is the correct format to use for Date/Time in an XML file

EDIT: This is bad advice. Use "o", as above. "s" does the wrong thing.

I always use this:

dateTime.ToUniversalTime().ToString("s");

This is correct if your schema looks like this:

<xs:element name="startdate" type="xs:dateTime"/>

Which would result in:

<startdate>2002-05-30T09:00:00</startdate>

You can get more information here: http://www.w3schools.com/xml/schema_dtypes_date.asp

How to set 777 permission on a particular folder?

777 is a permission in Unix based system with full read/write/execute permission to owner, group and everyone.. in general we give this permission to assets which are not much needed to be hidden from public on a web server, for example images..

You said I am using windows 7. if that means that your web server is Windows based then you should login to that and right click the folder and set permissions to everyone and if you are on a windows client and server is unix/linux based then use some ftp software and in the parent directory right click and change the permission for the folder.

If you want permission to be set on sub-directories too then usually their is option to set permission recursively use that.

And, if you feel like doing it from command line the use putty and login to server and go to the parent directory includes and write the following command

chmod 0777 module_installation/

for recursive

chmod -R 0777 module_installation/

Hope this will help you

Disabling tab focus on form elements

If you're dealing with an input element, I found it useful to set the pointer focus to back itself.

$('input').on('keydown', function(e) { 
    if (e.keyCode == 9) {
        $(this).focus();
       e.preventDefault();
    }
});

How can I build for release/distribution on the Xcode 4?

That part is now located under Schemes. If you edit your schemes you will see that you can set the debug/release/adhoc/distribution build config for each scheme.

How do you dismiss the keyboard when editing a UITextField

You can also use

 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
  {

   [self.yourTextField resignFirstResponder];

  }

Best one if You have many Uitextfields :

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
 {    
     [self.view endEditing:YES];
 }

What causes signal 'SIGILL'?

It could be some un-initialized function pointer, in particular if you have corrupted memory (then the bogus vtable of C++ bad pointers to invalid objects might give that).

BTW gdb watchpoints & tracepoints, and also valgrind might be useful (if available) to debug such issues. Or some address sanitizer.

Getting strings recognized as variable names in R

Subsetting the data and combining them back is unnecessary. So are loops since those operations are vectorized. From your previous edit, I'm guessing you are doing all of this to make bubble plots. If that is correct, perhaps the example below will help you. If this is way off, I can just delete the answer.

library(ggplot2)
# let's look at the included dataset named trees.
# ?trees for a description
data(trees)
ggplot(trees,aes(Height,Volume)) + geom_point(aes(size=Girth))
# Great, now how do we color the bubbles by groups?
# For this example, I'll divide Volume into three groups: lo, med, high
trees$set[trees$Volume<=22.7]="lo"
trees$set[trees$Volume>22.7 & trees$Volume<=45.4]="med"
trees$set[trees$Volume>45.4]="high"

ggplot(trees,aes(Height,Volume,colour=set)) + geom_point(aes(size=Girth))


# Instead of just circles scaled by Girth, let's also change the symbol
ggplot(trees,aes(Height,Volume,colour=set)) + geom_point(aes(size=Girth,pch=set))

# Now let's choose a specific symbol for each set. Full list of symbols at ?pch
trees$symbol[trees$Volume<=22.7]=1
trees$symbol[trees$Volume>22.7 & trees$Volume<=45.4]=2
trees$symbol[trees$Volume>45.4]=3

ggplot(trees,aes(Height,Volume,colour=set)) + geom_point(aes(size=Girth,pch=symbol))

Google Maps: How to create a custom InfoWindow?

You can even append your own css class on the popup container/canvas or how do you want. Current google maps 3.7 has popups styled by canvas element which prepends popup div container in code. So at googlemaps 3.7 You can get into rendering process by popup's domready event like this:

var popup = new google.maps.InfoWindow();
google.maps.event.addListener(popup, 'domready', function() {
  if (this.content && this.content.parentNode && this.content.parentNode.parentNode) {
    if (this.content.parentNode.parentNode.previousElementSibling) {
      this.content.parentNode.parentNode.previousElementSibling.className = 'my-custom-popup-container-css-classname';
    }
  }
});

element.previousElementSibling is not present at IE8- so if you want to make it work at it, follow this.

check the latest InfoWindow reference for events and more..

I found this most clean in some cases.

How do you read CSS rule values with JavaScript?

Some browser differences to be aware of:

Given the CSS:

div#a { ... }
div#b, div#c { ... }

and given InsDel's example, classes will have 2 classes in FF and 3 classes in IE7.

My example illustrates this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <style>
    div#a { }
    div#b, div#c { }
    </style>
    <script>
    function PrintRules() {
    var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules
        for(var x=0;x<rules.length;x++) {
            document.getElementById("rules").innerHTML += rules[x].selectorText + "<br />";
        }
    }
    </script>
</head>
<body>
    <input onclick="PrintRules()" type="button" value="Print Rules" /><br />
    RULES:
    <div id="rules"></div>
</body>
</html>

How to get values of selected items in CheckBoxList with foreach in ASP.NET C#?

Good afternoon, you could always use a little LINQ to get the selected list items and then do what you want with the results:

var selected = CBLGold.Items.Cast<ListItem>().Where(x => x.Selected);
// work with selected...

CSS - Syntax to select a class within an id

This will also work and you don't need the extra class:

#navigation li li {}

If you have a third level of LI's you may have to reset/override some of the styles they will inherit from the above selector. You can target the third level like so:

#navigation li li li {}

Delete the 'first' record from a table in SQL Server, without a WHERE condition

What do you mean by «'first' record from a table» ? There's no such concept as "first record" in a relational db, i think.

Using MS SQL Server 2005, if you intend to delete the "top record" (the first one that is presented when you do a simple "*select * from tablename*"), you may use "delete top(1) from tablename"... but be aware that this does not assure which row is deleted from the recordset, as it just removes the first row that would be presented if you run the command "select top(1) from tablename".

Disable double-tap "zoom" option in browser on touch devices

If you need a version that works without jQuery, I modified Wouter Konecny's answer (which was also created by modifying this gist by Johan Sundström) to use vanilla JavaScript.

function preventZoom(e) {
  var t2 = e.timeStamp;
  var t1 = e.currentTarget.dataset.lastTouch || t2;
  var dt = t2 - t1;
  var fingers = e.touches.length;
  e.currentTarget.dataset.lastTouch = t2;

  if (!dt || dt > 500 || fingers > 1) return; // not double-tap

  e.preventDefault();
  e.target.click();
}

Then add an event handler on touchstart that calls this function:

myButton.addEventListener('touchstart', preventZoom); 

How to sort a list/tuple of lists/tuples by the element at a given index?

For sorting by multiple criteria, namely for instance by the second and third elements in a tuple, let

data = [(1,2,3),(1,2,1),(1,1,4)]

and so define a lambda that returns a tuple that describes priority, for instance

sorted(data, key=lambda tup: (tup[1],tup[2]) )
[(1, 1, 4), (1, 2, 1), (1, 2, 3)]

How can I view the shared preferences file using Android Studio?

Stetho

You can use http://facebook.github.io/stetho/ for accessing your shared preferences while your application is in the debug mode. No Root

features:

  1. view and edit sharedpreferences
  2. view and edit sqLite db
  3. view view heirarchy
  4. monitor http network requests
  5. view stream from the device's screen
  6. and more....

enter image description here

Basic setup:

  1. in the build.gradle add compile 'com.facebook.stetho:stetho:1.5.0'
  2. in the application's onCreate() add Stetho.initializeWithDefaults(this);
  3. in Chrome on your PC go to the chrome://inspect/

UPDATE: Flipper

Flipper is a newer alternative from facebook. It has more features but for the time writing is only available for Mac, slightly harder to configure and lacks data base debugging, while brining up extreamely enhanced layout inspector

You can also use @Jeffrey suggestion:

  • Open Device File Explorer (Lower Right of screen)
  • Go to data/data/com.yourAppName/shared_prefs

Change Name of Import in Java, or import two classes with the same name

There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.

Import one class and use the fully qualified name for the other one, i.e.

import com.text.Formatter;

private Formatter textFormatter;
private com.json.Formatter jsonFormatter;

Create own colormap using matplotlib and plot color scale

If you want to automate the creating of a custom divergent colormap commonly used for surface plots, this module combined with @unutbu method worked well for me.

def diverge_map(high=(0.565, 0.392, 0.173), low=(0.094, 0.310, 0.635)):
    '''
    low and high are colors that will be used for the two
    ends of the spectrum. they can be either color strings
    or rgb color tuples
    '''
    c = mcolors.ColorConverter().to_rgb
    if isinstance(low, basestring): low = c(low)
    if isinstance(high, basestring): high = c(high)
    return make_colormap([low, c('white'), 0.5, c('white'), high])

The high and low values can be either string color names or rgb tuples. This is the result using the surface plot demo: enter image description here

How do you get a string from a MemoryStream?

This sample shows how to read a string from a MemoryStream, in which I've used a serialization (using DataContractJsonSerializer), pass the string from some server to client, and then, how to recover the MemoryStream from the string passed as parameter, then, deserialize the MemoryStream.

I've used parts of different posts to perform this sample.

Hope that this helps.

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Threading;

namespace JsonSample
{
    class Program
    {
        static void Main(string[] args)
        {
            var phones = new List<Phone>
            {
                new Phone { Type = PhoneTypes.Home, Number = "28736127" },
                new Phone { Type = PhoneTypes.Movil, Number = "842736487" }
            };
            var p = new Person { Id = 1, Name = "Person 1", BirthDate = DateTime.Now, Phones = phones };

            Console.WriteLine("New object 'Person' in the server side:");
            Console.WriteLine(string.Format("Id: {0}, Name: {1}, Birthday: {2}.", p.Id, p.Name, p.BirthDate.ToShortDateString()));
            Console.WriteLine(string.Format("Phone: {0} {1}", p.Phones[0].Type.ToString(), p.Phones[0].Number));
            Console.WriteLine(string.Format("Phone: {0} {1}", p.Phones[1].Type.ToString(), p.Phones[1].Number));

            Console.Write(Environment.NewLine);
            Thread.Sleep(2000);

            var stream1 = new MemoryStream();
            var ser = new DataContractJsonSerializer(typeof(Person));

            ser.WriteObject(stream1, p);

            stream1.Position = 0;
            StreamReader sr = new StreamReader(stream1);
            Console.Write("JSON form of Person object: ");
            Console.WriteLine(sr.ReadToEnd());

            Console.Write(Environment.NewLine);
            Thread.Sleep(2000);

            var f = GetStringFromMemoryStream(stream1);

            Console.Write(Environment.NewLine);
            Thread.Sleep(2000);

            Console.WriteLine("Passing string parameter from server to client...");

            Console.Write(Environment.NewLine);
            Thread.Sleep(2000);

            var g = GetMemoryStreamFromString(f);
            g.Position = 0;
            var ser2 = new DataContractJsonSerializer(typeof(Person));
            var p2 = (Person)ser2.ReadObject(g);

            Console.Write(Environment.NewLine);
            Thread.Sleep(2000);

            Console.WriteLine("New object 'Person' arrived to the client:");
            Console.WriteLine(string.Format("Id: {0}, Name: {1}, Birthday: {2}.", p2.Id, p2.Name, p2.BirthDate.ToShortDateString()));
            Console.WriteLine(string.Format("Phone: {0} {1}", p2.Phones[0].Type.ToString(), p2.Phones[0].Number));
            Console.WriteLine(string.Format("Phone: {0} {1}", p2.Phones[1].Type.ToString(), p2.Phones[1].Number));

            Console.Read();
        }

        private static MemoryStream GetMemoryStreamFromString(string s)
        {
            var stream = new MemoryStream();
            var sw = new StreamWriter(stream);
            sw.Write(s);
            sw.Flush();
            stream.Position = 0;
            return stream;
        }

        private static string GetStringFromMemoryStream(MemoryStream ms)
        {
            ms.Position = 0;
            using (StreamReader sr = new StreamReader(ms))
            {
                return sr.ReadToEnd();
            }
        }
    }

    [DataContract]
    internal class Person
    {
        [DataMember]
        public int Id { get; set; }
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public DateTime BirthDate { get; set; }
        [DataMember]
        public List<Phone> Phones { get; set; }
    }

    [DataContract]
    internal class Phone
    {
        [DataMember]
        public PhoneTypes Type { get; set; }
        [DataMember]
        public string Number { get; set; }
    }

    internal enum PhoneTypes
    {
        Home = 1,
        Movil = 2
    }
}

Convert timestamp long to normal date format

To show leading zeros infront of hours, minutes and seconds use below modified code. The trick here is we are converting (or more accurately formatting) integer into string so that it shows leading zero whenever applicable :

public String convertTimeWithTimeZome(long time) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("UTC"));
        cal.setTimeInMillis(time);
        String curTime = String.format("%02d:%02d:%02d", cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND));
        return curTime;
    }

Result would be like : 00:01:30

Convert PDF to PNG using ImageMagick

when you set the density to 96, doesn't it look good?

when i tried it i saw that saving as jpg resulted with better quality, but larger file size

Process.start: how to get the output?

  1. It is possible to get the command line shell output of a process as described here : http://www.c-sharpcorner.com/UploadFile/edwinlima/SystemDiagnosticProcess12052005035444AM/SystemDiagnosticProcess.aspx

  2. This depends on mencoder. If it ouputs this status on the command line then yes :)

Add line break to 'git commit -m' from the command line

If you just want, say, a head line and a content line, you can use:

git commit -m "My head line" -m "My content line."

Note that this creates separate paragraphs - not lines. So there will be a blank line between each two -m lines, e.g.:

My head line

My content line.

Connecting to Postgresql in a docker container from outside

first open the docker image for the postgres

docker exec -it <container_name>

then u will get the root --root@868594e88b53:/# it need the database connection

psql postgresql://<username>:<databasepassword>@postgres:5432/<database>

How do I resize a Google Map with JavaScript after it has loaded?

First of all, thanks for guiding me and closing this issue. I found a way to fix this issue from your discussions. Yeah, Let's come to the point. The thing is I'm Using GoogleMapHelper v3 helper in CakePHP3. When i tried to open bootstrap modal popup, I got struck with the grey box issue over the map. It's been extended for 2 days. Finally i got a fix over this.

We need to Update the GoogleMapHelper to fix the issue

Need to add the below script in setCenterMap function

google.maps.event.trigger({$id}, \"resize\");

And need the include below code in JavaScript

google.maps.event.addListenerOnce({$id}, 'idle', function(){
   setCenterMap(new google.maps.LatLng({$this->defaultLatitude}, 
   {$this->defaultLongitude}));
});

Python list / sublist selection -1 weirdness

It seems pretty consistent to me; positive indices are also non-inclusive. I think you're doing it wrong. Remembering that range() is also non-inclusive, and that Python arrays are 0-indexed, here's a sample python session to illustrate:

>>> d = range(10)
>>> d
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> d[9]
9
>>> d[-1]
9
>>> d[0:9]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> d[0:-1]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> len(d)
10

How to import Google Web Font in CSS file?

<link href="https://fonts.googleapis.com/css?family=(any font of your 
choice)" rel="stylesheet" type="text/css">

To choose the font you can visit the link : https://fonts.google.com

Write the font name of your choice from the website excluding the brackets.

For example you chose Lobster as a font of your choice then,

<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" 
type="text/css">

Then you can use this normally as a font-family in your whole HTML/CSS file.

For example

<h2 style="Lobster">Please Like This Answer</h2>

How do I create a master branch in a bare Git repository?

By default there will be no branches listed and pops up only after some file is placed. You don't have to worry much about it. Just run all your commands like creating folder structures, adding/deleting files, commiting files, pushing it to server or creating branches. It works seamlessly without any issue.

https://git-scm.com/docs

T-SQL: Using a CASE in an UPDATE statement to update certain columns depending on a condition

I know this is a very old question and the problem is marked as fixed. However, if someone with a case like mine where the table have trigger for data logging on update events, this will cause problem. Both the columns will get the update and log will make useless entries. The way I did

IF (CONDITION) IS TRUE
BEGIN
    UPDATE table SET columnx = 25
END
ELSE
BEGIN
    UPDATE table SET columny = 25
END

Now this have another benefit that it does not have unnecessary writes on the table like the above solutions.

How do I start an activity from within a Fragment?

You should do it with getActivity().startActivity(myIntent)

Setting PayPal return URL and making it auto return?

on the checkout page, look for the 'cancel_return' hidden form element:

set the value of the cancel_return form element to the URL you wish to return to:

SELECT INTO USING UNION QUERY

Here's one working syntax for SQL Server 2017:

USE [<yourdb-name>]
GO

SELECT * INTO NEWTABLE 
FROM <table1-name>
UNION ALL
SELECT * FROM <table2-name>

Route.get() requires callback functions but got a "object Undefined"

(1) Make sure that you have imported the corresponding controller file in router file

(2) Make sure that the function name written in the any of the router.get() or router.post() in router.js file is exactly same as the function name written in the corresponding controller file

(3) Make sure that you have written module.exports=router; at the bottom of router.js file

How do I parse command line arguments in Java?

Maybe these

  • JArgs command line option parsing suite for Java - this tiny project provides a convenient, compact, pre-packaged and comprehensively documented suite of command line option parsers for the use of Java programmers. Initially, parsing compatible with GNU-style 'getopt' is provided.

  • ritopt, The Ultimate Options Parser for Java - Although, several command line option standards have been preposed, ritopt follows the conventions prescribed in the opt package.

fatal: does not appear to be a git repository

I was facing same issue with my one of my feature branch. I tried above mentioned solution nothing worked. I resolved this issue by doing following things.

  • git pull origin feature-branch-name
  • git push

Variable not accessible when initialized outside function

Make sure you declare the variable on "root" level, outside any code blocks.

You could also remove the var altogether, although that is not recommended and will throw a "strict" warning.

According to the documentation at MDC, you can set global variables using window.variablename.

How many bytes in a JavaScript string?

You can use the Blob to get the string size in bytes.

Examples:

_x000D_
_x000D_
console.info(_x000D_
  new Blob(['']).size,                             // 4_x000D_
  new Blob(['']).size,                             // 4_x000D_
  new Blob(['']).size,                           // 8_x000D_
  new Blob(['']).size,                           // 8_x000D_
  new Blob(['I\'m a string']).size,                  // 12_x000D_
_x000D_
  // from Premasagar correction of Lauri's answer for_x000D_
  // strings containing lone characters in the surrogate pair range:_x000D_
  // https://stackoverflow.com/a/39488643/6225838_x000D_
  new Blob([String.fromCharCode(55555)]).size,       // 3_x000D_
  new Blob([String.fromCharCode(55555, 57000)]).size // 4 (not 6)_x000D_
);
_x000D_
_x000D_
_x000D_

Add inline style using Javascript

Using jQuery :

$(nFilter).attr("style","whatever");

Otherwise :

nFilter.setAttribute("style", "whatever");

should work

check if a file is open in Python

if myfile.closed == False:
   print("File is still open ################")

How do I clear a C++ array?

Hey i think The fastest way to handle that kind of operation is to memset() the memory.

Example-

memset(&myPage.pageArray[0][0], 0, sizeof(myPage.pageArray));

A similar C++ way would be to use std::fill

char *begin = myPage.pageArray[0][0];
char *end = begin + sizeof(myPage.pageArray);
std::fill(begin, end, 0);

How would I stop a while loop after n amount of time?

Try this module: http://pypi.python.org/pypi/interruptingcow/

from interruptingcow import timeout
try:
    with timeout(60*5, exception=RuntimeError):
        while True:
            test = 0
            if test == 5:
                break
            test = test - 1
except RuntimeError:
    pass

Disabling swap files creation in vim

Set the following variables in .vimrc or /etc/vimrc to make vim put swap, backup and undo files in a special location instead of the working directory of the file being edited:

set backupdir=~/.vim/backup//
set directory=~/.vim/swap//
set undodir=~/.vim/undo//

Using double trailing slashes in the path tells vim to enable a feature where it avoids name collisions. For example, if you edit a file in one location and another file in another location and both files have the same name, you don't want a name collision to occur in ~/.vim/swap/. If you specify ~/.vim/swap// with two trailing slashes vim will create swap files using the whole path of the files being edited to avoid collisions (slashes in the file's path will be replaced by percent symbol %).

For example, if you edit /path/one/foobar.txt and /path/two/foobar.txt, then you will see two swap files in ~/.vim/swap/ that are named %path%one%foobar.txt and %path%two%foobar.txt, respectively.

Using CRON jobs to visit url?

You can also use the local commandline php-cli:

* * * * * php /local/root/path/to/tasks.php > /dev/null

It is faster and decrease load for your webserver.

JSON Structure for List of Objects

The second is almost correct:

{
    "foos" : [{
        "prop1":"value1",
        "prop2":"value2"
    }, {
        "prop1":"value3", 
        "prop2":"value4"
    }]
}

Close popup window

An old tip...

var daddy = window.self;
daddy.opener = window.self;
daddy.close();

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.


If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.


It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

How to Consume WCF Service with Android

You will need something more that a http request to interact with a WCF service UNLESS your WCF service has a REST interface. Either look for a SOAP web service API that runs on android or make your service RESTful. You will need .NET 3.5 SP1 to do WCF REST services:

http://msdn.microsoft.com/en-us/netframework/dd547388.aspx

How to set the margin or padding as percentage of height of parent container?

Here are two options to emulate the needed behavior. Not a general solution, but may help in some cases. The vertical spacing here is calculated on the basis of the size of the outer element, not its parent, but this size itself can be relative to the parent and this way the spacing will be relative too.

<div id="outer">
    <div id="inner">
        content
    </div>
</div>

First option: use pseudo-elements, here vertical and horizontal spacing are relative to the outer. Demo

#outer::before, #outer::after {
    display: block;
    content: "";
    height: 10%;
}
#inner {
    height: 80%;
    margin-left: 10%;
    margin-right: 10%;
}

Moving the horizontal spacing to the outer element makes it relative to the parent of the outer. Demo

#outer {
    padding-left: 10%;
    padding-right: 10%;
}

Second option: use absolute positioning. Demo

#outer {
    position: relative;
}
#inner {
    position: absolute;
    left: 10%;
    right: 10%;
    top: 10%;
    bottom: 10%;
}

PHP header() redirect with POST variables

It is not possible to redirect a POST somewhere else. When you have POSTED the request, the browser will get a response from the server and then the POST is done. Everything after that is a new request. When you specify a location header in there the browser will always use the GET method to fetch the next page.

You could use some Ajax to submit the form in background. That way your form values stay intact. If the server accepts, you can still redirect to some other page. If the server does not accept, then you can display an error message, let the user correct the input and send it again.

Python: fastest way to create a list of n lists

The probably only way which is marginally faster than

d = [[] for x in xrange(n)]

is

from itertools import repeat
d = [[] for i in repeat(None, n)]

It does not have to create a new int object in every iteration and is about 15 % faster on my machine.

Edit: Using NumPy, you can avoid the Python loop using

d = numpy.empty((n, 0)).tolist()

but this is actually 2.5 times slower than the list comprehension.

List tables in a PostgreSQL schema

In all schemas:

=> \dt *.*

In a particular schema:

=> \dt public.*

It is possible to use regular expressions with some restrictions

\dt (public|s).(s|t)
       List of relations
 Schema | Name | Type  | Owner 
--------+------+-------+-------
 public | s    | table | cpn
 public | t    | table | cpn
 s      | t    | table | cpn

Advanced users can use regular-expression notations such as character classes, for example [0-9] to match any digit. All regular expression special characters work as specified in Section 9.7.3, except for . which is taken as a separator as mentioned above, * which is translated to the regular-expression notation .*, ? which is translated to ., and $ which is matched literally. You can emulate these pattern characters at need by writing ? for ., (R+|) for R*, or (R|) for R?. $ is not needed as a regular-expression character since the pattern must match the whole name, unlike the usual interpretation of regular expressions (in other words, $ is automatically appended to your pattern). Write * at the beginning and/or end if you don't wish the pattern to be anchored. Note that within double quotes, all regular expression special characters lose their special meanings and are matched literally. Also, the regular expression special characters are matched literally in operator name patterns (i.e., the argument of \do).

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

What I did was to create an extension to UITextField and added a Designer editable property. Setting this property to any color would change the border (bottom) to that color (setting other borders to none).

Since this also requires to change the place holder text color, I also added that to the extension.

    extension UITextField {

    @IBInspectable var placeHolderColor: UIColor? {
        get {
            return self.placeHolderColor
        }
        set {
            self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: newValue!])
        }
    }


    @IBInspectable var bottomBorderColor: UIColor? {
        get {
            return self.bottomBorderColor
        }
        set {
            self.borderStyle = UITextBorderStyle.None;
            let border = CALayer()
            let width = CGFloat(0.5)
            border.borderColor = newValue?.CGColor
            border.frame = CGRect(x: 0, y: self.frame.size.height - width,   width:  self.frame.size.width, height: self.frame.size.height)

            border.borderWidth = width
            self.layer.addSublayer(border)
            self.layer.masksToBounds = true

        }
    }
}

Is it possible to run selenium (Firefox) web driver without a GUI?

If you want headless browser support then there is another approach you might adopt.

https://github.com/detro/ghostdriver

It was announced during Selenium Conference and it is still in development. It uses PhantomJS as the browser and is much better than HTMLUnitDriver, there are no screenshots yet, but as it is still in active development.

Conda command is not recognized on Windows 10

Even I got the same problem when I've first installed Anaconda. It said 'conda' command not found.

So I've just setup two values[added two new paths of Anaconda] system environment variables in the PATH variable which are: C:\Users\mshas\Anaconda2\ & C:\Users\mshas\Anaconda2\Scripts

Lot of people forgot to add the second variable which is "Scripts" just add that then 'conda' command works.

How to create empty data frame with column names specified in R?

Perhaps:

> data.frame(aname=NA, bname=NA)[numeric(0), ]
[1] aname bname
<0 rows> (or 0-length row.names)

IF EXISTS condition not working with PLSQL

IF EXISTS() is semantically incorrect. EXISTS condition can be used only inside a SQL statement. So you might rewrite your pl/sql block as follows:

declare
  l_exst number(1);
begin
  select case 
           when exists(select ce.s_regno 
                         from courseoffering co
                         join co_enrolment ce
                           on ce.co_id = co.co_id
                        where ce.s_regno=403 
                          and ce.coe_completionstatus = 'C' 
                          and ce.c_id = 803
                          and rownum = 1
                        )
           then 1
           else 0
         end  into l_exst
  from dual;

  if l_exst = 1 
  then
    DBMS_OUTPUT.put_line('YES YOU CAN');
  else
    DBMS_OUTPUT.put_line('YOU CANNOT'); 
  end if;
end;

Or you can simply use count function do determine the number of rows returned by the query, and rownum=1 predicate - you only need to know if a record exists:

declare
  l_exst number;
begin
   select count(*) 
     into l_exst
     from courseoffering co
          join co_enrolment ce
            on ce.co_id = co.co_id
    where ce.s_regno=403 
      and ce.coe_completionstatus = 'C' 
      and ce.c_id = 803
      and rownum = 1;

  if l_exst = 0
  then
    DBMS_OUTPUT.put_line('YOU CANNOT');
  else
    DBMS_OUTPUT.put_line('YES YOU CAN');
  end if;
end;

what does "error : a nonstatic member reference must be relative to a specific object" mean?

Only static functions are called with class name.

classname::Staicfunction();

Non static functions have to be called using objects.

classname obj;
obj.Somefunction();

This is exactly what your error means. Since your function is non static you have to use a object reference to invoke it.

How can get the text of a div tag using only javascript (no jQuery)

You can use innerHTML(then parse text from HTML) or use innerText.

let textContentWithHTMLTags = document.querySelector('div').innerHTML; 
let textContent = document.querySelector('div').innerText;

console.log(textContentWithHTMLTags, textContent);

innerHTML and innerText is supported by all browser(except FireFox < 44) including IE6.

Getting an error "fopen': This function or variable may be unsafe." when compling

This is not an error, it is a warning from your Microsoft compiler.

Select your project and click "Properties" in the context menu.

In the dialog, chose Configuration Properties -> C/C++ -> Preprocessor

In the field PreprocessorDefinitions add ;_CRT_SECURE_NO_WARNINGS to turn those warnings off.

Disable pasting text into HTML form

I recently had to begrudgingly disable pasting in a form element. To do so, I wrote a cross-browser* implementation of Internet Explorer's (and others') onpaste event handler. My solution had to be independent of any third-party JavaScript libraries.

Here's what I came up with. It doesn't completely disable pasting (the user can paste a single character at a time, for example), but it meets my needs and avoids having to deal with keyCodes, etc.

// Register onpaste on inputs and textareas in browsers that don't
// natively support it.
(function () {
    var onload = window.onload;

    window.onload = function () {
        if (typeof onload == "function") {
            onload.apply(this, arguments);
        }

        var fields = [];
        var inputs = document.getElementsByTagName("input");
        var textareas = document.getElementsByTagName("textarea");

        for (var i = 0; i < inputs.length; i++) {
            fields.push(inputs[i]);
        }

        for (var i = 0; i < textareas.length; i++) {
            fields.push(textareas[i]);
        }

        for (var i = 0; i < fields.length; i++) {
            var field = fields[i];

            if (typeof field.onpaste != "function" && !!field.getAttribute("onpaste")) {
                field.onpaste = eval("(function () { " + field.getAttribute("onpaste") + " })");
            }

            if (typeof field.onpaste == "function") {
                var oninput = field.oninput;

                field.oninput = function () {
                    if (typeof oninput == "function") {
                        oninput.apply(this, arguments);
                    }

                    if (typeof this.previousValue == "undefined") {
                        this.previousValue = this.value;
                    }

                    var pasted = (Math.abs(this.previousValue.length - this.value.length) > 1 && this.value != "");

                    if (pasted && !this.onpaste.apply(this, arguments)) {
                        this.value = this.previousValue;
                    }

                    this.previousValue = this.value;
                };

                if (field.addEventListener) {
                    field.addEventListener("input", field.oninput, false);
                } else if (field.attachEvent) {
                    field.attachEvent("oninput", field.oninput);
                }
            }
        }
    }
})();

To make use of this in order to disable pasting:

<input type="text" onpaste="return false;" />

* I know oninput isn't part of the W3C DOM spec, but all of the browsers I've tested this code with—Chrome 2, Safari 4, Firefox 3, Opera 10, IE6, IE7—support either oninput or onpaste. Out of all these browsers, only Opera doesn't support onpaste, but it does support oninput.

Note: This won't work on a console or other system that uses an on-screen keyboard (assuming the on-screen keyboard doesn't send keys to the browser when each key is selected). If it's possible your page/app could be used by someone with an on-screen keyboard and Opera (e.g.: Nintendo Wii, some mobile phones), don't use this script unless you've tested to make sure the on-screen keyboard sends keys to the browser after each key selection.

Positioning background image, adding padding

first off, to be a bit of a henpeck, its best NOT to use just the <background> tag. rather, use the proper, more specific, <background-image> tag.

the only way that i'm aware of to do such a thing is to build the padding into the image by extending the matte. since the empty pixels aren't stripped, you have your padding right there. so if you need a 10px border, create 10px of empty pixels all around your image. this is mui simple in Photoshop, Fireworks, GIMP, &c.

i'd also recommend trying out the PNG8 format instead of the dying GIF... much better.

there may be an alternate solution to your problem if we knew a bit more of how you're using it. :) it LOOKS like you're trying to add an accordion button. this would be best placed in the HTML because then you can target it with JavaScript/PHP; something you cannot do if it's in the background (at least not simply). in such a case, you can style the heck out of the image you currently have in CSS by using the following:

#hello img { padding: 10px; }

WR!

How to round up with excel VBA round()?

Used the function "RDown" and "RUp" from ShamBhagwat and created another function that will return the round part (without the need to give "digits" for input)

Function RoundDown(a As Double, digits As Integer) As Double
    RoundDown = Int((a + (1 / (10 ^ (digits + 1)))) * (10 ^ digits)) / (10 ^ digits)
End Function

Function RoundUp(a As Double, digits As Integer) As Double
    RoundUp = RoundDown(a + (5 / (10 ^ (digits + 1))), digits)
End Function

Function RDownAuto(a As Double) As Double
    Dim i As Integer
    For i = 0 To 17
        If Abs(a * 10) > WorksheetFunction.Power(10, -(i - 1)) Then
            If a > 0 Then
                RDownAuto = RoundDown(a, i)
            Else
                RDownAuto = RoundUp(a, i)
            End If
        Exit Function
        End If
    Next
End Function

the output will be:

RDownAuto(458.067)=458
RDownAuto(10.11)=10
RDownAuto(0.85)=0.8
RDownAuto(0.0052)=0.005
RDownAuto(-458.067)=-458
RDownAuto(-10.11)=-10
RDownAuto(-0.85)=-0.8
RDownAuto(-0.0052)=-0.005

JOIN two SELECT statement results

SELECT t1.ks, t1.[# Tasks], COALESCE(t2.[# Late], 0) AS [# Late]
FROM 
    (SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks) t1
LEFT JOIN
    (SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks) t2
ON (t1.ks = t2.ks);

Print a div using javascript in angularJS single page application

Two conditional functions are needed: one for Google Chrome, and a second for the remaining browsers.

$scope.printDiv = function (divName) {

    var printContents = document.getElementById(divName).innerHTML; 

    if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
        var popupWin = window.open('', '_blank', 'width=600,height=600,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
        popupWin.window.focus();
        popupWin.document.write('<!DOCTYPE html><html><head>' +
            '<link rel="stylesheet" type="text/css" href="style.css" />' +
            '</head><body onload="window.print()"><div class="reward-body">' + printContents + '</div></body></html>');
        popupWin.onbeforeunload = function (event) {
            popupWin.close();
            return '.\n';
        };
        popupWin.onabort = function (event) {
            popupWin.document.close();
            popupWin.close();
        }
    } else {
        var popupWin = window.open('', '_blank', 'width=800,height=600');
        popupWin.document.open();
        popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
        popupWin.document.close();
    }
    popupWin.document.close();

    return true;
}

Which Architecture patterns are used on Android?

enter image description here

When i reach this post it really help me to understand patterns with example so i have make below table to clearly see the Design patterns & their example in Android Framework

I hope you will find it helpful.

Non-static method requires a target

All the answers are pointing to a Lambda expression with an NRE (Null Reference Exception). I have found that it also occurs when using Linq to Entities. I thought it would be helpful to point out that this exception is not limited to just an NRE inside a Lambda expression.

SQL Server 2008 - Case / If statements in SELECT Clause

You are looking for the CASE statement

http://msdn.microsoft.com/en-us/library/ms181765.aspx

Example copied from MSDN:

USE AdventureWorks;
GO
SELECT   ProductNumber, Category =
      CASE ProductLine
         WHEN 'R' THEN 'Road'
         WHEN 'M' THEN 'Mountain'
         WHEN 'T' THEN 'Touring'
         WHEN 'S' THEN 'Other sale items'
         ELSE 'Not for sale'
      END,
   Name
FROM Production.Product
ORDER BY ProductNumber;
GO

Html.HiddenFor value property not getting set

Keep in mind the second parameter to @Html.HiddenFor will only be used to set the value when it can't find route or model data matching the field. Darin is correct, use view model.

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

In my case it was just a matter of:

Tools -> NuGet Package Manager -> Package Manager Settings -> Clear Cache

The problem was caused when I remapped a TFS folder.

Deserialize a json string to an object in python

Another way is to simply pass the json string as a dict to the constructor of your object. For example your object is:

class Payload(object):
    def __init__(self, action, method, data, *args, **kwargs):
        self.action = action
        self.method = method
        self.data = data

And the following two lines of python code will construct it:

j = json.loads(yourJsonString)
payload = Payload(**j)

Basically, we first create a generic json object from the json string. Then, we pass the generic json object as a dict to the constructor of the Payload class. The constructor of Payload class interprets the dict as keyword arguments and sets all the appropriate fields.

Xcode iOS 8 Keyboard types not supported

There is no "Numeric Keypad" for iPads out of the box. When you specify one iPads display the normal keypad with the numeric part displayed. You can switch over to alpha characters, etc. If you want to display a numbers only keyboard for iPad you must implement it yourself.

See here: Number keyboard in iPad?

How to remove the querystring and get only the url?

Try this:

$urrl=$_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME']

or

$urrl=$_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']

How to make a progress bar

If you are using HTML5 its better to make use of <progress> tag which was newly introduced.

<progress value="22" max="100"></progress>

Or create a progress bar of your own.

Example written in sencha

if (!this.popup) {
            this.popup = new Ext.Panel({
            floating: true,
            modal: false,
            // centered:true,
            style:'background:black;opacity:0.6;margin-top:330px;',
            width: '100%',
            height: '20%',
            styleHtmlContent: true,
            html: '<p align="center" style="color:#FFFFFF;font-size:12px">Downloading Data<hr noshade="noshade"size="7" style="color:#FFFFFF"></p>',

            });
}
this.popup.show('pop');

Get list of data-* attributes using javascript / jQuery

Have a look here:

If the browser also supports the HTML5 JavaScript API, you should be able to get the data with:

var attributes = element.dataset

or

var cat = element.dataset.cat

Oh, but I also read:

Unfortunately, the new dataset property has not yet been implemented in any browser, so in the meantime it’s best to use getAttribute and setAttribute as demonstrated earlier.

It is from May 2010.


If you use jQuery anyway, you might want to have a look at the customdata plugin. I have no experience with it though.

Byte and char conversion in Java

A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b the value you get is 2^16 - 56 or 65536 - 56.

Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8 using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8 when casting to a char, which translates to the positive number 65480.

From the language specification:

5.1.4. Widening and Narrowing Primitive Conversion

First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).


To get the right point use char c = (char) (b & 0xFF) which first converts the byte value of b to the positive integer 200 by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8 becomes 0x000000C8 or the positive number 200 in decimals.


Above is a direct explanation of what happens during conversion between the byte, int and char primitive types.

If you want to encode/decode characters from bytes, use Charset, CharsetEncoder, CharsetDecoder or one of the convenience methods such as new String(byte[] bytes, Charset charset) or String#toBytes(Charset charset). You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets.

Practical uses for AtomicInteger

The absolute simplest example I can think of is to make incrementing an atomic operation.

With standard ints:

private volatile int counter;

public int getNextUniqueIndex() {
    return counter++; // Not atomic, multiple threads could get the same result
}

With AtomicInteger:

private AtomicInteger counter;

public int getNextUniqueIndex() {
    return counter.getAndIncrement();
}

The latter is a very simple way to perform simple mutations effects (especially counting, or unique-indexing), without having to resort to synchronizing all access.

More complex synchronization-free logic can be employed by using compareAndSet() as a type of optimistic locking - get the current value, compute result based on this, set this result iff value is still the input used to do the calculation, else start again - but the counting examples are very useful, and I'll often use AtomicIntegers for counting and VM-wide unique generators if there's any hint of multiple threads being involved, because they're so easy to work with I'd almost consider it premature optimisation to use plain ints.

While you can almost always achieve the same synchronization guarantees with ints and appropriate synchronized declarations, the beauty of AtomicInteger is that the thread-safety is built into the actual object itself, rather than you needing to worry about the possible interleavings, and monitors held, of every method that happens to access the int value. It's much harder to accidentally violate threadsafety when calling getAndIncrement() than when returning i++ and remembering (or not) to acquire the correct set of monitors beforehand.

Getting the absolute path of the executable, using C#?

MSDN has an article that says to use System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase; if you need the directory, use System.IO.Path.GetDirectoryName on that result.

Or, there's the shorter Application.ExecutablePath which "Gets the path for the executable file that started the application, including the executable name" so that might mean it's slightly less reliable depending on how the application was launched.

Printing Mongo query output to a file while in the mongo shell

There are ways to do this without having to quit the CLI and pipe mongo output to a non-tty.

To save the output from a query with result x we can do the following to directly store the json output to /tmp/x.json:

> EDITOR="cat > /tmp/x.json"
> x = db.MyCollection.find(...).toArray()
> edit x
>

Note that the output isn't strictly Json but rather the dialect that Mongo uses.

Check if a number has a decimal place/is a whole number

convert number string to array, split by decimal point. Then, if the array has only one value, that means no decimal in string.

if(!number.split(".")[1]){
    //do stuff
}

This way you can also know what the integer and decimal actually are. a more advanced example would be.

number_to_array = string.split(".");
inte = number_to_array[0];
dece = number_to_array[1]; 

if(!dece){
    //do stuff
}

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

Given a column of numbers:

lst = []
cols = ['A']
for a in range(100, 105):
    lst.append([a])
df = pd.DataFrame(lst, columns=cols, index=range(5))
df

    A
0   100
1   101
2   102
3   103
4   104

You can reference the previous row with shift:

df['Change'] = df.A - df.A.shift(1)
df

    A   Change
0   100 NaN
1   101 1.0
2   102 1.0
3   103 1.0
4   104 1.0

How do I check if a Sql server string is null or empty

[Column_name] IS NULL OR LEN(RTRIM(LTRIM([Column_name]))) = 0

Enable/Disable a dropdownbox in jquery

$(document).ready(function() {
 $('#chkdwn2').click(function() {
   if ($('#chkdwn2').prop('checked')) {
      $('#dropdown').prop('disabled', true);
   } else {
      $('#dropdown').prop('disabled', false);  
   }
 });
});

making use of .prop in the if statement.

onclick on a image to navigate to another page using Javascript

maybe this is what u want?

<a href="#" id="bottle" onclick="document.location=this.id+'.html';return false;" >
    <img src="../images/bottle.jpg" alt="bottle" class="thumbnails" />
</a>

edit: keep in mind that anyone who does not have javascript enabled will not be able to navaigate to the image page....

How do I use arrays in C++?

Programmers often confuse multidimensional arrays with arrays of pointers.

Multidimensional arrays

Most programmers are familiar with named multidimensional arrays, but many are unaware of the fact that multidimensional array can also be created anonymously. Multidimensional arrays are often referred to as "arrays of arrays" or "true multidimensional arrays".

Named multidimensional arrays

When using named multidimensional arrays, all dimensions must be known at compile time:

int H = read_int();
int W = read_int();

int connect_four[6][7];   // okay

int connect_four[H][7];   // ISO C++ forbids variable length array
int connect_four[6][W];   // ISO C++ forbids variable length array
int connect_four[H][W];   // ISO C++ forbids variable length array

This is how a named multidimensional array looks like in memory:

              +---+---+---+---+---+---+---+
connect_four: |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+

Note that 2D grids such as the above are merely helpful visualizations. From the point of view of C++, memory is a "flat" sequence of bytes. The elements of a multidimensional array are stored in row-major order. That is, connect_four[0][6] and connect_four[1][0] are neighbors in memory. In fact, connect_four[0][7] and connect_four[1][0] denote the same element! This means that you can take multi-dimensional arrays and treat them as large, one-dimensional arrays:

int* p = &connect_four[0][0];
int* q = p + 42;
some_int_sequence_algorithm(p, q);

Anonymous multidimensional arrays

With anonymous multidimensional arrays, all dimensions except the first must be known at compile time:

int (*p)[7] = new int[6][7];   // okay
int (*p)[7] = new int[H][7];   // okay

int (*p)[W] = new int[6][W];   // ISO C++ forbids variable length array
int (*p)[W] = new int[H][W];   // ISO C++ forbids variable length array

This is how an anonymous multidimensional array looks like in memory:

              +---+---+---+---+---+---+---+
        +---> |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |
      +-|-+
   p: | | |
      +---+

Note that the array itself is still allocated as a single block in memory.

Arrays of pointers

You can overcome the restriction of fixed width by introducing another level of indirection.

Named arrays of pointers

Here is a named array of five pointers which are initialized with anonymous arrays of different lengths:

int* triangle[5];
for (int i = 0; i < 5; ++i)
{
    triangle[i] = new int[5 - i];
}

// ...

for (int i = 0; i < 5; ++i)
{
    delete[] triangle[i];
}

And here is how it looks like in memory:

          +---+---+---+---+---+
          |   |   |   |   |   |
          +---+---+---+---+---+
            ^
            | +---+---+---+---+
            | |   |   |   |   |
            | +---+---+---+---+
            |   ^
            |   | +---+---+---+
            |   | |   |   |   |
            |   | +---+---+---+
            |   |   ^
            |   |   | +---+---+
            |   |   | |   |   |
            |   |   | +---+---+
            |   |   |   ^
            |   |   |   | +---+
            |   |   |   | |   |
            |   |   |   | +---+
            |   |   |   |   ^
            |   |   |   |   |
            |   |   |   |   |
          +-|-+-|-+-|-+-|-+-|-+
triangle: | | | | | | | | | | |
          +---+---+---+---+---+

Since each line is allocated individually now, viewing 2D arrays as 1D arrays does not work anymore.

Anonymous arrays of pointers

Here is an anonymous array of 5 (or any other number of) pointers which are initialized with anonymous arrays of different lengths:

int n = calculate_five();   // or any other number
int** p = new int*[n];
for (int i = 0; i < n; ++i)
{
    p[i] = new int[n - i];
}

// ...

for (int i = 0; i < n; ++i)
{
    delete[] p[i];
}
delete[] p;   // note the extra delete[] !

And here is how it looks like in memory:

          +---+---+---+---+---+
          |   |   |   |   |   |
          +---+---+---+---+---+
            ^
            | +---+---+---+---+
            | |   |   |   |   |
            | +---+---+---+---+
            |   ^
            |   | +---+---+---+
            |   | |   |   |   |
            |   | +---+---+---+
            |   |   ^
            |   |   | +---+---+
            |   |   | |   |   |
            |   |   | +---+---+
            |   |   |   ^
            |   |   |   | +---+
            |   |   |   | |   |
            |   |   |   | +---+
            |   |   |   |   ^
            |   |   |   |   |
            |   |   |   |   |
          +-|-+-|-+-|-+-|-+-|-+
          | | | | | | | | | | |
          +---+---+---+---+---+
            ^
            |
            |
          +-|-+
       p: | | |
          +---+

Conversions

Array-to-pointer decay naturally extends to arrays of arrays and arrays of pointers:

int array_of_arrays[6][7];
int (*pointer_to_array)[7] = array_of_arrays;

int* array_of_pointers[6];
int** pointer_to_pointer = array_of_pointers;

However, there is no implicit conversion from T[h][w] to T**. If such an implicit conversion did exist, the result would be a pointer to the first element of an array of h pointers to T (each pointing to the first element of a line in the original 2D array), but that pointer array does not exist anywhere in memory yet. If you want such a conversion, you must create and fill the required pointer array manually:

int connect_four[6][7];

int** p = new int*[6];
for (int i = 0; i < 6; ++i)
{
    p[i] = connect_four[i];
}

// ...

delete[] p;

Note that this generates a view of the original multidimensional array. If you need a copy instead, you must create extra arrays and copy the data yourself:

int connect_four[6][7];

int** p = new int*[6];
for (int i = 0; i < 6; ++i)
{
    p[i] = new int[7];
    std::copy(connect_four[i], connect_four[i + 1], p[i]);
}

// ...

for (int i = 0; i < 6; ++i)
{
    delete[] p[i];
}
delete[] p;

Allow scroll but hide scrollbar

I know this is an oldie but here is a quick way to hide the scroll bar with pure CSS.

Just add

::-webkit-scrollbar {display:none;}

To your id or class of the div you're using the scroll bar with.

Here is a helpful link Custom Scroll Bar in Webkit

How to get difference between two dates in Year/Month/Week/Day?

DateTime dt1 = new DateTime(2009, 3, 14);
DateTime dt2 = new DateTime(2008, 3, 15);

int diffMonth = Math.Abs((dt2.Year - dt1.Year)*12 + dt1.Month - dt2.Month)

Killing a process using Java

On Windows, you could use this command.

taskkill /F /IM <processname>.exe 

To kill it forcefully, you may use;

Runtime.getRuntime().exec("taskkill /F /IM <processname>.exe")

Create a new database with MySQL Workbench

In MySQL Work bench 6.0 CE.

  1. You launch MySQL Workbench.
  2. From Menu Bar click on Database and then select "Connect to Database"
  3. It by default showing you default settings other wise you choose you host name, user name and password. and click to ok.
  4. As in above define that you should click write on existing database but if you don't have existing new database then you may choose the option from the icon menu that is provided on below the menu bar. Now keep the name as you want and enjoy ....

What is the difference between a definition and a declaration?

There are interesting edge cases in C++ (some of them in C too). Consider

T t;

That can be a definition or a declaration, depending on what type T is:

typedef void T();
T t; // declaration of function "t"

struct X { 
  T t; // declaration of function "t".
};

typedef int T;
T t; // definition of object "t".

In C++, when using templates, there is another edge case.

template <typename T>
struct X { 
  static int member; // declaration
};

template<typename T>
int X<T>::member; // definition

template<>
int X<bool>::member; // declaration!

The last declaration was not a definition. It's the declaration of an explicit specialization of the static member of X<bool>. It tells the compiler: "If it comes to instantiating X<bool>::member, then don't instantiate the definition of the member from the primary template, but use the definition found elsewhere". To make it a definition, you have to supply an initializer

template<>
int X<bool>::member = 1; // definition, belongs into a .cpp file.

How do I put a clear button inside my HTML text input box like the iPhone does?

I got a creative solution I think you are looking for

_x000D_
_x000D_
$('#clear').click(function() {_x000D_
  $('#input-outer input').val('');_x000D_
});
_x000D_
body {_x000D_
  font-family: "Tahoma";_x000D_
}_x000D_
#input-outer {_x000D_
  height: 2em;_x000D_
  width: 15em;_x000D_
  border: 1px #e7e7e7 solid;_x000D_
  border-radius: 20px;_x000D_
}_x000D_
#input-outer input {_x000D_
  height: 2em;_x000D_
  width: 80%;_x000D_
  border: 0px;_x000D_
  outline: none;_x000D_
  margin: 0 0 0 10px;_x000D_
  border-radius: 20px;_x000D_
  color: #666;_x000D_
}_x000D_
#clear {_x000D_
  position: relative;_x000D_
  float: right;_x000D_
  height: 20px;_x000D_
  width: 20px;_x000D_
  top: 5px;_x000D_
  right: 5px;_x000D_
  border-radius: 20px;_x000D_
  background: #f1f1f1;_x000D_
  color: white;_x000D_
  font-weight: bold;_x000D_
  text-align: center;_x000D_
  cursor: pointer;_x000D_
}_x000D_
#clear:hover {_x000D_
  background: #ccc;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="input-outer">_x000D_
  <input type="text">_x000D_
  <div id="clear">_x000D_
    X_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

https://jsfiddle.net/qdesign/xn9eogmx/1/

Use Font Awesome Icons in CSS

To use font awesome using css follow below steps -

step 1 - Add Fonts of FontAwesome in CSS

/*Font Awesome Fonts*/
@font-face {
    font-family: 'FontAwesome';
    //in url add your folder path of FontAwsome Fonts
    src: url('font-awesome/fontawesome-webfont.ttf') format('truetype');
}

Step - 2 Use below css to apply font on class element of HTML

.sorting_asc:after {
    content: "\f0de"; /* this is your text. You can also use UTF-8 character codes as I do here */
    font-family: FontAwesome;
    padding-left: 10px !important;
    vertical-align: middle;
}

And finally, use "sorting_asc" class to apply the css on desired HTML tag/element.

What is the difference between String.slice and String.substring?

The one answer is fine but requires a little reading into. Especially with the new terminology "stop".

My Go -- organized by differences to make it useful in addition to the first answer by Daniel above:

1) negative indexes. Substring requires positive indexes and will set a negative index to 0. Slice's negative index means the position from the end of the string.

"1234".substring(-2, -1) == "1234".substring(0,0) == ""
"1234".slice(-2, -1) == "1234".slice(2, 3) == "3"

2) Swapping of indexes. Substring will reorder the indexes to make the first index less than or equal to the second index.

"1234".substring(3,2) == "1234".substring(2,3) == "3"
"1234".slice(3,2) == ""

--------------------------

General comment -- I find it weird that the second index is the position after the last character of the slice or substring. I would expect "1234".slice(2,2) to return "3". This makes Andy's confusion above justified -- I would expect "1234".slice(2, -1) to return "34". Yes, this means I'm new to Javascript. This means also this behavior:

"1234".slice(-2, -2) == "", "1234".slice(-2, -1) == "3", "1234".slice(-2, -0) == "" <-- you have to use length or omit the argument to get the 4.
"1234".slice(3, -2) == "", "1234".slice(3, -1) == "", "1234".slice(3, -0) == "" <-- same issue, but seems weirder.

My 2c.

Check if a path represents a file or a folder

There is no way for the system to tell you if a String represent a file or directory, if it does not exist in the file system. For example:

Path path = Paths.get("/some/path/to/dir");
System.out.println(Files.isDirectory(path)); // return false
System.out.println(Files.isRegularFile(path)); // return false

And for the following example:

Path path = Paths.get("/some/path/to/dir/file.txt");
System.out.println(Files.isDirectory(path));  //return false
System.out.println(Files.isRegularFile(path));  // return false

So we see that in both case system return false. This is true for both java.io.File and java.nio.file.Path

How to set thousands separator in Java?

public String formatStr(float val) {
 return String.format(Locale.CANADA, "%,.2f", val);
}

formatStr(2524.2) // 2,254.20



Debug JavaScript in Eclipse

In 2015, there are at least six choices for JavaScript debugging in Eclipse:

Adding to the above, here are a couple of videos which focus on "debugging JavaScript using eclipse"

Outdated

Spring Boot Remove Whitelabel Error Page

Manual here says that you have to set server.error.whitelabel.enabled to false to disable the standard error page. Maybe it is what you want?

I am experiencing the same error after adding /error mapping, by the way.

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

To sum up based on answers here and elsewhere:

  1. Check the .NET version of the app pool (e.g. 2.0 vs 4.0)
  2. Check that all IIS referenced modules are installed. In this case it was the AJAX extensions (probably not the case these days), but URL Rewrite is a common one.

Run CSS3 animation only once (at page loading)

After hours of googling: No, it's not possible without JavaScript. The animation-iteration-count: 1; is internally saved in the animation shothand attribute, which gets resetted and overwritten on :hover. When we blur the <a> and release the :hover the old class reapplies and therefore again resets the animation attribute.

There sadly is no way to save a certain attribute states across element states.

You'll have to use JavaScript.

CASE (Contains) rather than equal statement

Pseudo code, something like:

CASE
  When CHARINDEX('lactulose', dbo.Table.Column) > 0 Then 'BP Medication'
ELSE ''
END AS 'Medication Type'

This does not care where the keyword is found in the list and avoids depending on formatting of spaces and commas.

Delete a row in Excel VBA

Chris Nielsen's solution is simple and will work well. A slightly shorter option would be...

ws.Rows(Rand).Delete

...note there is no need to specify a Shift when deleting a row as, by definition, it's not possible to shift left

Incidentally, my preferred method for deleting rows is to use...

ws.Rows(Rand) = ""

...in the initial loop. I then use a Sort function to push these rows to the bottom of the data. The main reason for this is because deleting single rows can be a very slow procedure (if you are deleting >100). It also ensures nothing gets missed as per Robert Ilbrink's comment

You can learn the code for sorting by recording a macro and reducing the code as demonstrated in this expert Excel video. I have a suspicion that the neatest method (Range("A1:Z10").Sort Key1:=Range("A1"), Order1:=xlSortAscending/Descending, Header:=xlYes/No) can only be discovered on pre-2007 versions of Excel...but you can always reduce the 2007/2010 equivalent code

Couple more points...if your list is not already sorted by a column and you wish to retain the order, you can stick the row number 'Rand' in a spare column to the right of each row as you loop through. You would then sort by that comment and eliminate it

If your data rows contain formatting, you may wish to find the end of the new data range and delete the rows that you cleared earlier. That's to keep the file size down. Note that a single large delete at the end of the procedure will not impair your code's performance in the same way that deleting single rows does

How to make a variable accessible outside a function?

Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.

You have to nest the requests:

$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   obj = name;   // sID is only now available!   sID = obj.id;   console.log(sID); }); 


Clean up your code!

  • Put the second request into a function
  • and let it accept sID as a parameter, so you don't have to declare it globally anymore! (Global variables are almost always evil!)
  • Remove sID and obj variables - name.id is sufficient unless you really need the other variables outside the function.


$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   // We don't need sID or obj here - name.id is sufficient   console.log(name.id);    doSecondRequest(name.id); });  /// TODO Choose a better name function doSecondRequest(sID) {   $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){         console.log(stats);   }); } 

Hapy New Year :)

Entity Framework Queryable async

Long story short,
IQueryable is designed to postpone RUN process and firstly build the expression in conjunction with other IQueryable expressions, and then interprets and runs the expression as a whole.
But ToList() method (or a few sort of methods like that), are ment to run the expression instantly "as is".
Your first method (GetAllUrlsAsync), will run imediately, because it is IQueryable followed by ToListAsync() method. hence it runs instantly (asynchronous), and returns a bunch of IEnumerables.
Meanwhile your second method (GetAllUrls), won't get run. Instead, it returns an expression and CALLER of this method is responsible to run the expression.

Python 'list indices must be integers, not tuple"

To create list of lists, you need to separate them with commas, like this

coin_args = [
    ["pennies", '2.5', '50.0', '.01'],
    ["nickles", '5.0', '40.0', '.05'],
    ["dimes", '2.268', '50.0', '.1'],
    ["quarters", '5.67', '40.0', '.25']
]

PHPExcel How to apply styles and set cell width and cell height to cell generated dynamically

Try this:

$objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);

Parse XLSX with Node and create json

You can also use

var XLSX = require('xlsx');
var workbook = XLSX.readFile('Master.xlsx');
var sheet_name_list = workbook.SheetNames;
console.log(XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]))

Set NOW() as Default Value for datetime datatype?

I use a trigger as a workaround to set a datetime field to NOW() for new inserts:

CREATE TRIGGER `triggername` BEFORE INSERT ON  `tablename` 
FOR EACH ROW 
SET NEW.datetimefield = NOW()

it should work for updates too

Answers by Johan & Leonardo involve converting to a timestamp field. Although this is probably ok for the use case presented in the question (storing RegisterDate and LastVisitDate), it is not a universal solution. See datetime vs timestamp question.

How to convert SecureString to System.String?

I created the following extension methods based on the answer from rdev5. Pinning the managed string is important as it prevents the garbage collector from moving it around and leaving behind copies that you're unable to erase.

I think the advantage of my solution has is that no unsafe code is needed.

/// <summary>
/// Allows a decrypted secure string to be used whilst minimising the exposure of the
/// unencrypted string.
/// </summary>
/// <typeparam name="T">Generic type returned by Func delegate.</typeparam>
/// <param name="secureString">The string to decrypt.</param>
/// <param name="action">
/// Func delegate which will receive the decrypted password as a string object
/// </param>
/// <returns>Result of Func delegate</returns>
/// <remarks>
/// This method creates an empty managed string and pins it so that the garbage collector
/// cannot move it around and create copies. An unmanaged copy of the the secure string is
/// then created and copied into the managed string. The action is then called using the
/// managed string. Both the managed and unmanaged strings are then zeroed to erase their
/// contents. The managed string is unpinned so that the garbage collector can resume normal
/// behaviour and the unmanaged string is freed.
/// </remarks>
public static T UseDecryptedSecureString<T>(this SecureString secureString, Func<string, T> action)
{
    int length = secureString.Length;
    IntPtr sourceStringPointer = IntPtr.Zero;

    // Create an empty string of the correct size and pin it so that the GC can't move it around.
    string insecureString = new string('\0', length);
    var insecureStringHandler = GCHandle.Alloc(insecureString, GCHandleType.Pinned);

    IntPtr insecureStringPointer = insecureStringHandler.AddrOfPinnedObject();

    try
    {
        // Create an unmanaged copy of the secure string.
        sourceStringPointer = Marshal.SecureStringToBSTR(secureString);

        // Use the pointers to copy from the unmanaged to managed string.
        for (int i = 0; i < secureString.Length; i++)
        {
            short unicodeChar = Marshal.ReadInt16(sourceStringPointer, i * 2);
            Marshal.WriteInt16(insecureStringPointer, i * 2, unicodeChar);
        }

        return action(insecureString);
    }
    finally
    {
        // Zero the managed string so that the string is erased. Then unpin it to allow the
        // GC to take over.
        Marshal.Copy(new byte[length], 0, insecureStringPointer, length);
        insecureStringHandler.Free();

        // Zero and free the unmanaged string.
        Marshal.ZeroFreeBSTR(sourceStringPointer);
    }
}

/// <summary>
/// Allows a decrypted secure string to be used whilst minimising the exposure of the
/// unencrypted string.
/// </summary>
/// <param name="secureString">The string to decrypt.</param>
/// <param name="action">
/// Func delegate which will receive the decrypted password as a string object
/// </param>
/// <returns>Result of Func delegate</returns>
/// <remarks>
/// This method creates an empty managed string and pins it so that the garbage collector
/// cannot move it around and create copies. An unmanaged copy of the the secure string is
/// then created and copied into the managed string. The action is then called using the
/// managed string. Both the managed and unmanaged strings are then zeroed to erase their
/// contents. The managed string is unpinned so that the garbage collector can resume normal
/// behaviour and the unmanaged string is freed.
/// </remarks>
public static void UseDecryptedSecureString(this SecureString secureString, Action<string> action)
{
    UseDecryptedSecureString(secureString, (s) =>
    {
        action(s);
        return 0;
    });
}

C string append

You could use asprintf to concatenate both into a new string:

char *new_str;
asprintf(&new_str,"%s%s",str1,str2);

A simple jQuery form validation script

You can simply use the jQuery Validate plugin as follows.

jQuery:

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            field1: {
                required: true,
                email: true
            },
            field2: {
                required: true,
                minlength: 5
            }
        }
    });

});

HTML:

<form id="myform">
    <input type="text" name="field1" />
    <input type="text" name="field2" />
    <input type="submit" />
</form>

DEMO: http://jsfiddle.net/xs5vrrso/

Options: http://jqueryvalidation.org/validate

Methods: http://jqueryvalidation.org/category/plugin/

Standard Rules: http://jqueryvalidation.org/category/methods/

Optional Rules available with the additional-methods.js file:

maxWords
minWords
rangeWords
letterswithbasicpunc
alphanumeric
lettersonly
nowhitespace
ziprange
zipcodeUS
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
phonesUK
postcodeUK
strippedminlength
email2 (optional TLD)
url2 (optional TLD)
creditcardtypes
ipv4
ipv6
pattern
require_from_group
skip_or_fill_minimum
accept
extension

How to compare two files in Notepad++ v6.6.8

2018 10 25. Update.

Notepad++ 7.5.8 does not have plugin manager by default. You have to download plugins manually.

Keep in mind, if you use 64 bit version of Notepad++, you should also use 64 bit version of plugin. I had a similar issue here.

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

Plotting 4 curves in a single plot, with 3 y-axes

Multi-scale plots are rare to find beyond two axes... Luckily in Matlab it is possible, but you have to fully overlap axes and play with tickmarks so as not to hide info.

Below is a nice working sample. I hope this is what you are looking for (although colors could be much nicer)!

close all
clear all 

display('Generating data');

x = 0:10;
y1 = rand(1,11);
y2 = 10.*rand(1,11);
y3 = 100.*rand(1,11);
y4 = 100.*rand(1,11);

display('Plotting');

figure;
ax1 = gca;
get(ax1,'Position')
set(ax1,'XColor','k',...
    'YColor','b',...
    'YLim',[0,1],...
    'YTick',[0, 0.2, 0.4, 0.6, 0.8, 1.0]);
line(x, y1, 'Color', 'b', 'LineStyle', '-', 'Marker', '.', 'Parent', ax1)

ax2 = axes('Position',get(ax1,'Position'),...
           'XAxisLocation','bottom',...
           'YAxisLocation','left',...
           'Color','none',...
           'XColor','k',...
           'YColor','r',...
           'YLim',[0,10],...
           'YTick',[1, 3, 5, 7, 9],...
           'XTick',[],'XTickLabel',[]);
line(x, y2, 'Color', 'r', 'LineStyle', '-', 'Marker', '.', 'Parent', ax2)

ax3 = axes('Position',get(ax1,'Position'),...
           'XAxisLocation','bottom',...
           'YAxisLocation','right',...
           'Color','none',...
           'XColor','k',...
           'YColor','g',...
           'YLim',[0,100],...
           'YTick',[0, 20, 40, 60, 80, 100],...
           'XTick',[],'XTickLabel',[]);
line(x, y3, 'Color', 'g', 'LineStyle', '-', 'Marker', '.', 'Parent', ax3)

ax4 = axes('Position',get(ax1,'Position'),...
           'XAxisLocation','bottom',...
           'YAxisLocation','right',...
           'Color','none',...
           'XColor','k',...
           'YColor','c',...
           'YLim',[0,100],...
           'YTick',[10, 30, 50, 70, 90],...
           'XTick',[],'XTickLabel',[]);
line(x, y4, 'Color', 'c', 'LineStyle', '-', 'Marker', '.', 'Parent', ax4)

alt text
(source: pablorodriguez.info)

How to send cookies in a post request with the Python Requests library?

Just to extend on the previous answer, if you are linking two requests together and want to send the cookies returned from the first one to the second one (for example, maintaining a session alive across requests) you can do:

import requests
r1 = requests.post('http://www.yourapp.com/login')
r2 = requests.post('http://www.yourapp.com/somepage',cookies=r1.cookies)

Difference between long and int data types

The guarantees the standard gives you go like this:

1 == sizeof(char) <= sizeof(short) <= sizeof (int) <= sizeof(long) <= sizeof(long long)

So it's perfectly valid for sizeof (int) and sizeof (long) to be equal, and many platforms choose to go with this approach. You will find some platforms where int is 32 bits, long is 64 bits, and long long is 128 bits, but it seems very common for sizeof (long) to be 4.

(Note that long long is recognized in C from C99 onwards, but was normally implemented as an extension in C++ prior to C++11.)

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

Image vs Bitmap class

This is a clarification because I have seen things done in code which are honestly confusing - I think the following example might assist others.

As others have said before - Bitmap inherits from the Abstract Image class

Abstract effectively means you cannot create a New() instance of it.

    Image imgBad1 = new Image();        // Bad - won't compile
    Image imgBad2 = new Image(200,200); // Bad - won't compile

But you can do the following:

    Image imgGood;  // Not instantiated object!
    // Now you can do this
    imgGood = new Bitmap(200, 200);

You can now use imgGood as you would the same bitmap object if you had done the following:

    Bitmap bmpGood = new Bitmap(200,200);

The nice thing here is you can draw the imgGood object using a Graphics object

    Graphics gr = default(Graphics);
    gr = Graphics.FromImage(new Bitmap(1000, 1000));
    Rectangle rect = new Rectangle(50, 50, imgGood.Width, imgGood.Height); // where to draw
    gr.DrawImage(imgGood, rect);

Here imgGood can be any Image object - Bitmap, Metafile, or anything else that inherits from Image!

What's the fastest way to do a bulk insert into Postgres?

One way to speed things up is to explicitly perform multiple inserts or copy's within a transaction (say 1000). Postgres's default behavior is to commit after each statement, so by batching the commits, you can avoid some overhead. As the guide in Daniel's answer says, you may have to disable autocommit for this to work. Also note the comment at the bottom that suggests increasing the size of the wal_buffers to 16 MB may also help.

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

If you have access to a linux box with mdbtools installed, you can use this Bash shell script (save as mdbconvert.sh):

#!/bin/bash

TABLES=$(mdb-tables -1 $1)

MUSER="root"
MPASS="yourpassword"
MDB="$2"

MYSQL=$(which mysql)

for t in $TABLES
do
    $MYSQL -u $MUSER -p$MPASS $MDB -e "DROP TABLE IF EXISTS $t"
done

mdb-schema $1 mysql | $MYSQL -u $MUSER -p$MPASS $MDB

for t in $TABLES
do
    mdb-export -D '%Y-%m-%d %H:%M:%S' -I mysql $1 $t | $MYSQL -u $MUSER -p$MPASS $MDB
done

To invoke it simply call it like this:

./mdbconvert.sh accessfile.mdb mysqldatabasename

It will import all tables and all data.

Microsoft.ACE.OLEDB.12.0 provider is not registered

I am assuming that if you are running a 64 bit system with a 32 bit database and trying to run a 64 bit console, the following packages need to be installed on the machine.

  1. Install the Microsoft Access Database Engine 2010 x86 Redistributable, this installation is available at: http://www.microsoft.com/download/en/details.aspx?id=13255 .
  2. Data Connectivity Components of Office 2007, this installation is available at: http://www.microsoft.com/download/en/confirmation.aspx?id=23734 .
  3. Microsoft Access Database Engine 2010 x64 Redistributable. You will need to download the package locally and run it with a passive flag. You can download the installation here: http://www.microsoft.com/en-us/download/details.aspx?id=13255 Installing using the command prompt with the '/passive' flag. In the command prompt run the following command: 'AccessDatabaseEngine_x64.exe /passive'

Note: The order seems to matter - so if you have anything installed already, uninstall and follow the steps above.

"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"

ON DUPLICATE KEY UPDATE is not really in the standard. It's about as standard as REPLACE is. See SQL MERGE.

Essentially both commands are alternative-syntax versions of standard commands.

How to create a function in SQL Server

This one get everything between the "." characters. Please note this won't work for more complex URLs like "www.somesite.co.uk" Ideally the function would check for how many instances of the "." character and choose the substring accordingly.

CREATE FUNCTION dbo.GetURL (@URL VARCHAR(250))
RETURNS VARCHAR(250)
AS BEGIN
    DECLARE @Work VARCHAR(250)

    SET @Work = @URL

    SET @Work = SUBSTRING(@work, CHARINDEX('.', @work) + 1, LEN(@work))   
    SET @Work = SUBSTRING(@work, 0, CHARINDEX('.', @work))

    --Alternate:
    --SET @Work = SUBSTRING(@work, CHARINDEX('.', @work) + 1, CHARINDEX('.', @work) + 1)   

    RETURN @work
END

EPPlus - Read Excel Table

There is no native but what if you use what I put in this post:

How to parse excel rows back to types using EPPlus

If you want to point it at a table only it will need to be modified. Something like this should do it:

public static IEnumerable<T> ConvertTableToObjects<T>(this ExcelTable table) where T : new()
{
    //DateTime Conversion
    var convertDateTime = new Func<double, DateTime>(excelDate =>
    {
        if (excelDate < 1)
            throw new ArgumentException("Excel dates cannot be smaller than 0.");

        var dateOfReference = new DateTime(1900, 1, 1);

        if (excelDate > 60d)
            excelDate = excelDate - 2;
        else
            excelDate = excelDate - 1;
        return dateOfReference.AddDays(excelDate);
    });

    //Get the properties of T
    var tprops = (new T())
        .GetType()
        .GetProperties()
        .ToList();

    //Get the cells based on the table address
    var start = table.Address.Start;
    var end = table.Address.End;
    var cells = new List<ExcelRangeBase>();

    //Have to use for loops insteadof worksheet.Cells to protect against empties
    for (var r = start.Row; r <= end.Row; r++)
        for (var c = start.Column; c <= end.Column; c++)
            cells.Add(table.WorkSheet.Cells[r, c]);

    var groups = cells
        .GroupBy(cell => cell.Start.Row)
        .ToList();

    //Assume the second row represents column data types (big assumption!)
    var types = groups
        .Skip(1)
        .First()
        .Select(rcell => rcell.Value.GetType())
        .ToList();

    //Assume first row has the column names
    var colnames = groups
        .First()
        .Select((hcell, idx) => new { Name = hcell.Value.ToString(), index = idx })
        .Where(o => tprops.Select(p => p.Name).Contains(o.Name))
        .ToList();

    //Everything after the header is data
    var rowvalues = groups
        .Skip(1) //Exclude header
        .Select(cg => cg.Select(c => c.Value).ToList());

    //Create the collection container
    var collection = rowvalues
        .Select(row =>
        {
            var tnew = new T();
            colnames.ForEach(colname =>
            {
                //This is the real wrinkle to using reflection - Excel stores all numbers as double including int
                var val = row[colname.index];
                var type = types[colname.index];
                var prop = tprops.First(p => p.Name == colname.Name);

                //If it is numeric it is a double since that is how excel stores all numbers
                if (type == typeof(double))
                {
                    if (!string.IsNullOrWhiteSpace(val?.ToString()))
                    {
                        //Unbox it
                        var unboxedVal = (double)val;

                        //FAR FROM A COMPLETE LIST!!!
                        if (prop.PropertyType == typeof(Int32))
                            prop.SetValue(tnew, (int)unboxedVal);
                        else if (prop.PropertyType == typeof(double))
                            prop.SetValue(tnew, unboxedVal);
                        else if (prop.PropertyType == typeof(DateTime))
                            prop.SetValue(tnew, convertDateTime(unboxedVal));
                        else
                            throw new NotImplementedException(String.Format("Type '{0}' not implemented yet!", prop.PropertyType.Name));
                    }
                }
                else
                {
                    //Its a string
                    prop.SetValue(tnew, val);
                }
            });

            return tnew;
        });


    //Send it back
    return collection;
}

Here is a test method:

[TestMethod]
public void Table_To_Object_Test()
{
    //Create a test file
    var fi = new FileInfo(@"c:\temp\Table_To_Object.xlsx");

    using (var package = new ExcelPackage(fi))
    {
        var workbook = package.Workbook;
        var worksheet = workbook.Worksheets.First();
        var ThatList = worksheet.Tables.First().ConvertTableToObjects<ExcelData>();
        foreach (var data in ThatList)
        {
            Console.WriteLine(data.Id + data.Name + data.Gender);
        }

        package.Save();
    }
}

Gave this in the console:

1JohnMale
2MariaFemale
3DanielUnknown

Just be careful if you Id field is an number or string in excel since the class is expecting a string.

How to use WinForms progress bar?

There is Task exists, It is unnesscery using BackgroundWorker, Task is more simple. for example:

ProgressDialog.cs:

   public partial class ProgressDialog : Form
    {
        public System.Windows.Forms.ProgressBar Progressbar { get { return this.progressBar1; } }

        public ProgressDialog()
        {
            InitializeComponent();
        }

        public void RunAsync(Action action)
        {
            Task.Run(action);
        }
    }

Done! Then you can reuse ProgressDialog anywhere:

var progressDialog = new ProgressDialog();
progressDialog.Progressbar.Value = 0;
progressDialog.Progressbar.Maximum = 100;

progressDialog.RunAsync(() =>
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000)
        this.progressDialog.Progressbar.BeginInvoke((MethodInvoker)(() => {
            this.progressDialog.Progressbar.Value += 1;
        }));
    }
});

progressDialog.ShowDialog();

Query error with ambiguous column name in SQL

One of your tables has the same column name's which brings a confusion in the query as to which columns of the tables are you referring to. Copy this code and run it.

SELECT 
    v.VendorName, i.InvoiceID, iL.InvoiceSequence, iL.InvoiceLineItemAmount
FROM Vendors AS v
JOIN Invoices AS i ON (v.VendorID = .VendorID)
JOIN InvoiceLineItems AS iL ON (i.InvoiceID = iL.InvoiceID)
WHERE  
    I.InvoiceID IN
        (SELECT iL.InvoiceSequence 
         FROM InvoiceLineItems
         WHERE iL.InvoiceSequence > 1)
ORDER BY 
    V.VendorName, i.InvoiceID, iL.InvoiceSequence, iL.InvoiceLineItemAmount

How to delete a whole folder and content?

Simple way to delete all file from directory :

It is generic function for delete all images from directory by calling only

deleteAllImageFile(context);

public static void deleteAllFile(Context context) {
File directory = context.getExternalFilesDir(null);
        if (directory.isDirectory()) {
            for (String fileName: file.list()) {
                new File(file,fileName).delete();
            }
        }    
    } 

Set style for TextView programmatically

The accepted answer was great solution for me. The only thing to add is about inflate() method.

In accepted answer all android:layout_* parameters will not be applied.

The reason is no way to adjust it, cause null was passed as ViewGroup parent.

You can use it like this:

View view = inflater.inflate(R.layout.view, parent, false);

and the parent is the ViewGroup, from where you like to adjust android:layout_*.

In this case, all relative properties will be set.

Hope it'll be useful for someone.

What can MATLAB do that R cannot do?

We can't because it's expected/required by our customers.

Handling warning for possible multiple enumeration of IEnumerable

Using IReadOnlyCollection<T> or IReadOnlyList<T> in the method signature instead of IEnumerable<T>, has the advantage of making explicit that you might need to check the count before iterating, or to iterate multiple times for some other reason.

However they have a huge downside that will cause problems if you try to refactor your code to use interfaces, for instance to make it more testable and friendly to dynamic proxying. The key point is that IList<T> does not inherit from IReadOnlyList<T>, and similarly for other collections and their respective read-only interfaces. (In short, this is because .NET 4.5 wanted to keep ABI compatibility with earlier versions. But they didn't even take the opportunity to change that in .NET core.)

This means that if you get an IList<T> from some part of the program and want to pass it to another part that expects an IReadOnlyList<T>, you can't! You can however pass an IList<T> as an IEnumerable<T>.

In the end, IEnumerable<T> is the only read-only interface supported by all .NET collections including all collection interfaces. Any other alternative will come back to bite you as you realize that you locked yourself out from some architecture choices. So I think it's the proper type to use in function signatures to express that you just want a read-only collection.

(Note that you can always write a IReadOnlyList<T> ToReadOnly<T>(this IList<T> list) extension method that simple casts if the underlying type supports both interfaces, but you have to add it manually everywhere when refactoring, where as IEnumerable<T> is always compatible.)

As always this is not an absolute, if you're writing database-heavy code where accidental multiple enumeration would be a disaster, you might prefer a different trade-off.

What is the inclusive range of float and double in Java?

Of course you can use floats or doubles for "critical" things ... Many applications do nothing but crunch numbers using these datatypes.

You might have misunderstood some of the various caveats regarding floating-point numbers, such as the recommendation to never compare for exact equality, and so on.

Executing periodic actions in Python

Here's a nice implementation using the Thread class: http://g-off.net/software/a-python-repeatable-threadingtimer-class

the code below is a little more quick and dirty:

from threading import Timer
from time import sleep

def hello():
    print "hello, world"
    t = Timer(3,hello)
    t.start()

t = Timer(3, hello)
t.start() # after 3 seconds, "hello, world" will be printed

# timer will wake up ever 3 seconds, while we do something else
while True:
    print "do something else"
    sleep(10)

javascript close current window

I found this method by Jeff Clayton. It is working for me with Firefox 56 and Chrome (on Windows and Android).

Did not try all possibilities. On my side, I open a window with a target name in my A links, for example, target="mywindowname", so all my links open inside the same window name: mywindowname.

To open a new window:

<a href="example-link.html" target="mywindowname">New Window</a>

And then in the new window (inside example-link.html):

<a href="#" onclick="return quitBox('quit');"></a>

Javascript:

function quitBox(cmd) {   
    if (cmd=='quit') {
        open(location, '_self').close();
    }   
    return false;   
}

Hope this can help anyone else that is looking for a method to close a window. I tried a lot of other methods and this one is the best I found.

Selecting a row of pandas series/dataframe by integer index

You can take a look at the source code .

DataFrame has a private function _slice() to slice the DataFrame, and it allows the parameter axis to determine which axis to slice. The __getitem__() for DataFrame doesn't set the axis while invoking _slice(). So the _slice() slice it by default axis 0.

You can take a simple experiment, that might help you:

print df._slice(slice(0, 2))
print df._slice(slice(0, 2), 0)
print df._slice(slice(0, 2), 1)

How can I create a simple message box in Python?

import sys
from tkinter import *
def mhello():
    pass
    return

mGui = Tk()
ment = StringVar()

mGui.geometry('450x450+500+300')
mGui.title('My youtube Tkinter')

mlabel = Label(mGui,text ='my label').pack()

mbutton = Button(mGui,text ='ok',command = mhello,fg = 'red',bg='blue').pack()

mEntry = entry().pack 

Getting a Request.Headers value

The following code should allow you to check for the existance of the header you're after in Request.Headers:

if (Request.Headers.AllKeys.Contains("XYZComponent"))
{
    // Can now check if the value is true:
    var value = Convert.ToBoolean(Request.Headers["XYZComponent"]);
}

How to put a tooltip on a user-defined function

I know you've accepted an answer for this, but there's now a solution that lets you get an intellisense style completion box pop up like for the other excel functions, via an Excel-DNA add in, or by registering an intellisense server inside your own add in. See here.

Now, i prefer the C# way of doing it - it's much simpler, as inside Excel-DNA, any class that implements IExcelAddin is picked up by the addin framework and has AutoOpen() and AutoClose() run when you open/close the add in. So you just need this:

namespace MyNameSpace {
    public class Intellisense : IExcelAddIn {
        public void AutoClose() {
        }
        public void AutoOpen() {
            IntelliSenseServer.Register();
        }
    }
}

and then (and this is just taken from the github page), you just need to use the ExcelDNA annotations on your functions:

[ExcelFunction(Description = "A useful test function that adds two numbers, and returns the sum.")]
public static double AddThem(
    [ExcelArgument(Name = "Augend", Description = "is the first number, to which will be added")] 
    double v1,
    [ExcelArgument(Name = "Addend", Description = "is the second number that will be added")]     
    double v2)
{
    return v1 + v2;
}

which are annotated using the ExcelDNA annotations, the intellisense server will pick up the argument names and descriptions.

enter image description here enter image description here

There are examples for using it with just VBA too, but i'm not too into my VBA, so i don't use those parts.

Android RelativeLayout programmatically Set "centerInParent"

I have done for

1. centerInParent

2. centerHorizontal

3. centerVertical

with true and false.

private void addOrRemoveProperty(View view, int property, boolean flag){
    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
    if(flag){
        layoutParams.addRule(property);
    }else {
        layoutParams.removeRule(property);
    }
    view.setLayoutParams(layoutParams);
}

How to call method:

centerInParent - true

addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, true);

centerInParent - false

addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, false);

centerHorizontal - true

addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, true);

centerHorizontal - false

addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, false);

centerVertical - true

addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, true);

centerVertical - false

addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, false);

Hope this would help you.

php return 500 error but no error log

Copy and paste the following into a new .htaccess file and place it on your website's root folder :

php_flag  display_errors                  on
php_flag  display_startup_errors          on

Errors will be shown directly in your page.

That's the best way to debug quickly but don't use it for long time because it could be a security breach.

How to export data as CSV format from SQL Server using sqlcmd?

Usually sqlcmd comes with bcp utility (as part of mssql-tools) which exports into CSV by default.

Usage:

bcp {dbtable | query} {in | out | queryout | format} datafile

For example:

bcp.exe MyTable out data.csv

To dump all tables into corresponding CSV files, here is the Bash script:

#!/usr/bin/env bash
# Script to dump all tables from SQL Server into CSV files via bcp.
# @file: bcp-dump.sh
server="sql.example.com" # Change this.
user="USER" # Change this.
pass="PASS" # Change this.
dbname="DBNAME" # Change this.
creds="-S '$server' -U '$user' -P '$pass' -d '$dbname'"
sqlcmd $creds -Q 'SELECT * FROM sysobjects sobjects' > objects.lst
sqlcmd $creds -Q 'SELECT * FROM information_schema.routines' > routines.lst
sqlcmd $creds -Q 'sp_tables' | tail -n +3 | head -n -2 > sp_tables.lst
sqlcmd $creds -Q 'SELECT name FROM sysobjects sobjects WHERE xtype = "U"' | tail -n +3 | head -n -2 > tables.lst

for table in $(<tables.lst); do
  sqlcmd $creds -Q "exec sp_columns $table" > $table.desc && \
  bcp $table out $table.csv -S $server -U $user -P $pass -d $dbname -c
done

insert data into database using servlet and jsp in eclipse

Can you check value of i by putting logger or println(). and check with closing db conn at the end. Rest your code looks fine and it should work.

How to set a header in an HTTP response?

Header fields are not copied to subsequent requests. You should use either cookie for this (addCookie method) or store "REMOTE_USER" in session (which you can obtain with getSession method).

Write variable to a file in Ansible

An important comment from tmoschou:

As of Ansible 2.10, The documentation for ansible.builtin.copy says:
If you need variable interpolation in copied files, use the
ansible.builtin.template module. Using a variable in the content
field will result in unpredictable output.

For more details see this and an explanation


Original answer:

You could use the copy module, with the content parameter:

- copy: content="{{ your_json_feed }}" dest=/path/to/destination/file

The docs here: copy module

How to style a clicked button in CSS

If you just want the button to have different styling while the mouse is pressed you can use the :active pseudo class.

.button:active {
}

If on the other hand you want the style to stay after clicking you will have to use javascript.

Flutter Circle Design

You can use CustomMultiChildLayout to draw this kind of layouts. Here you can find a tutorial: How to Create Custom Layout Widgets in Flutter.

adb remount permission denied, but able to access super user in shell -- android

I rebooted to recovery then

adb root; adb adb remount system; 

worked for me my recovery is twrp v3.5

Linq select objects in list where exists IN (A,B,C)

Try with Contains function;

Determines whether a sequence contains a specified element.

var allowedStatus = new[]{ "A", "B", "C" };
var filteredOrders = orders.Order.Where(o => allowedStatus.Contains(o.StatusCode));

git pull while not in a git directory

For anyone like me that was trying to do this via a drush (Drupal shell) command on a remote server, you will not be able to use the solution that requires you to CD into the working directory:

Instead you need to use the solution that breaks up the pull into a fetch & merge:

drush @remote exec git --git-dir=/REPO/PATH --work-tree=/REPO/WORKDIR-PATH fetch origin
drush @remote exec git --git-dir=/REPO/PATH --work-tree=/REPO/WORKDIR-PATH merge origin/branch

How to automatically update an application without ClickOnce?

There are a lot of questions already about this, so I will refer you to those.

One thing you want to make sure to prevent the need for uninstallation, is that you use the same upgrade code on every release, but change the product code. These values are located in the Installshield project properties.

Some references:

Count a list of cells with the same background color

The worksheet formula, =CELL("color",D3) returns 1 if the cell is formatted with color for negative values (else returns 0).

You can solve this with a bit of VBA. Insert this into a VBA code module:

Function CellColor(xlRange As Excel.Range)
    CellColor = xlRange.Cells(1, 1).Interior.ColorIndex
End Function

Then use the function =CellColor(D3) to display the .ColorIndex of D3

How to check if the given string is palindrome?

// JavaScript Version.
function isPalindrome(str) { 
  str = str.replace(/[^a-zA-Z]/g, '')
  return str.split('').reverse().join('').toUpperCase() === str.toUpperCase()       
}

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

Taken from Using FOREIGN KEY Constraints

Foreign key relationships involve a parent table that holds the central data values, and a child table with identical values pointing back to its parent. The FOREIGN KEY clause is specified in the child table.

It will reject any INSERT or UPDATE operation that attempts to create a foreign key value in a child table if there is no a matching candidate key value in the parent table.

So your error Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails essentially means that, you are trying to add a row to your Ordrelinje table for which no matching row (OrderID) is present in Ordre table.

You must first insert the row to your Ordre table.

php - push array into array - key issue

Use this..

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
    $res_arr_values[] = $row;
}

Object of custom type as dictionary key

You override __hash__ if you want special hash-semantics, and __cmp__ or __eq__ in order to make your class usable as a key. Objects who compare equal need to have the same hash value.

Python expects __hash__ to return an integer, returning Banana() is not recommended :)

User defined classes have __hash__ by default that calls id(self), as you noted.

There is some extra tips from the documentation.:

Classes which inherit a __hash__() method from a parent class but change the meaning of __cmp__() or __eq__() such that the hash value returned is no longer appropriate (e.g. by switching to a value-based concept of equality instead of the default identity based equality) can explicitly flag themselves as being unhashable by setting __hash__ = None in the class definition. Doing so means that not only will instances of the class raise an appropriate TypeError when a program attempts to retrieve their hash value, but they will also be correctly identified as unhashable when checking isinstance(obj, collections.Hashable) (unlike classes which define their own __hash__() to explicitly raise TypeError).

How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?

Convert the integer into a string and then you can use the STUFF function to insert in your colons into time string. Once you've done that you can convert the string into a time datatype.

SELECT CAST(STUFF(STUFF(STUFF(cast(23421155 as varchar),3,0,':'),6,0,':'),9,0,'.') AS TIME)

That should be the simplest way to convert it to a time without doing anything to crazy.

In your example you also had an int where the leading zeros are not there. In that case you can simple do something like this:

SELECT CAST(STUFF(STUFF(STUFF(RIGHT('00000000' + CAST(421151 AS VARCHAR),8),3,0,':'),6,0,':'),9,0,'.') AS TIME)

Find a value in DataTable

Maybe you can filter rows by possible columns like this :

DataRow[] filteredRows = 
  datatable.Select(string.Format("{0} LIKE '%{1}%'", columnName, value));

How to tag docker image with docker-compose

Original answer Nov 20 '15:

No option for a specific tag as of Today. Docker compose just does its magic and assigns a tag like you are seeing. You can always have some script call docker tag <image> <tag> after you call docker-compose.

Now there's an option as described above or here

build: ./dir
image: webapp:tag

How do I check in python if an element of a list is empty?

Suppose

letter= ['a','','b','c']

for i in range(len(letter)):
    if letter[i] =='':
        print(str(i) + ' is empty')

output- 1 is emtpy

So we can see index 1 is empty.

How to keep onItemSelected from firing off on a newly instantiated Spinner?

Not a prefect solution but if your happy with having the starting string as just a place holder you can add place holder spring value ("Day_of_Work_Out")

  @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String name = (String) parent.getItemAtPosition(position);
            if (name.equals("Day_of_Work_Out")) {

            }else {

                workOutD = name;
                Intent intent = new Intent();
                workOutNam = workOutName.getText().toString();

                if (workOutNam == null) {

                    startActivity(intent);
                    Log.i("NewWorkOutActivity","Name is null");

                }else {
                    Log.i("NewWorkOutActivity","Name Not null");
                    Toast.makeText(NewWorkOutActivity.this, "Please Select a Day", Toast.LENGTH_LONG).show();
                }


            }
        }

xpath find if node exists

Might be better to use a choice, don't have to type (or possibly mistype) your expressions more than once, and allows you to follow additional different behaviors.

I very often use count(/html/body) = 0, as the specific number of nodes is more interesting than the set. For example... when there is unexpectedly more than 1 node that matches your expression.

<xsl:choose>
    <xsl:when test="/html/body">
         <!-- Found the node(s) -->
    </xsl:when>
    <!-- more xsl:when here, if needed -->
    <xsl:otherwise>
         <!-- No node exists -->
    </xsl:otherwise>
</xsl:choose>

Gson: How to exclude specific fields from Serialization without annotations

I have Kotlin version

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FIELD)
internal annotation class JsonSkip

class SkipFieldsStrategy : ExclusionStrategy {

    override fun shouldSkipClass(clazz: Class<*>): Boolean {
        return false
    }

    override fun shouldSkipField(f: FieldAttributes): Boolean {
        return f.getAnnotation(JsonSkip::class.java) != null
    }
}

and how You can add this to Retrofit GSONConverterFactory:

val gson = GsonBuilder()
                .setExclusionStrategies(SkipFieldsStrategy())
                //.serializeNulls()
                //.setDateFormat(DateFormat.LONG)
                //.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
                //.setPrettyPrinting()
                //.registerTypeAdapter(Id.class, IdTypeAdapter())
                .create()
        return GsonConverterFactory.create(gson)

How do I switch between command and insert mode in Vim?

Pressing ESC quits from insert mode to normal mode, where you can press : to type in a command. Press i again to back to insert mode, and you are good to go.

I'm not a Vim guru, so someone else can be more experienced and give you other options.

how to set default main class in java?

Best way is to handle this in an Ant script. You can create 2 different tasks for the 2 jar files. Specify class A as the main class in the manifst file for the first jar. similarly specify class B as the main class in the manifest file for the second jar.

you can easily run the Ant tasks from Netbeans.

Populate nested array in mongoose

You can populate multiple nested documents like this.

   Project.find(query)
    .populate({ 
      path: 'pages',
      populate: [{
       path: 'components',
       model: 'Component'
      },{
        path: 'AnotherRef',
        model: 'AnotherRef',
        select: 'firstname lastname'
      }] 
   })
   .exec(function(err, docs) {});

How to initialize java.util.date to empty

Try initializing with null value.

private java.util.Date date2 = null;

Also private java.util.Date date2 = ""; will not work as "" is a string.

Any implementation of Ordered Set in Java?

IndexedTreeSet from the indexed-tree-map project provides this functionality (ordered/sorted set with list-like access by index).

Django set default form values

As explained in Django docs, initial is not default.

  • The initial value of a field is intended to be displayed in an HTML . But if the user delete this value, and finally send back a blank value for this field, the initial value is lost. So you do not obtain what is expected by a default behaviour.

  • The default behaviour is : the value that validation process will take if data argument do not contain any value for the field.

To implement that, a straightforward way is to combine initial and clean_<field>():

class JournalForm(ModelForm):
    tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123) 

    (...)

    def clean_tank(self):
        if not self['tank'].html_name in self.data:
            return self.fields['tank'].initial
        return self.cleaned_data['tank']

What happened to the .pull-left and .pull-right classes in Bootstrap 4?

Update 2021, Bootstrap 5

In bootstrap 5 these classes have been renamed to .float-end and .float-start.

Docs: https://getbootstrap.com/docs/5.0/utilities/float/

Example:

<div class="row">
    <div class="col-12">
       <button class="btn btn-primary float-end">Login</div>
    </div>
</div>

How do you get the length of a string?

You don't need jquery, just use yourstring.length. See reference here and also here.

Update:

To support unicode strings, length need to be computed as following:

[...""].length

or create an auxiliary function

function uniLen(s) {
    return [...s].length
}

Is there an addHeaderView equivalent for RecyclerView?

Easy and reusable ItemDecoration

Static headers can easily be added with an ItemDecoration and without any further changes.

// add the decoration. done.
HeaderDecoration headerDecoration = new HeaderDecoration(/* init */);
recyclerView.addItemDecoration(headerDecoration);

The decoration is also reusable since there is no need to modify the adapter or the RecyclerView at all.

The sample code provided below will require a view to add to the top which can just be inflated like everything else. It can look like this:

HeaderDecoration sample

Why static?

If you just have to display text and images this solution is for you—there is no possibility for user interaction like buttons or view pagers, since it will just be drawn to top of your list.

Empty list handling

If there is no view to decorate, the decoration will not be drawn. You will still have to handle an empty list yourself. (One possible workaround would be to add a dummy item to the adapter.)

The code

You can find the full source code here on GitHub including a Builder to help with the initialization of the decorator, or just use the code below and supply your own values to the constructor.

Please be sure to set a correct layout_height for your view. e.g. match_parent might not work properly.

public class HeaderDecoration extends RecyclerView.ItemDecoration {

    private final View mView;
    private final boolean mHorizontal;
    private final float mParallax;
    private final float mShadowSize;
    private final int mColumns;
    private final Paint mShadowPaint;

    public HeaderDecoration(View view, boolean scrollsHorizontally, float parallax, float shadowSize, int columns) {
        mView = view;
        mHorizontal = scrollsHorizontally;
        mParallax = parallax;
        mShadowSize = shadowSize;
        mColumns = columns;

        if (mShadowSize > 0) {
            mShadowPaint = new Paint();
            mShadowPaint.setShader(mHorizontal ?
                    new LinearGradient(mShadowSize, 0, 0, 0,
                            new int[]{Color.argb(55, 0, 0, 0), Color.argb(55, 0, 0, 0), Color.argb(3, 0, 0, 0)},
                            new float[]{0f, .5f, 1f},
                            Shader.TileMode.CLAMP) :
                    new LinearGradient(0, mShadowSize, 0, 0,
                            new int[]{Color.argb(55, 0, 0, 0), Color.argb(55, 0, 0, 0), Color.argb(3, 0, 0, 0)},
                            new float[]{0f, .5f, 1f},
                            Shader.TileMode.CLAMP));
        } else {
            mShadowPaint = null;
        }
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        // layout basically just gets drawn on the reserved space on top of the first view
        mView.layout(parent.getLeft(), 0, parent.getRight(), mView.getMeasuredHeight());

        for (int i = 0; i < parent.getChildCount(); i++) {
            View view = parent.getChildAt(i);
            if (parent.getChildAdapterPosition(view) == 0) {
                c.save();
                if (mHorizontal) {
                    c.clipRect(parent.getLeft(), parent.getTop(), view.getLeft(), parent.getBottom());
                    final int width = mView.getMeasuredWidth();
                    final float left = (view.getLeft() - width) * mParallax;
                    c.translate(left, 0);
                    mView.draw(c);
                    if (mShadowSize > 0) {
                        c.translate(view.getLeft() - left - mShadowSize, 0);
                        c.drawRect(parent.getLeft(), parent.getTop(), mShadowSize, parent.getBottom(), mShadowPaint);
                    }
                } else {
                    c.clipRect(parent.getLeft(), parent.getTop(), parent.getRight(), view.getTop());
                    final int height = mView.getMeasuredHeight();
                    final float top = (view.getTop() - height) * mParallax;
                    c.translate(0, top);
                    mView.draw(c);
                    if (mShadowSize > 0) {
                        c.translate(0, view.getTop() - top - mShadowSize);
                        c.drawRect(parent.getLeft(), parent.getTop(), parent.getRight(), mShadowSize, mShadowPaint);
                    }
                }
                c.restore();
                break;
            }
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        if (parent.getChildAdapterPosition(view) < mColumns) {
            if (mHorizontal) {
                if (mView.getMeasuredWidth() <= 0) {
                    mView.measure(View.MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth(), View.MeasureSpec.AT_MOST),
                            View.MeasureSpec.makeMeasureSpec(parent.getMeasuredHeight(), View.MeasureSpec.AT_MOST));
                }
                outRect.set(mView.getMeasuredWidth(), 0, 0, 0);
            } else {
                if (mView.getMeasuredHeight() <= 0) {
                    mView.measure(View.MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth(), View.MeasureSpec.AT_MOST),
                            View.MeasureSpec.makeMeasureSpec(parent.getMeasuredHeight(), View.MeasureSpec.AT_MOST));
                }
                outRect.set(0, mView.getMeasuredHeight(), 0, 0);
            }
        } else {
            outRect.setEmpty();
        }
    }
}

Please note: The GitHub project is my personal playground. It is not thorougly tested, which is why there is no library yet.

What does it do?

An ItemDecoration is additional drawing to an item of a list. In this case, a decoration is drawn to the top of the first item.

The view gets measured and laid out, then it is drawn to the top of the first item. If a parallax effect is added it will also be clipped to the correct bounds.

How to include *.so library in Android Studio?

Current Solution

Create the folder project/app/src/main/jniLibs, and then put your *.so files within their abi folders in that location. E.g.,

project/
+--libs/
|  +-- *.jar       <-- if your library has jar files, they go here
+--src/
   +-- main/
       +-- AndroidManifest.xml
       +-- java/
       +-- jniLibs/ 
           +-- arm64-v8a/                       <-- ARM 64bit
           ¦   +-- yourlib.so
           +-- armeabi-v7a/                     <-- ARM 32bit
           ¦   +-- yourlib.so
           +-- x86/                             <-- Intel 32bit
               +-- yourlib.so

Deprecated solution

Add both code snippets in your module gradle.build file as a dependency:

compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')

How to create this custom jar:

task nativeLibsToJar(type: Jar, description: 'create a jar archive of the native libs') {
    destinationDir file("$buildDir/native-libs")
    baseName 'native-libs'
    from fileTree(dir: 'libs', include: '**/*.so')
    into 'lib/'
}

tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn(nativeLibsToJar)
}

Same answer can also be found in related question: Include .so library in apk in android studio

UTF-8 encoding in JSP page

Page encoding or anything else do not matter a lot. ISO-8859-1 is a subset of UTF-8, therefore you never have to convert ISO-8859-1 to UTF-8 because ISO-8859-1 is already UTF-8,a subset of UTF-8 but still UTF-8. Plus, all that do not mean a thing if You have a double encoding somewhere. This is my "cure all" recipe for all things encoding and charset related:

        String myString = "heartbroken ð";

//String is double encoded, fix that first.

                myString = new String(myString.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                String cleanedText = StringEscapeUtils.unescapeJava(myString);
                byte[] bytes = cleanedText.getBytes(StandardCharsets.UTF_8);
                String text = new String(bytes, StandardCharsets.UTF_8);
                Charset charset = Charset.forName("UTF-8");
                CharsetDecoder decoder = charset.newDecoder();
                decoder.onMalformedInput(CodingErrorAction.IGNORE);
                decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
                CharsetEncoder encoder = charset.newEncoder();
                encoder.onMalformedInput(CodingErrorAction.IGNORE);
                encoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
                try {
                    // The new ByteBuffer is ready to be read.
                    ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(text));
                    // The new ByteBuffer is ready to be read.
                    CharBuffer cbuf = decoder.decode(bbuf);
                    String str = cbuf.toString();
                } catch (CharacterCodingException e) {
                    logger.error("Error Message if you want to");

                } 

jQuery get an element by its data-id

$('[data-item-id="stand-out"]')

How to make several plots on a single page using matplotlib?

This works also:

for i in range(19):
    plt.subplot(5,4,i+1) 

It plots 19 total graphs on one page. The format is 5 down and 4 across..

Select info from table where row has max date

SELECT group,MAX(date) as max_date
FROM table
WHERE checks>0
GROUP BY group

That works to get the max date..join it back to your data to get the other columns:

Select group,max_date,checks
from table t
inner join 
(SELECT group,MAX(date) as max_date
FROM table
WHERE checks>0
GROUP BY group)a
on a.group = t.group and a.max_date = date

Inner join functions as the filter to get the max record only.

FYI, your column names are horrid, don't use reserved words for columns (group, date, table).

Convert string to datetime in vb.net

You can try with ParseExact method

Sample

Dim format As String  
format = "d" 
Dim provider As CultureInfo = CultureInfo.InvariantCulture
result = Date.ParseExact(DateString, format, provider)

PHP Call to undefined function

Your function is probably in a different namespace than the one you're calling it from.

http://php.net/manual/en/language.namespaces.basics.php