Programs & Examples On #Audio analysis

What's the difference between commit() and apply() in SharedPreferences

The difference between commit() and apply()

We might be confused by those two terms, when we are using SharedPreference. Basically they are probably the same, so let’s clarify the differences of commit() and apply().

1.Return value:

apply() commits without returning a boolean indicating success or failure. commit() returns true if the save works, false otherwise.

  1. Speed:

apply() is faster. commit() is slower.

  1. Asynchronous v.s. Synchronous:

apply(): Asynchronous commit(): Synchronous

  1. Atomic:

apply(): atomic commit(): atomic

  1. Error notification:

apply(): No commit(): Yes

What's the difference between passing by reference vs. passing by value?

Here is an example:

#include <iostream>

void by_val(int arg) { arg += 2; }
void by_ref(int&arg) { arg += 2; }

int main()
{
    int x = 0;
    by_val(x); std::cout << x << std::endl;  // prints 0
    by_ref(x); std::cout << x << std::endl;  // prints 2

    int y = 0;
    by_ref(y); std::cout << y << std::endl;  // prints 2
    by_val(y); std::cout << y << std::endl;  // prints 2
}

Class has no objects member

I installed PyLint but I was having the error Missing module docstringpylint(missing-module-docstring). So I found this answer with this config for pylint :

"python.linting.pylintEnabled": true,
"python.linting.pylintArgs": [
    "--disable=C0111", // missing docstring
    "--load-plugins=pylint_django,pylint_celery",
 ],

And now it works

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

You can implement this with a new Html helper extension function which will then be used similarly to the existing ActionLinks.

public static MvcHtmlString ActionLinkHtml5Data(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes, object htmlDataAttributes)
{
    if (string.IsNullOrEmpty(linkText))
    {
        throw new ArgumentException(string.Empty, "linkText");
    }

    var html = new RouteValueDictionary(htmlAttributes);
    var data = new RouteValueDictionary(htmlDataAttributes);

    foreach (var attributes in data)
    {
        html.Add(string.Format("data-{0}", attributes.Key), attributes.Value);
    }

    return MvcHtmlString.Create(HtmlHelper.GenerateLink(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection, linkText, null, actionName, controllerName, new RouteValueDictionary(routeValues), html));
}

And you call it like so ...

<%: Html.ActionLinkHtml5Data("link display", "Action", "Controller", new { id = Model.Id }, new { @class="link" }, new { extra = "some extra info" })  %>

Simples :-)

edit

bit more of a write up here

Eclipse error, "The selection cannot be launched, and there are no recent launches"

Eclipse can't work out what you want to run and since you've not run anything before, it can't try re-running that either.

Instead of clicking the green 'run' button, click the dropdown next to it and chose Run Configurations. On the Android tab, make sure it's set to your project. In the Target tab, set the tick box and options as appropriate to target your device. Then click Run. Keep an eye on your Console tab in Eclipse - that'll let you know what's going on. Once you've got your run configuration set, you can just hit the green 'run' button next time.

Sometimes getting everything to talk to your device can be problematic to begin with. Consider using an AVD (i.e. an emulator) as alternative, at least to begin with if you have problems. You can easily create one from the menu Window -> Android Virtual Device Manager within Eclipse.

To view the progress of your project being installed and started on your device, check the console. It's a panel within Eclipse with the tabs Problems/Javadoc/Declaration/Console/LogCat etc. It may be minimised - check the tray in the bottom right. Or just use Window/Show View/Console from the menu to make it come to the front. There are two consoles, Android and DDMS - there is a dropdown by its icon where you can switch.

Java function for arrays like PHP's join()?

Starting from Java8 it is possible to use String.join().

String.join(", ", new String[]{"Hello", "World", "!"})

Generates:

Hello, World, !

Otherwise, Apache Commons Lang has a StringUtils class which has a join function which will join arrays together to make a String.

For example:

StringUtils.join(new String[] {"Hello", "World", "!"}, ", ")

Generates the following String:

Hello, World, !

Position of a string within a string using Linux shell script?

With bash

a="The cat sat on the mat"
b=cat
strindex() { 
  x="${1%%$2*}"
  [[ "$x" = "$1" ]] && echo -1 || echo "${#x}"
}
strindex "$a" "$b"   # prints 4
strindex "$a" foo    # prints -1

Pass user defined environment variable to tomcat

For Unix & Mac systems, Go to /bin/setenv.sh inside tomcat folder

Add the below line

export JAVA_OPTS="$JAVA_OPTS -DAPP_MASTER_PASSWORD=mypass"

Now System.getProperty("APP_MASTER_PASSWORD") will return "mypass"

How to create a directory and give permission in single command

install -d -m 0777 /your/dir

should give you what you want. Be aware that every user has the right to write add and delete files in that directory.

Can I pass parameters in computed properties in Vue.Js

computed: {
  fullName: (app)=> (salut)=> {
      return salut + ' ' + this.firstName + ' ' + this.lastName    
  }
}

when you want use

<p>{{fullName('your salut')}}</p>

Unicode character for "X" cancel / close?

This works nicely for me:

<style>
a.closeX {
    position: absolute;
    right: 0px; top: 0px; width:20px;
    background-color: #FFF; color: black;
    margin-top:-15px; margin-right:-15px; border-radius: 20px;
    padding-left: 3px; padding-top: 1px;
    cursor:pointer; z-index: -1;
    font-size:16px; font-weight:bold;
}
</style>
<div id="content">
    <a class="closeX" id="closeX" onclick='$("#content").hide();'>&#10006;</a>
    Click "X" to close this box
</div>

Does bootstrap have builtin padding and margin classes?

I think what you're asking about is how to create responsive spacing between rows or col-xx-xx classes.

You can definitely do this with the col-xx-offset-xx class:

<div class="col-xs-4">
</div>

<div class="col-xs-7 col-xs-offset-1">
</div>

As for adding margin or padding directly to elements, there are some simple ways to do this depending on your element. You can use btn-lg or label-lg or well-lg. If you're ever wondering, how can i give this alittle padding. Try adding the primary class name + lg or sm or md depending on your size needs:

<button class="btn btn-success btn-lg btn-block">Big Button w/ Display: Block</button>

Celery Received unregistered task of type (run example)

Just to add my two cents for my case with this error...

My path is /vagrant/devops/test with app.py and __init__.py in it.

When I run cd /vagrant/devops/ && celery worker -A test.app.celery --loglevel=info I am getting this error.

But when I run it like cd /vagrant/devops/test && celery worker -A app.celery --loglevel=info everything is OK.

How to fetch Java version using single line command in Linux

Since (at least on my linux system) the version string looks like "1.8.0_45":

 #!/bin/bash
 function checkJavaVers {
    for token in $(java -version 2>&1)
    do
        if [[ $token =~ \"([[:digit:]])\.([[:digit:]])\.(.*)\" ]]
        then
            export JAVA_MAJOR=${BASH_REMATCH[1]}
            export JAVA_MINOR=${BASH_REMATCH[2]}
            export JAVA_BUILD=${BASH_REMATCH[3]}
            return 0
        fi
    done
    return 1
}

#test
checkJavaVers || { echo "check failed" ; exit; }
echo "$JAVA_MAJOR $JAVA_MINOR $JAVA_BUILD"
~

Getting "project" nuget configuration is invalid error

NOTE: This is mentioned in the question but restarting Visual Studio fixes the issue in most cases.

Updating Visual Studio to 'Update 2' got it working again.

Tools -> Extensions and Updates ->Visual Studio Update 2

As mentioned in the question and the link i posted therein, I'd already updated NuGet Package Manager to 3.4.4 prior to this and restarted to no avail, so I don't know if the combination of both these actions worked.

Find row where values for column is maximal in a pandas DataFrame

The idmax of the DataFrame returns the label index of the row with the maximum value and the behavior of argmax depends on version of pandas (right now it returns a warning). If you want to use the positional index, you can do the following:

max_row = df['A'].values.argmax()

or

import numpy as np
max_row = np.argmax(df['A'].values)

Note that if you use np.argmax(df['A']) behaves the same as df['A'].argmax().

JQuery - Get select value

var nationality = $("#dancerCountry").val(); should work. Are you sure that the element selector is working properly? Perhaps you should try:

var nationality = $('select[name="dancerCountry"]').val();

When to use Interface and Model in TypeScript / Angular

Use Class instead of Interface that is what I discovered after all my research.

Why? A class alone is less code than a class-plus-interface. (anyway you may require a Class for data model)

Why? A class can act as an interface (use implements instead of extends).

Why? An interface-class can be a provider lookup token in Angular dependency injection.

from Angular Style Guide

Basically a Class can do all, what an Interface will do. So may never need to use an Interface.

How to align texts inside of an input?

Try this in your CSS:

input {
text-align: right;
}

To align the text in the center:

input {
text-align: center;
}

But, it should be left-aligned, as that is the default - and appears to be the most user friendly.

Correct way to write line to file?

You can also try filewriter

pip install filewriter

from filewriter import Writer

Writer(filename='my_file', ext='txt') << ["row 1 hi there", "row 2"]

Writes into my_file.txt

Takes an iterable or an object with __str__ support.

Git - How to close commit editor?

Not sure the key combination that gets you there to the > prompt but it is not a bash prompt that I know. I usually get it by accident. Ctrl+C (or D) gets me back to the $ prompt.

Loading context in Spring using web.xml

From the spring docs

Spring can be easily integrated into any Java-based web framework. All you need to do is to declare the ContextLoaderListener in your web.xml and use a contextConfigLocation to set which context files to load.

The <context-param>:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

<listener>
   <listener-class>
        org.springframework.web.context.ContextLoaderListener
   </listener-class>
</listener> 

You can then use the WebApplicationContext to get a handle on your beans.

WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext());
SomeBean someBean = (SomeBean) ctx.getBean("someBean");

See http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/support/WebApplicationContextUtils.html for more info

How can I plot with 2 different y-axes?

One option is to make two plots side by side. ggplot2 provides a nice option for this with facet_wrap():

dat <- data.frame(x = c(rnorm(100), rnorm(100, 10, 2))
  , y = c(rnorm(100), rlnorm(100, 9, 2))
  , index = rep(1:2, each = 100)
  )

require(ggplot2)
ggplot(dat, aes(x,y)) + 
geom_point() + 
facet_wrap(~ index, scales = "free_y")

XAMPP - MySQL shutdown unexpectedly

That's the more precise answer and worked for me!!!! ! A cleaner way of undoing the damage is to revert your whole /mysql/data/ folder. Windows has built-in folder versioning — right click on /mysql/data/ and select Restore previous versions. You can then delete the current contents of the folder and replace it with the older version's contents. as mentioned above by Ryan Williams.

jQuery selector for id starts with specific text

If all your divs start with editDialog as you stated, then you can use the following selector:

$("div[id^='editDialog']")

Or you could use a class selector instead if it's easier for you

<div id="editDialog-0" class="editDialog">...</div>

$(".editDialog")

How do I use hexadecimal color strings in Flutter?

I missed the obvious answer using hex numbers for the fromRGB constructor:

Color.fromRGBO(0xb7, 0x40, 0x93, 1),

XAMPP - Port 80 in use by "Unable to open process" with PID 4! 12

I've had same problem, when I was installed MS WebMatrix, IIS Server was blocked the port 80 which XAMPP was running on. I tried to find World Wide Web Publishing Service and stop it, but could not find it on list. Best way is changing a port.

Please refer with this
link ref.

What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

HTML/CSS Approach

If you are looking for an option that does not require much JavaScript (and and all the problems that come with it, such as rapid scroll event calls), it is possible to gain the same behavior by adding a wrapper <div> and a couple of styles. I noticed much smoother scrolling (no elements lagging behind) when I used the following approach:

JS Fiddle

HTML

<div id="wrapper">
  <div id="fixed">
    [Fixed Content]
  </div><!-- /fixed -->
  <div id="scroller">
    [Scrolling Content]
  </div><!-- /scroller -->
</div><!-- /wrapper -->

CSS

#wrapper { position: relative; }
#fixed { position: fixed; top: 0; right: 0; }
#scroller { height: 100px; overflow: auto; }

JS

//Compensate for the scrollbar (otherwise #fixed will be positioned over it).
$(function() {
  //Determine the difference in widths between
  //the wrapper and the scroller. This value is
  //the width of the scroll bar (if any).
  var offset = $('#wrapper').width() - $('#scroller').get(0).clientWidth;

  //Set the right offset
  $('#fixed').css('right', offset + 'px');?
});

Of course, this approach could be modified for scrolling regions that gain/lose content during runtime (which would result in addition/removal of scrollbars).

Bold & Non-Bold Text In A Single UILabel?

Try a category on UILabel:

Here's how it's used:

myLabel.text = @"Updated: 2012/10/14 21:59 PM";
[myLabel boldSubstring: @"Updated:"];
[myLabel boldSubstring: @"21:59 PM"];

And here's the category

UILabel+Boldify.h

- (void) boldSubstring: (NSString*) substring;
- (void) boldRange: (NSRange) range;

UILabel+Boldify.m

- (void) boldRange: (NSRange) range {
    if (![self respondsToSelector:@selector(setAttributedText:)]) {
        return;
    }
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    [attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:self.font.pointSize]} range:range];

    self.attributedText = attributedText;    
}

- (void) boldSubstring: (NSString*) substring {
    NSRange range = [self.text rangeOfString:substring];
    [self boldRange:range];
}

Note that this will only work in iOS 6 and later. It will simply be ignored in iOS 5 and earlier.

Is there a maximum number you can set Xmx to when trying to increase jvm memory?

I think that it's around 2GB. While the answer by Pete Kirkham is very interesting and probably holds truth, I have allocated upwards of 3GB without error, however it did not use 3GB in practice. That might explain why you were able to allocate 2.5 GB on 2GB RAM with no swap space. In practice, it wasn't using 2.5GB.

How to make google spreadsheet refresh itself every 1 minute?

If you're on the New Google Sheets, this is all you need to do, according to the docs:

change your recalculation setting to "On change and every minute" in your spreadsheet at File > Spreadsheet settings.

This will make the entire sheet update itself every minute, on the server side, regardless of whether you have the spreadsheet up in your browser or not.

If you're on the old Google Sheets, you'll want to add a cell with this formula to achieve the same functionality:

=GoogleClock()

EDIT to include old and new Google Sheets and change to =GoogleClock().

How to "comment-out" (add comment) in a batch/cmd?

You can use :: or rem for comments.

When commenting, use :: as it's 3 times faster. An example is shown here

Only if comments are in if, use rem, as the colons could make errors, because they are a label.

What is an idempotent operation?

No matter how many times you call the operation, the result will be the same.

Moment.js with ReactJS (ES6)

I'm using moment in my react project

import moment from 'moment'

state = {
    startDate: moment()
};
render() {
    const selectedDate = this.state.startDate.format("Do MMMM YYYY");
    return(
     <Fragment>
       {selectedDate)
     </Fragment>
   );
}

How to save .xlsx data to file as a blob

The answer above is correct. Please be sure that you have a string data in base64 in the data variable without any prefix or stuff like that just raw data.

Here's what I did on the server side (asp.net mvc core):

string path = Path.Combine(folder, fileName);
Byte[] bytes = System.IO.File.ReadAllBytes(path);
string base64 = Convert.ToBase64String(bytes);

On the client side, I did the following code:

const xhr = new XMLHttpRequest();

xhr.open("GET", url);
xhr.setRequestHeader("Content-Type", "text/plain");

xhr.onload = () => {
    var bin = atob(xhr.response);
    var ab = s2ab(bin); // from example above
    var blob = new Blob([ab], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' });

    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = 'demo.xlsx';

    document.body.appendChild(link);

    link.click();

    document.body.removeChild(link);
};

xhr.send();

And it works perfectly for me.

get url content PHP

Try using cURL instead. cURL implements a cookie jar, while file_get_contents doesn't.

How do I choose grid and block dimensions for CUDA kernels?

The blocksize is usually selected to maximize the "occupancy". Search on CUDA Occupancy for more information. In particular, see the CUDA Occupancy Calculator spreadsheet.

Create thumbnail image

The following code will write an image in proportional to the response, you can modify the code for your purpose:

public void WriteImage(string path, int width, int height)
{
    Bitmap srcBmp = new Bitmap(path);
    float ratio = srcBmp.Width / srcBmp.Height;
    SizeF newSize = new SizeF(width, height * ratio);
    Bitmap target = new Bitmap((int) newSize.Width,(int) newSize.Height);
    HttpContext.Response.Clear();
    HttpContext.Response.ContentType = "image/jpeg";
    using (Graphics graphics = Graphics.FromImage(target))
    {
        graphics.CompositingQuality = CompositingQuality.HighSpeed;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.CompositingMode = CompositingMode.SourceCopy;
        graphics.DrawImage(srcBmp, 0, 0, newSize.Width, newSize.Height);
        using (MemoryStream memoryStream = new MemoryStream()) 
        {
            target.Save(memoryStream, ImageFormat.Jpeg);
            memoryStream.WriteTo(HttpContext.Response.OutputStream);
        }
    }
    Response.End();
}

Sort a Map<Key, Value> by values

Okay, this version works with two new Map objects and two iterations and sorts on values. Hope, the performs well although the map entries must be looped twice:

public static void main(String[] args) {
    Map<String, String> unsorted = new HashMap<String, String>();
    unsorted.put("Cde", "Cde_Value");
    unsorted.put("Abc", "Abc_Value");
    unsorted.put("Bcd", "Bcd_Value");

    Comparator<String> comparer = new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return o1.compareTo(o2);
        }};

    System.out.println(sortByValue(unsorted, comparer));

}

public static <K, V> Map<K,V> sortByValue(Map<K, V> in, Comparator<? super V> compare) {
    Map<V, K> swapped = new TreeMap<V, K>(compare);
    for(Entry<K,V> entry: in.entrySet()) {
        if (entry.getValue() != null) {
            swapped.put(entry.getValue(), entry.getKey());
        }
    }
    LinkedHashMap<K, V> result = new LinkedHashMap<K, V>();
    for(Entry<V,K> entry: swapped.entrySet()) {
        if (entry.getValue() != null) {
            result.put(entry.getValue(), entry.getKey());
        }
    }
    return result;
}

The solution uses a TreeMap with a Comparator and sorts out all null keys and values. First, the ordering functionality from the TreeMap is used to sort upon the values, next the sorted Map is used to create a result as a LinkedHashMap that retains has the same order of values.

Greetz, GHad

Python send UDP packet

If you are running python 3 then you need to change the print statements to print functions, i.e. put things in brackets () after print statements.

The only thing that you will see the above do is the prints unless you have something listening on 127.0.0.1 port 5005 as you are sending a packet not receiving it - so you need to implement and start the other part of the example in another console window first so it is waiting for the message.

How to convert a number to string and vice versa in C++

#include <iostream>
#include <string.h>
using namespace std;
int main() {
   string s="000101";
   cout<<s<<"\n";
   int a = stoi(s);
   cout<<a<<"\n";
   s=to_string(a);
   s+='1';
   cout<<s;
   return 0;
}

Output:

  • 000101
  • 101
  • 1011

how to output every line in a file python

Loop through the file.

f = open("masters.txt")
lines = f.readlines()
for line in lines:
    print line

Fill drop down list on selection of another drop down list

enter image description here

enter image description here

enter image description here

Model:

namespace MvcApplicationrazor.Models
{
    public class CountryModel
    {
        public List<State> StateModel { get; set; }
        public SelectList FilteredCity { get; set; }
    }
    public class State
    {
        public int Id { get; set; }
        public string StateName { get; set; }
    }
    public class City
    {
        public int Id { get; set; }
        public int StateId { get; set; }
        public string CityName { get; set; }
    }
}   

Controller:

public ActionResult Index()
        {
            CountryModel objcountrymodel = new CountryModel();
            objcountrymodel.StateModel = new List<State>();
            objcountrymodel.StateModel = GetAllState();
            return View(objcountrymodel);
        }


        //Action result for ajax call
        [HttpPost]
        public ActionResult GetCityByStateId(int stateid)
        {
            List<City> objcity = new List<City>();
            objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
            SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
            return Json(obgcity);
        }
        // Collection for state
        public List<State> GetAllState()
        {
            List<State> objstate = new List<State>();
            objstate.Add(new State { Id = 0, StateName = "Select State" });
            objstate.Add(new State { Id = 1, StateName = "State 1" });
            objstate.Add(new State { Id = 2, StateName = "State 2" });
            objstate.Add(new State { Id = 3, StateName = "State 3" });
            objstate.Add(new State { Id = 4, StateName = "State 4" });
            return objstate;
        }
        //collection for city
        public List<City> GetAllCity()
        {
            List<City> objcity = new List<City>();
            objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
            objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
            objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
            objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
            objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
            objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
            return objcity;
        }

View:

@model MvcApplicationrazor.Models.CountryModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
    function GetCity(_stateId) {
        var procemessage = "<option value='0'> Please wait...</option>";
        $("#ddlcity").html(procemessage).show();
        var url = "/Test/GetCityByStateId/";

        $.ajax({
            url: url,
            data: { stateid: _stateId },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value='0'>Select City</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $("#ddlcity").html(markup).show();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });

    }
</script>
<h4>
 MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
    @Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
    <br />
    <br />
    <select id="ddlcity" name="ddlcity" style="width: 200px">

    </select>

    <br /><br />
  }

How do I concatenate multiple C++ strings on one line?

Maybe you like my "Streamer" solution to really do it in one line:

#include <iostream>
#include <sstream>
using namespace std;

class Streamer // class for one line string generation
{
public:

    Streamer& clear() // clear content
    {
        ss.str(""); // set to empty string
        ss.clear(); // clear error flags
        return *this;
    }

    template <typename T>
    friend Streamer& operator<<(Streamer& streamer,T str); // add to streamer

    string str() // get current string
    { return ss.str();}

private:
    stringstream ss;
};

template <typename T>
Streamer& operator<<(Streamer& streamer,T str)
{ streamer.ss<<str;return streamer;}

Streamer streamer; // make this a global variable


class MyTestClass // just a test class
{
public:
    MyTestClass() : data(0.12345){}
    friend ostream& operator<<(ostream& os,const MyTestClass& myClass);
private:
    double data;
};

ostream& operator<<(ostream& os,const MyTestClass& myClass) // print test class
{ return os<<myClass.data;}


int main()
{
    int i=0;
    string s1=(streamer.clear()<<"foo"<<"bar"<<"test").str();                      // test strings
    string s2=(streamer.clear()<<"i:"<<i++<<" "<<i++<<" "<<i++<<" "<<0.666).str(); // test numbers
    string s3=(streamer.clear()<<"test class:"<<MyTestClass()).str();              // test with test class
    cout<<"s1: '"<<s1<<"'"<<endl;
    cout<<"s2: '"<<s2<<"'"<<endl;
    cout<<"s3: '"<<s3<<"'"<<endl;
}

How to get the Development/Staging/production Hosting Environment in ConfigureServices

You can easily access it in ConfigureServices, just persist it to a property during Startup method which is called first and gets it passed in, then you can access the property from ConfigureServices.

public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
    ...your code here...
    CurrentEnvironment = env;
}

private IHostingEnvironment CurrentEnvironment{ get; set; } 

public void ConfigureServices(IServiceCollection services)
{
    string envName = CurrentEnvironment.EnvironmentName;
    ... your code here...
}

NSURLErrorDomain error codes description

IN SWIFT 3. Here are the NSURLErrorDomain error codes description in a Swift 3 enum: (copied from answer above and converted what i can).

enum NSURLError: Int {
    case unknown = -1
    case cancelled = -999
    case badURL = -1000
    case timedOut = -1001
    case unsupportedURL = -1002
    case cannotFindHost = -1003
    case cannotConnectToHost = -1004
    case connectionLost = -1005
    case lookupFailed = -1006
    case HTTPTooManyRedirects = -1007
    case resourceUnavailable = -1008
    case notConnectedToInternet = -1009
    case redirectToNonExistentLocation = -1010
    case badServerResponse = -1011
    case userCancelledAuthentication = -1012
    case userAuthenticationRequired = -1013
    case zeroByteResource = -1014
    case cannotDecodeRawData = -1015
    case cannotDecodeContentData = -1016
    case cannotParseResponse = -1017
    //case NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022
    case fileDoesNotExist = -1100
    case fileIsDirectory = -1101
    case noPermissionsToReadFile = -1102
    //case NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) =   -1103

    // SSL errors
    case secureConnectionFailed = -1200
    case serverCertificateHasBadDate = -1201
    case serverCertificateUntrusted = -1202
    case serverCertificateHasUnknownRoot = -1203
    case serverCertificateNotYetValid = -1204
    case clientCertificateRejected = -1205
    case clientCertificateRequired = -1206
    case cannotLoadFromNetwork = -2000

    // Download and file I/O errors
    case cannotCreateFile = -3000
    case cannotOpenFile = -3001
    case cannotCloseFile = -3002
    case cannotWriteToFile = -3003
    case cannotRemoveFile = -3004
    case cannotMoveFile = -3005
    case downloadDecodingFailedMidStream = -3006
    case downloadDecodingFailedToComplete = -3007

    /*
     case NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) =         -1018
     case NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) =                    -1019
     case NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) =                  -1020
     case NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) =      -1021

     case NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995
     case NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996
     case NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997
     */
}

Direct link to URLError.Code in the Swift github repository, which contains the up to date list of error codes being used (github link).

How to read if a checkbox is checked in PHP?

If your HTML page looks like this:

<input type="checkbox" name="test" value="value1">

After submitting the form you can check it with:

isset($_POST['test'])

or

if ($_POST['test'] == 'value1') ...

C# 30 Days From Todays Date

string[] servers = new string[] {
        "nist1-ny.ustiming.org",
        "nist1-nj.ustiming.org",
        "nist1-pa.ustiming.org",
        "time-a.nist.gov",
        "time-b.nist.gov",
        "nist1.aol-va.symmetricom.com",
        "nist1.columbiacountyga.gov",
        "nist1-chi.ustiming.org",
        "nist.expertsmi.com",
        "nist.netservicesgroup.com"
        };
string dateStart, dateEnd;

void SetDateToday()
    {
        Random rnd = new Random();
        DateTime result = new DateTime();
        int found = 0;
        foreach (string server in servers.OrderBy(s => rnd.NextDouble()).Take(5))
        {
            Console.Write(".");
            try
            {
                string serverResponse = string.Empty;
                using (var reader = new StreamReader(new System.Net.Sockets.TcpClient(server, 13).GetStream()))
                {
                    serverResponse = reader.ReadToEnd();
                    Console.WriteLine(serverResponse);
                }

                if (!string.IsNullOrEmpty(serverResponse))
                {
                    string[] tokens = serverResponse.Split(' ');
                    string[] date = tokens[1].Split(' ');
                    string time = tokens[2];
                    string properTime;

                    dateStart = date[2] + "/" + date[0] + "/" + date[1];

                    int month = Convert.ToInt16(date[0]), day = Convert.ToInt16(date[2]), year = Convert.ToInt16(date[1]);
                    day = day + 30;
                    if ((month % 2) == 0)
                    {
                        //MAX DAYS IS 30
                        if (day > 30)
                        {
                            day = day - 30;
                            month++;
                            if (month > 12)
                            {
                                month = 1;
                                year++;
                            }
                        }
                    }
                    else
                    {
                        //MAX DAYS IS 31
                        if (day > 31)
                        {
                            day = day - 31;
                            month++;
                            if (month > 12)
                            {
                                month = 1;
                                year++;
                            }
                        }
                    }
                    string sday, smonth;
                    if (day < 10)
                    {
                        sday = "0" + day;
                    }
                    if (month < 10)
                    {
                        smonth = "0" + month;
                    }
                    dateEnd = sday + "/" + smonth + "/" + year.ToString();

                }

            }
            catch
            {
                // Ignore exception and try the next server
            }
        }
        if (found == 0)
        {
            MessageBox.Show(this, "Internet Connection is required to complete Registration. Please check your internet connection and try again.", "Not connected", MessageBoxButtons.OK, MessageBoxIcon.Information);
            Success = false;
        }
    }

I saw that code in some part of some website. Doing the example above exposes a glitch: Changing the current Time and Date to the start date would prolong the application expiration.

The solution? Refer to a online time server.

CSS Animation onClick

You can achieve this by binding an onclick listener and then adding the animate class like this:

$('#button').onClick(function(){
    $('#target_element').addClass('animate_class_name');
});

Remove an item from an IEnumerable<T> collection

You can not remove an item from an IEnumerable; it can only be enumerated, as described here: http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx

You have to use an ICollection if you want to add and remove items. Maybe you can try and casting your IEnumerable; this will off course only work if the underlying object implements ICollection`.

See here for more on ICollection: http://msdn.microsoft.com/en-us/library/92t2ye13.aspx

You can, of course, just create a new list from your IEnumerable, as pointed out by lante, but this might be "sub optimal", depending on your actual use case, of course.

ICollection is probably the way to go.

C++ Fatal Error LNK1120: 1 unresolved externals

Well it seems that you are missing a reference to some library. I had the similar error solved it by adding a reference to the #pragma comment(lib, "windowscodecs.lib")

Difference between Relative path and absolute path in javascript

What is the difference between Relative path and absolute path?

One has to be calculated with respect to another URI. The other does not.

Is there any performance issues occures for using these paths?

Nothing significant.

We will get any secure for the sites ?

No

Is there any way to converting absolute path to relative

In really simplified terms: Working from left to right, try to match the scheme, hostname, then path segments with the URI you are trying to be relative to. Stop when you have a match.

How exactly does the python any() function work?

If you use any(lst) you see that lst is the iterable, which is a list of some items. If it contained [0, False, '', 0.0, [], {}, None] (which all have boolean values of False) then any(lst) would be False. If lst also contained any of the following [-1, True, "X", 0.00001] (all of which evaluate to True) then any(lst) would be True.

In the code you posted, x > 0 for x in lst, this is a different kind of iterable, called a generator expression. Before generator expressions were added to Python, you would have created a list comprehension, which looks very similar, but with surrounding []'s: [x > 0 for x in lst]. From the lst containing [-1, -2, 10, -4, 20], you would get this comprehended list: [False, False, True, False, True]. This internal value would then get passed to the any function, which would return True, since there is at least one True value.

But with generator expressions, Python no longer has to create that internal list of True(s) and False(s), the values will be generated as the any function iterates through the values generated one at a time by the generator expression. And, since any short-circuits, it will stop iterating as soon as it sees the first True value. This would be especially handy if you created lst using something like lst = range(-1,int(1e9)) (or xrange if you are using Python2.x). Even though this expression will generate over a billion entries, any only has to go as far as the third entry when it gets to 1, which evaluates True for x>0, and so any can return True.

If you had created a list comprehension, Python would first have had to create the billion-element list in memory, and then pass that to any. But by using a generator expression, you can have Python's builtin functions like any and all break out early, as soon as a True or False value is seen.

JSONObject - How to get a value?

String loudScreaming = json.getJSONObject("LabelData").getString("slogan");

Create a data.frame with m columns and 2 rows

For completeness:

Along the lines of Chase's answer, I usually use as.data.frame to coerce the matrix to a data.frame:

m <- as.data.frame(matrix(0, ncol = 30, nrow = 2))

EDIT: speed test data.frame vs. as.data.frame

system.time(replicate(10000, data.frame(matrix(0, ncol = 30, nrow = 2))))
   user  system elapsed 
  8.005   0.108   8.165 

system.time(replicate(10000, as.data.frame(matrix(0, ncol = 30, nrow = 2))))
   user  system elapsed 
  3.759   0.048   3.802 

Yes, it appears to be faster (by about 2 times).

How to read data From *.CSV file using javascript?

Actually you can use a light-weight library called any-text.

  • install dependencies
npm i -D any-text
  • use custom command to read files
var reader = require('any-text');
 
reader.getText(`path-to-file`).then(function (data) {
  console.log(data);
});

or use async-await :

var reader = require('any-text');
 
const chai = require('chai');
const expect = chai.expect;
 
describe('file reader checks', () => {
  it('check csv file content', async () => {
    expect(
      await reader.getText(`${process.cwd()}/test/files/dummy.csv`)
    ).to.contains('Lorem ipsum');
  });
});

Sending SOAP request using Python Requests

It is indeed possible.

Here is an example calling the Weather SOAP Service using plain requests lib:

import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
         <SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <SOAP-ENV:Header/>
              <ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
         </SOAP-ENV:Envelope>"""

response = requests.post(url,data=body,headers=headers)
print response.content

Some notes:

  • The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xml is probably the more correct header to use (but the weatherservice prefers text/xml
  • This will return the response as a string of xml - you would then need to parse that xml.
  • For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.

For example:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()

Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).

You can do the above with suds like so:

from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service

result = client.service.GetWeatherInformation() 
print result 

Note: when using suds, you will almost always end up needing to use the doctor!

Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:

sudo tcpdump -As 0 

This can be helpful for inspecting the requests that actually go over the wire.

The above two code snippets are also available as gists:

Why can't Visual Studio find my DLL?

try "configuration properties -> debugging -> environment" and set the PATH variable in run-time

CSS: Truncate table cells, but fit as much as possible

I believe I have a non-javascript solution! Better late than never, right? After all this is an excellent question and Google is all over it. I didn't want to settle for a javascript fix because I find the slight jitter of things moving around after the page is loaded to be unacceptable.

Features:

  • No javascript
  • No fixed-layout
  • No weighting or percentage-width tricks
  • Works with any number of columns
  • Simple server-side generation and client-side updating (no calculation necessary)
  • Cross-browser compatible

How it works: Inside the table cell place two copies of the content in two different elements within a relatively-positioned container element. The spacer element is statically-positioned and as such will affect the width of the table cells. By allowing the contents of the spacer cell to wrap we can get the "best-fit" width of the table cells that we are looking for. This also allows us to use the absolutely-positioned element to restrict the width of the visible content to that of the relatively-positioned parent.

Tested and working in: IE8, IE9, IE10, Chrome, Firefox, Safari, Opera

Result Images:

Nice proportional widths Nice proportional clipping

JSFiddle: http://jsfiddle.net/zAeA2/

Sample HTML/CSS:

<td>
    <!--Relative-positioned container-->
    <div class="container">
        <!--Visible-->
        <div class="content"><!--Content here--></div>
        <!--Hidden spacer-->
        <div class="spacer"><!--Content here--></div>
        <!--Keeps the container from collapsing without
            having to specify a height-->
        <span>&nbsp;</span>
     </div>
</td>

.container {
    position: relative;
}
.content {
    position: absolute;
    max-width: 100%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.spacer {
    height: 0;
    overflow: hidden;
}

How to create a sub array from another array in Java?

int newArrayLength = 30; 

int[] newArray = new int[newArrayLength];

System.arrayCopy(oldArray, 0, newArray, 0, newArray.length);

How to determine whether code is running in DEBUG / RELEASE build?

Just one more idea to detect:

DebugMode.h

#import <Foundation/Foundation.h>

@interface DebugMode: NSObject
    +(BOOL) isDebug;
@end

DebugMode.m

#import "DebugMode.h"

@implementation DebugMode
+(BOOL) isDebug {
#ifdef DEBUG
    return true;
#else
    return false;
#endif
}
@end

add into header bridge file:

#include "DebugMode.h"

usage:

DebugMode.isDebug()

It is not needed to write something inside project properties swift flags.

how to set default culture info for entire c# application

With 4.0, you will need to manage this yourself by setting the culture for each thread as Alexei describes. But with 4.5, you can define a culture for the appdomain and that is the preferred way to handle this. The relevant apis are CultureInfo.DefaultThreadCurrentCulture and CultureInfo.DefaultThreadCurrentUICulture.

How can I require at least one checkbox be checked before a form can be submitted?

This should have what you need, check out the jsfiddle at the bottom:

$(document).ready(function () {
$('#txt').val($("input[type=checkbox]:checked").length);
$('#txt2').val($("input[type=checkbox]").length);

$('input[type=checkbox]').change(function () {
checked = $("input[type=checkbox]:checked").length;
$('#block').show();
$('#block2').hide();
if (checked > 0) {
  $('#block').hide();
  $('#block2').show();
  $('#txt').val(checked);
 }
});
});

How can I split a text into sentences?

Here is a middle of the road approach that doesn't rely on any external libraries. I use list comprehension to exclude overlaps between abbreviations and terminators as well as to exclude overlaps between variations on terminations, for example: '.' vs. '."'

abbreviations = {'dr.': 'doctor', 'mr.': 'mister', 'bro.': 'brother', 'bro': 'brother', 'mrs.': 'mistress', 'ms.': 'miss', 'jr.': 'junior', 'sr.': 'senior',
                 'i.e.': 'for example', 'e.g.': 'for example', 'vs.': 'versus'}
terminators = ['.', '!', '?']
wrappers = ['"', "'", ')', ']', '}']


def find_sentences(paragraph):
   end = True
   sentences = []
   while end > -1:
       end = find_sentence_end(paragraph)
       if end > -1:
           sentences.append(paragraph[end:].strip())
           paragraph = paragraph[:end]
   sentences.append(paragraph)
   sentences.reverse()
   return sentences


def find_sentence_end(paragraph):
    [possible_endings, contraction_locations] = [[], []]
    contractions = abbreviations.keys()
    sentence_terminators = terminators + [terminator + wrapper for wrapper in wrappers for terminator in terminators]
    for sentence_terminator in sentence_terminators:
        t_indices = list(find_all(paragraph, sentence_terminator))
        possible_endings.extend(([] if not len(t_indices) else [[i, len(sentence_terminator)] for i in t_indices]))
    for contraction in contractions:
        c_indices = list(find_all(paragraph, contraction))
        contraction_locations.extend(([] if not len(c_indices) else [i + len(contraction) for i in c_indices]))
    possible_endings = [pe for pe in possible_endings if pe[0] + pe[1] not in contraction_locations]
    if len(paragraph) in [pe[0] + pe[1] for pe in possible_endings]:
        max_end_start = max([pe[0] for pe in possible_endings])
        possible_endings = [pe for pe in possible_endings if pe[0] != max_end_start]
    possible_endings = [pe[0] + pe[1] for pe in possible_endings if sum(pe) > len(paragraph) or (sum(pe) < len(paragraph) and paragraph[sum(pe)] == ' ')]
    end = (-1 if not len(possible_endings) else max(possible_endings))
    return end


def find_all(a_str, sub):
    start = 0
    while True:
        start = a_str.find(sub, start)
        if start == -1:
            return
        yield start
        start += len(sub)

I used Karl's find_all function from this entry: Find all occurrences of a substring in Python

Visual Studio Code - Target of URI doesn't exist 'package:flutter/material.dart'

If you change the property name in pubspect.yaml all your package in lib folder turn to red with the error Target of URI doesn't exist...

In PowerShell, how do I test whether or not a specific variable exists in global scope?

So far, it looks like the answer that works is this one.

To break it out further, what worked for me was this:

Get-Variable -Name foo -Scope Global -ea SilentlyContinue | out-null

$? returns either true or false.

String is immutable. What exactly is the meaning?

String is immutable means that you cannot change the object itself, but you can change the reference to the object.

When you execute a = "ty", you are actually changing the reference of a to a new object created by the String literal "ty".

Changing an object means to use its methods to change one of its fields (or the fields are public and not final, so that they can be updated from outside without accessing them via methods), for example:

Foo x = new Foo("the field");
x.setField("a new field");
System.out.println(x.getField()); // prints "a new field"

While in an immutable class (declared as final, to prevent modification via inheritance)(its methods cannot modify its fields, and also the fields are always private and recommended to be final), for example String, you cannot change the current String but you can return a new String, i.e:

String s = "some text";
s.substring(0,4);
System.out.println(s); // still printing "some text"
String a = s.substring(0,4);
System.out.println(a); // prints "some"

MacOSX homebrew mysql root password

If you run

brew install mariadb
...
brew services start mariadb
==> Successfully started `mariadb` (label: homebrew.mxcl.mariadb)

 $(brew --prefix mariadb)/bin/mysqladmin -u root password newpass
/usr/local/opt/mariadb/bin/mysqladmin: connect to server at 'localhost' failed
error: 'Access denied for user 'root'@'localhost''

also login with root account fails:

mariadb -u root
ERROR 1698 (28000): Access denied for user 'root'@'localhost'

then default admin user is created same name as your MacOS account username, e.g. johnsmit.

To login as root, issue:

mariadb -u johnsmit
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 17
Server version: 10.4.11-MariaDB Homebrew

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> exit
Bye

Java HTML Parsing

You might be interested by TagSoup, a Java HTML parser able to handle malformed HTML. XML parsers would work only on well formed XHTML.

How to change a <select> value from JavaScript

You can use the selectedIndex property to set it to the first option:

document.getElementById("select").selectedIndex = 0;

MySql Error: Can't update table in stored function/trigger because it is already used by statement which invoked this stored function/trigger

You cannot change a table while the INSERT trigger is firing. The INSERT might do some locking which could result in a deadlock. Also, updating the table from a trigger would then cause the same trigger to fire again in an infinite recursive loop. Both of these reasons are why MySQL prevents you from doing this.

However, depending on what you're trying to achieve, you can access the new values by using NEW.fieldname or even the old values--if doing an UPDATE--with OLD.

If you had a row named full_brand_name and you wanted to use the first two letters as a short name in the field small_name you could use:

CREATE TRIGGER `capital` BEFORE INSERT ON `brandnames`
FOR EACH ROW BEGIN
  SET NEW.short_name = CONCAT(UCASE(LEFT(NEW.full_name,1)) , LCASE(SUBSTRING(NEW.full_name,2)))
END

Should Jquery code go in header or footer?

Standard practice is to put all of your scripts at the bottom of the page, but I use ASP.NET MVC with a number of jQuery plugins, and I find that it all works better if I put my jQuery scripts in the <head> section of the master page.

In my case, there are artifacts that occur when the page is loaded, if the scripts are at the bottom of the page. I'm using the jQuery TreeView plugin, and if the scripts are not loaded at the beginning, the tree will render without the necessary CSS classes imposed on it by the plugin. So you get this funny-looking mess when the page first loads, followed by the proper rendering of the TreeView. Very bad looking. Putting the jQuery plugins in the <head> section of the master page eliminates this problem.

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

i have solve my same problem

i update my android studio, and i choose not to import my setting from my previous version than that problem appear.

than i realize that i have 2 AndroidStudio folder on my windows account (.AndroidStudio and .AndroidStudio1.2) and on my new .AndroidStudio1.2 folder there are no other.xml file.

than i copy other.xml file from C:\Users\my windows account name.AndroidStudio\config\options to C:\Users\my windows account name.AndroidStudio1.2\config\options

and that how i solve my problem.

How can I send emails through SSL SMTP with the .NET Framework?

As stated in a comment at

http://blogs.msdn.com/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx

with System.Net.Mail, use port 25 instead of 465:

You must set SSL=true and Port=25. Server responds to your request from unprotected 25 and then throws connection to protected 465.

HTTP Error 503, the service is unavailable

If the app pool immediately stops after you start it and your event log shows:

The worker process for application pool 'APP_POOL_NAME' encountered an error 'Cannot read configuration file ' trying to read configuration data from file '\?\', line number '0'. The data field contains the error code.

... you may experiencing a bug that was apparently introduced in the Windows 10 Fall Creators Update and/or .Net Framework v4.7.1. It can be resolved via the following workaround steps, which are from this answer to the related question Cannot read configuration file ' trying to read configuration data from file '\\?\<EMPTY>', line number '0'.

  1. Go to the drive your IIS is installed on, eg. C:\inetpub\temp\appPools\
  2. Delete the directory (or virtual directory) with the same name as your app pool.
  3. Recycle/Start your app pool again.

I have reported this bug to Microsoft by creating the following issue on the dotnet GitHub repo: After installing 4.7.1, IIS AppPool stops with "Cannot read configuration file".

EDIT

Microsoft responded that this is a known issue with the Windows setup process for the Fall Creators Update and was documented in KB 4050891, Web applications return HTTP Error 503 and WAS event 5189 on Windows 10 Version 1709 (Fall Creators Update). That article provides the following workaround procedure, which is similar to the one above. However, note that it will recycle all app pools regardless of whether they are affected by the issue.

  1. Open a Windows PowerShell window by using the Run as administrator option.
  2. Run the following commands:
    • Stop-Service -Force WAS
    • Remove-Item -Recurse -Force C:\inetpub\temp\appPools\*
    • Start-Service W3SVC

Python Sets vs Lists

It depends on what you are intending to do with it.

Sets are significantly faster when it comes to determining if an object is present in the set (as in x in s), but are slower than lists when it comes to iterating over their contents.

You can use the timeit module to see which is faster for your situation.

jquery toggle slide from left to right and back

There is no such method as slideLeft() and slideRight() which looks like slideUp() and slideDown(), but you can simulate these effects using jQuery’s animate() function.

HTML Code:

<div class="text">Lorem ipsum.</div>

JQuery Code:

  $(document).ready(function(){
    var DivWidth = $(".text").width();
    $(".left").click(function(){
      $(".text").animate({
        width: 0
      });
    });
    $(".right").click(function(){
      $(".text").animate({
        width: DivWidth
      });
    });
  });

You can see an example here: How to slide toggle a DIV from Left to Right?

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

Simple: In Visual Studio Report designer
1. Open the report in design mode and delete the dataset from the RDLC File
2. Open solution Explorer and delete the actual (corrupted) XSD file
3. Add the dataset back to the RDLC file.
4. The above procedure will create the new XSD file.
5. More detailed is below.

In Visual Studio, Open your RDLC file Report in Design mode. Click on the report and then Select View and then Report Data from the top line menu. Select Datasets and then Right Click and delete the dataset from the report. Next Open Solution Explorer, if it is not already open in your Visual Studio. Locate the XSD file (It should be the same name as the dataset you just deleted from the report). Now go back and right click again on the report data Datasets, and select Add Dataset . This will create a new XSD file and write the dataset properties to the report. Now your error message will be gone and any missing data will now appear in your reports.

python numpy/scipy curve fitting

You'll first need to separate your numpy array into two separate arrays containing x and y values.

x = [1, 2, 3, 9]
y = [1, 4, 1, 3]

curve_fit also requires a function that provides the type of fit you would like. For instance, a linear fit would use a function like

def func(x, a, b):
    return a*x + b

scipy.optimize.curve_fit(func, x, y) will return a numpy array containing two arrays: the first will contain values for a and b that best fit your data, and the second will be the covariance of the optimal fit parameters.

Here's an example for a linear fit with the data you provided.

import numpy as np
from scipy.optimize import curve_fit

x = np.array([1, 2, 3, 9])
y = np.array([1, 4, 1, 3])

def fit_func(x, a, b):
    return a*x + b

params = curve_fit(fit_func, x, y)

[a, b] = params[0]

This code will return a = 0.135483870968 and b = 1.74193548387

Here's a plot with your points and the linear fit... which is clearly a bad one, but you can change the fitting function to obtain whatever type of fit you would like.

enter image description here

Short description of the scoping rules?

Essentially, the only thing in Python that introduces a new scope is a function definition. Classes are a bit of a special case in that anything defined directly in the body is placed in the class's namespace, but they are not directly accessible from within the methods (or nested classes) they contain.

In your example there are only 3 scopes where x will be searched in:

  • spam's scope - containing everything defined in code3 and code5 (as well as code4, your loop variable)

  • The global scope - containing everything defined in code1, as well as Foo (and whatever changes after it)

  • The builtins namespace. A bit of a special case - this contains the various Python builtin functions and types such as len() and str(). Generally this shouldn't be modified by any user code, so expect it to contain the standard functions and nothing else.

More scopes only appear when you introduce a nested function (or lambda) into the picture. These will behave pretty much as you'd expect however. The nested function can access everything in the local scope, as well as anything in the enclosing function's scope. eg.

def foo():
    x=4
    def bar():
        print x  # Accesses x from foo's scope
    bar()  # Prints 4
    x=5
    bar()  # Prints 5

Restrictions:

Variables in scopes other than the local function's variables can be accessed, but can't be rebound to new parameters without further syntax. Instead, assignment will create a new local variable instead of affecting the variable in the parent scope. For example:

global_var1 = []
global_var2 = 1

def func():
    # This is OK: It's just accessing, not rebinding
    global_var1.append(4) 

    # This won't affect global_var2. Instead it creates a new variable
    global_var2 = 2 

    local1 = 4
    def embedded_func():
        # Again, this doen't affect func's local1 variable.  It creates a 
        # new local variable also called local1 instead.
        local1 = 5
        print local1

    embedded_func() # Prints 5
    print local1    # Prints 4

In order to actually modify the bindings of global variables from within a function scope, you need to specify that the variable is global with the global keyword. Eg:

global_var = 4
def change_global():
    global global_var
    global_var = global_var + 1

Currently there is no way to do the same for variables in enclosing function scopes, but Python 3 introduces a new keyword, "nonlocal" which will act in a similar way to global, but for nested function scopes.

How to wrap async function calls into a sync function in Node.js or Javascript?

I can't find a scenario that cannot be solved using node-fibers. The example you provided using node-fibers behaves as expected. The key is to run all the relevant code inside a fiber, so you don't have to start a new fiber in random positions.

Lets see an example: Say you use some framework, which is the entry point of your application (you cannot modify this framework). This framework loads nodejs modules as plugins, and calls some methods on the plugins. Lets say this framework only accepts synchronous functions, and does not use fibers by itself.

There is a library that you want to use in one of your plugins, but this library is async, and you don't want to modify it either.

The main thread cannot be yielded when no fiber is running, but you still can create plugins using fibers! Just create a wrapper entry that starts the whole framework inside a fiber, so you can yield the execution from the plugins.

Downside: If the framework uses setTimeout or Promises internally, then it will escape the fiber context. This can be worked around by mocking setTimeout, Promise.then, and all event handlers.

So this is how you can yield a fiber until a Promise is resolved. This code takes an async (Promise returning) function and resumes the fiber when the promise is resolved:

framework-entry.js

console.log(require("./my-plugin").run());

async-lib.js

exports.getValueAsync = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("Async Value");
    }, 100);
  });
};

my-plugin.js

const Fiber = require("fibers");

function fiberWaitFor(promiseOrValue) {
  var fiber = Fiber.current, error, value;
  Promise.resolve(promiseOrValue).then(v => {
    error = false;
    value = v;
    fiber.run();
  }, e => {
    error = true;
    value = e;
    fiber.run();
  });
  Fiber.yield();
  if (error) {
    throw value;
  } else {
    return value;
  }
}

const asyncLib = require("./async-lib");

exports.run = () => {
  return fiberWaitFor(asyncLib.getValueAsync());
};

my-entry.js

require("fibers")(() => {
  require("./framework-entry");
}).run();

When you run node framework-entry.js it will throw an error: Error: yield() called with no fiber running. If you run node my-entry.js it works as expected.

How to continue the code on the next line in VBA

In VBA (and VB.NET) the line terminator (carriage return) is used to signal the end of a statement. To break long statements into several lines, you need to

Use the line-continuation character, which is an underscore (_), at the point at which you want the line to break. The underscore must be immediately preceded by a space and immediately followed by a line terminator (carriage return).

(From How to: Break and Combine Statements in Code)

In other words: Whenever the interpreter encounters the sequence <space>_<line terminator>, it is ignored and parsing continues on the next line. Note, that even when ignored, the line continuation still acts as a token separator, so it cannot be used in the middle of a variable name, for example. You also cannot continue a comment by using a line-continuation character.

To break the statement in your question into several lines you could do the following:

U_matrix(i, j, n + 1) = _
     k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
     (k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))

(Leading whitespaces are ignored.)

Python Requests library redirect new url

I think requests.head instead of requests.get will be more safe to call when handling url redirect,check the github issue here:

r = requests.head(url, allow_redirects=True)
print(r.url)

How do I diff the same file between two different commits on the same branch?

All the other responses are more complete, so upvote them. This one is just to remember that you can avoid knowing the id of the recent commit. Usually, I set my self in the branch that I want to compare and run diff tools knowing the old commit uid (You can use other notations):

git checkout master
git difftool 6f8bba my/file/relative/path.py

Also, check this other response here to set the tool you want git open to compare the file: Configuring diff tool with .gitconfig And to learn more about difftool, go to the difftool doc

How to Join to first row

You could do:

SELECT 
  Orders.OrderNumber, 
  LineItems.Quantity, 
  LineItems.Description
FROM 
  Orders INNER JOIN LineItems 
  ON Orders.OrderID = LineItems.OrderID
WHERE
  LineItems.LineItemID = (
    SELECT MIN(LineItemID) 
    FROM   LineItems
    WHERE  OrderID = Orders.OrderID
  )

This requires an index (or primary key) on LineItems.LineItemID and an index on LineItems.OrderID or it will be slow.

Init array of structs in Go

You can have it this way:

It is important to mind the commas after each struct item or set of items.

earnings := []LineItemsType{

        LineItemsType{

            TypeName: "Earnings",

            Totals: 0.0,

            HasTotal: true,

            items: []LineItems{

                LineItems{

                    name: "Basic Pay",

                    amount: 100.0,
                },

                LineItems{

                    name: "Commuter Allowance",

                    amount: 100.0,
                },
            },
        },
        LineItemsType{

            TypeName: "Earnings",

            Totals: 0.0,

            HasTotal: true,

            items: []LineItems{

                LineItems{

                    name: "Basic Pay",

                    amount: 100.0,
                },

                LineItems{

                    name: "Commuter Allowance",

                    amount: 100.0,
                },
            },
        },
    }

Setting Camera Parameters in OpenCV/Python

To avoid using integer values to identify the VideoCapture properties, one can use, e.g., cv2.cv.CV_CAP_PROP_FPS in OpenCV 2.4 and cv2.CAP_PROP_FPS in OpenCV 3.0. (See also Stefan's comment below.)

Here a utility function that works for both OpenCV 2.4 and 3.0:

# returns OpenCV VideoCapture property id given, e.g., "FPS"
def capPropId(prop):
  return getattr(cv2 if OPCV3 else cv2.cv,
    ("" if OPCV3 else "CV_") + "CAP_PROP_" + prop)

OPCV3 is set earlier in my utilities code like this:

from pkg_resources import parse_version
OPCV3 = parse_version(cv2.__version__) >= parse_version('3')

Sorting an ArrayList of objects using a custom sorting order

use this method:

private ArrayList<myClass> sortList(ArrayList<myClass> list) {
    if (list != null && list.size() > 1) {
        Collections.sort(list, new Comparator<myClass>() {
            public int compare(myClass o1, myClass o2) {
                if (o1.getsortnumber() == o2.getsortnumber()) return 0;
                return o1.getsortnumber() < o2.getsortnumber() ? 1 : -1;
            }
        });
    }
    return list;
}

`

and use: mySortedlist = sortList(myList); No need to implement comparator in your class. If you want inverse order swap 1 and -1

How do I redirect in expressjs while passing some context?

use app.set & app.get

Setting data

router.get(
  "/facebook/callback",
  passport.authenticate("facebook"),
  (req, res) => {
    req.app.set('user', res.req.user)
    return res.redirect("/sign");
  }
);

Getting data

router.get("/sign", (req, res) => {
  console.log('sign', req.app.get('user'))
});

animating addClass/removeClass with jQuery

You could use jquery ui's switchClass, Heres an example:

$( "selector" ).switchClass( "oldClass", "newClass", 1000, "easeInOutQuad" );

Or see this jsfiddle.

Using GregorianCalendar with SimpleDateFormat

Why such complications?

public static GregorianCalendar convertFromDMY(String dd_mm_yy) throws ParseException 
{
    SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
    Date date = fmt.parse(dd_mm_yy);
    GregorianCalendar cal = GregorianCalendar.getInstance();
    cal.setTime(date);
    return cal;
}

Error:Unable to locate adb within SDK in Android Studio

If you have an antivirus (such as AVG), you can take the file out of quarantine.

Click Menu > Quarantine > Check box next to the adb.exe file > Arrow next to delete > Restore

But sometimes, the file will keep reappearing in the quarantine. The way to solve this is by clicking Restore and add exception, or by going to Menu > Setting > General > Exceptions > And adding something like this: C:\Users\Johndoe\AppData\Local\Android\Sdk\platform-tools\

Other antiviruses have similar equivalents of a "quarantine" that the APK file may be in.

How do I check out an SVN project into Eclipse as a Java project?

Here are the steps:

  • Install the subclipse plugin (provides svn connectivity in eclipse) and connect to the repository. Instructions here: http://subclipse.tigris.org/install.html
  • Go to File->New->Other->Under the SVN category, select Checkout Projects from SVN.
  • Select your project's root folder and select checkout as a project in the workspace.

It seems you are checking the .project file into the source repository. I would suggest not checking in the .project file so users can have their own version of the file. Also, if you use the subclipse plugin it allows you to check out and configure a source folder as a java project. This process creates the correct .project for you(with the java nature),

Adding a directory to the PATH environment variable in Windows

Option 1

After you change PATH with the GUI, close and re-open the console window.

This works because only programs started after the change will see the new PATH.

Option 2

Execute this command in the command window you have open:

set PATH=%PATH%;C:\your\path\here\

This command appends C:\your\path\here\ to the current PATH.

Breaking it down:

  • set – A command that changes cmd's environment variables only for the current cmd session; other programs and the system are unaffected.
  • PATH= – Signifies that PATH is the environment variable to be temporarily changed.
  • %PATH%;C:\your\path\here\ – The %PATH% part expands to the current value of PATH, and ;C:\your\path\here\ is then concatenated to it. This becomes the new PATH.

calling another method from the main method in java

You can only call instance method like do() (which is an illegal method name, incidentally) against an instance of the class:

public static void main(String[] args){
  new Foo().doSomething();
}

public void doSomething(){}

Alternatively, make doSomething() static as well, if that works for your design.

Batch file to delete files older than N days

Ok was bored a bit and came up with this, which contains my version of a poor man's Linux epoch replacement limited for daily usage (no time retention):

7daysclean.cmd

@echo off
setlocal ENABLEDELAYEDEXPANSION
set day=86400
set /a year=day*365
set /a strip=day*7
set dSource=C:\temp

call :epoch %date%
set /a slice=epoch-strip

for /f "delims=" %%f in ('dir /a-d-h-s /b /s %dSource%') do (
    call :epoch %%~tf
    if !epoch! LEQ %slice% (echo DELETE %%f ^(%%~tf^)) ELSE echo keep %%f ^(%%~tf^)
)
exit /b 0

rem Args[1]: Year-Month-Day
:epoch
    setlocal ENABLEDELAYEDEXPANSION
    for /f "tokens=1,2,3 delims=-" %%d in ('echo %1') do set Years=%%d& set Months=%%e& set Days=%%f
    if "!Months:~0,1!"=="0" set Months=!Months:~1,1!
    if "!Days:~0,1!"=="0" set Days=!Days:~1,1!
    set /a Days=Days*day
    set /a _months=0
    set i=1&& for %%m in (31 28 31 30 31 30 31 31 30 31 30 31) do if !i! LSS !Months! (set /a _months=!_months! + %%m*day&& set /a i+=1)
    set /a Months=!_months!
    set /a Years=(Years-1970)*year
    set /a Epoch=Years+Months+Days
    endlocal& set Epoch=%Epoch%
    exit /b 0

USAGE

set /a strip=day*7 : Change 7 for the number of days to keep.

set dSource=C:\temp : This is the starting directory to check for files.

NOTES

This is non-destructive code, it will display what would have happened.

Change :

if !epoch! LEQ %slice% (echo DELETE %%f ^(%%~tf^)) ELSE echo keep %%f ^(%%~tf^)

to something like :

if !epoch! LEQ %slice% del /f %%f

so files actually get deleted

February: is hard-coded to 28 days. Bissextile years is a hell to add, really. if someone has an idea that would not add 10 lines of code, go ahead and post so I add it to my code.

epoch: I did not take time into consideration, as the need is to delete files older than a certain date, taking hours/minutes would have deleted files from a day that was meant for keeping.

LIMITATION

epoch takes for granted your short date format is YYYY-MM-DD. It would need to be adapted for other settings or a run-time evaluation (read sShortTime, user-bound configuration, configure proper field order in a filter and use the filter to extract the correct data from the argument).

Did I mention I hate this editor's auto-formating? it removes the blank lines and the copy-paste is a hell.

I hope this helps.

Request is not available in this context

I was able to workaround/hack this problem by moving in to "Classic" mode from "integrated" mode.

Attributes / member variables in interfaces?

Something important has been said by Tom:

if you use the has-a concept, you avoid the issue.

Indeed, if instead of using extends and implements you define two attributes, one of type rectangle, one of type JLabel in your Tile class, then you can define a Rectangle to be either an interface or a class.

Furthermore, I would normally encourage the use of interfaces in connection with has-a, but I guess it would be an overkill in your situation. However, you are the only one that can decide on this point (tradeoff flexibility/over-engineering).

Android REST client, Sample?

Disclaimer: I am involved in the rest2mobile open source project

Another alternative as a REST client is to use rest2mobile.

The approach is slightly different as it uses concrete rest examples to generate the client code for the REST service. The code replaces the REST URL and JSON payloads with native java methods and POJOs. It also automatically handles server connections, asynchronous invocations and POJO to/from JSON conversions.

Note that this tool comes in different flavors (cli, plugins, android/ios/js support) and you can use the android studio plugin to generate the API directly into your app.

All the code can be found on github here.

Cannot overwrite model once compiled Mongoose

I have a situation where I have to create the model dynamically with each request and because of that I received this error, however, what I used to fix it is using deleteModel method like the following:

var contentType = 'Product'

var contentSchema = new mongoose.Schema(schema, virtuals);

var model = mongoose.model(contentType, contentSchema);

mongoose.deleteModel(contentType);

I hope this could help anybody.

Java out.println() how is this possible?

PrintStream out = System.out;
out.println( "hello" );

How to convert from []byte to int in Go Programming

For encoding/decoding numbers to/from byte sequences, there's the encoding/binary package. There are examples in the documentation: see the Examples section in the table of contents.

These encoding functions operate on io.Writer interfaces. The net.TCPConn type implements io.Writer, so you can write/read directly to network connections.

If you've got a Go program on either side of the connection, you may want to look at using encoding/gob. See the article "Gobs of data" for a walkthrough of using gob (skip to the bottom to see a self-contained example).

Is string in array?

Arrays are, in general, a poor data structure to use if you want to ask if a particular object is in the collection or not.

If you'll be running this search frequently, it might be worth it to use a Dictionary<string, something> rather than an array. Lookups in a Dictionary are O(1) (constant-time), while searching through the array is O(N) (takes time proportional to the length of the array).

Even if the array is only 200 items at most, if you do a lot of these searches, the Dictionary will likely be faster.

Using Pandas to pd.read_excel() for multiple worksheets of the same workbook

Yes unfortunately it will always load the full file. If you're doing this repeatedly probably best to extract the sheets to separate CSVs and then load separately. You can automate that process with d6tstack which also adds additional features like checking if all the columns are equal across all sheets or multiple Excel files.

import d6tstack
c = d6tstack.convert_xls.XLStoCSVMultiSheet('multisheet.xlsx')
c.convert_all() # ['multisheet-Sheet1.csv','multisheet-Sheet2.csv']

See d6tstack Excel examples

how to delete all cookies of my website in php

All previous answers have overlooked that the setcookie could have been used with an explicit domain. Furthermore, the cookie might have been set on a higher subdomain, e.g. if you were on a foo.bar.tar.com domain, there might be a cookie set on tar.com. Therefore, you want to unset cookies for all domains that might have dropped the cookie:

$host = explode('.', $_SERVER['HTTP_HOST']);

while ($host) {
    $domain = '.' . implode('.', $host);

    foreach ($_COOKIE as $name => $value) {
        setcookie($name, '', 1, '/', $domain);
    }

    array_shift($host);
}

Terminating idle mysql connections

Manual cleanup:

You can KILL the processid.

mysql> show full processlist;
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| Id      | User       | Host              | db   | Command | Time  | State | Info                  |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| 1193777 | TestUser12 | 192.168.1.11:3775 | www  | Sleep   | 25946 |       | NULL                  |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+

mysql> kill 1193777;

But:

  • the php application might report errors (or the webserver, check the error logs)
  • don't fix what is not broken - if you're not short on connections, just leave them be.

Automatic cleaner service ;)

Or you configure your mysql-server by setting a shorter timeout on wait_timeout and interactive_timeout

mysql> show variables like "%timeout%";
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| connect_timeout          | 5     |
| delayed_insert_timeout   | 300   |
| innodb_lock_wait_timeout | 50    |
| interactive_timeout      | 28800 |
| net_read_timeout         | 30    |
| net_write_timeout        | 60    |
| slave_net_timeout        | 3600  |
| table_lock_wait_timeout  | 50    |
| wait_timeout             | 28800 |
+--------------------------+-------+
9 rows in set (0.00 sec)

Set with:

set global wait_timeout=3;
set global interactive_timeout=3;

(and also set in your configuration file, for when your server restarts)

But you're treating the symptoms instead of the underlying cause - why are the connections open? If the PHP script finished, shouldn't they close? Make sure your webserver is not using connection pooling...

dpi value of default "large", "medium" and "small" text views android

To put it in another way, can we replicate the appearance of these text views without using the android:textAppearance attribute?

Like biegleux already said:

  • small represents 14sp
  • medium represents 18sp
  • large represents 22sp

If you want to use the small, medium or large value on any text in your Android app, you can just create a dimens.xml file in your values folder and define the text size there with the following 3 lines:

<dimen name="text_size_small">14sp</dimen>
<dimen name="text_size_medium">18sp</dimen>
<dimen name="text_size_large">22sp</dimen>

Here is an example for a TextView with large text from the dimens.xml file:

<TextView
  android:id="@+id/hello_world"
  android:text="hello world"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:textSize="@dimen/text_size_large"/>

How can I convert ticks to a date format?

Answers so far helped me come up with mine. I'm wary of UTC vs local time; ticks should always be UTC IMO.

public class Time
{
    public static void Timestamps()
    {
        OutputTimestamp();
        Thread.Sleep(1000);
        OutputTimestamp();
    }

    private static void OutputTimestamp()
    {
        var timestamp = DateTime.UtcNow.Ticks;
        var localTicks = DateTime.Now.Ticks;
        var localTime = new DateTime(timestamp, DateTimeKind.Utc).ToLocalTime();
        Console.Out.WriteLine("Timestamp = {0}.  Local ticks = {1}.  Local time = {2}.", timestamp, localTicks, localTime);
    }
}

Output:

Timestamp = 636988286338754530.  Local ticks = 636988034338754530.  Local time = 2019-07-15 4:03:53 PM.
Timestamp = 636988286348878736.  Local ticks = 636988034348878736.  Local time = 2019-07-15 4:03:54 PM.

How to handle notification when app in background in Firebase

To capture the message in background you need to use a BroadcastReceiver

import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.legacy.content.WakefulBroadcastReceiver
import com.google.firebase.messaging.RemoteMessage

class FirebaseBroadcastReceiver : WakefulBroadcastReceiver() {

    val TAG: String = FirebaseBroadcastReceiver::class.java.simpleName

    override fun onReceive(context: Context, intent: Intent) {

        val dataBundle = intent.extras
        if (dataBundle != null)
            for (key in dataBundle.keySet()) {
                Log.d(TAG, "dataBundle: " + key + " : " + dataBundle.get(key))
            }
        val remoteMessage = RemoteMessage(dataBundle)
        }
    }

and add this to your manifest:

<receiver
      android:name="MY_PACKAGE_NAME.FirebaseBroadcastReceiver"
      android:exported="true"
      android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
</receiver>

Get OS-level system information

You can get some limited memory information from the Runtime class. It really isn't exactly what you are looking for, but I thought I would provide it for the sake of completeness. Here is a small example. Edit: You can also get disk usage information from the java.io.File class. The disk space usage stuff requires Java 1.6 or higher.

public class Main {
  public static void main(String[] args) {
    /* Total number of processors or cores available to the JVM */
    System.out.println("Available processors (cores): " + 
        Runtime.getRuntime().availableProcessors());

    /* Total amount of free memory available to the JVM */
    System.out.println("Free memory (bytes): " + 
        Runtime.getRuntime().freeMemory());

    /* This will return Long.MAX_VALUE if there is no preset limit */
    long maxMemory = Runtime.getRuntime().maxMemory();
    /* Maximum amount of memory the JVM will attempt to use */
    System.out.println("Maximum memory (bytes): " + 
        (maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory));

    /* Total memory currently available to the JVM */
    System.out.println("Total memory available to JVM (bytes): " + 
        Runtime.getRuntime().totalMemory());

    /* Get a list of all filesystem roots on this system */
    File[] roots = File.listRoots();

    /* For each filesystem root, print some info */
    for (File root : roots) {
      System.out.println("File system root: " + root.getAbsolutePath());
      System.out.println("Total space (bytes): " + root.getTotalSpace());
      System.out.println("Free space (bytes): " + root.getFreeSpace());
      System.out.println("Usable space (bytes): " + root.getUsableSpace());
    }
  }
}

jquery onclick change css background image

Use your jquery like this

$('.home').css({'background-image':'url(images/tabs3.png)'});

Traverse a list in reverse order in Python

The other answers are good, but if you want to do as List comprehension style

collection = ['a','b','c']
[item for item in reversed( collection ) ]

Google Drive as FTP Server

I couldn't find a direct GDrive/DropBox solution. I'm also surprised there's no lazy solution for a free ftp host. Windows azure offers a ftp server "FTP connector" that's fairly easy to turn on at: https://portal.azure.com

You can get a free 1 GB account by selecting "View All" machine types during your deployment.

How do I copy an entire directory of files into an existing directory using Python?

docs explicitly state that destination directory should not exist:

The destination directory, named by dst, must not already exist; it will be created as well as missing parent directories.

I think your best bet is to os.walk the second and all consequent directories, copy2 directory and files and do additional copystat for directories. After all that's precisely what copytree does as explained in the docs. Or you could copy and copystat each directory/file and os.listdir instead of os.walk.

Entity Framework Migrations renaming tables and columns

To expand a bit on Hossein Narimani Rad's answer, you can rename both a table and columns using System.ComponentModel.DataAnnotations.Schema.TableAttribute and System.ComponentModel.DataAnnotations.Schema.ColumnAttribute respectively.

This has a couple benefits:

  1. Not only will this create the the name migrations automatically, but
  2. it will also deliciously delete any foreign keys and recreate them against the new table and column names, giving the foreign keys and constaints proper names.
  3. All this without losing any table data

For example, adding [Table("Staffs")]:

[Table("Staffs")]
public class AccountUser
{
    public long Id { get; set; }

    public long AccountId { get; set; }

    public string ApplicationUserId { get; set; }

    public virtual Account Account { get; set; }

    public virtual ApplicationUser User { get; set; }
}

Will generate the migration:

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropForeignKey(
            name: "FK_AccountUsers_Accounts_AccountId",
            table: "AccountUsers");

        migrationBuilder.DropForeignKey(
            name: "FK_AccountUsers_AspNetUsers_ApplicationUserId",
            table: "AccountUsers");

        migrationBuilder.DropPrimaryKey(
            name: "PK_AccountUsers",
            table: "AccountUsers");

        migrationBuilder.RenameTable(
            name: "AccountUsers",
            newName: "Staffs");

        migrationBuilder.RenameIndex(
            name: "IX_AccountUsers_ApplicationUserId",
            table: "Staffs",
            newName: "IX_Staffs_ApplicationUserId");

        migrationBuilder.RenameIndex(
            name: "IX_AccountUsers_AccountId",
            table: "Staffs",
            newName: "IX_Staffs_AccountId");

        migrationBuilder.AddPrimaryKey(
            name: "PK_Staffs",
            table: "Staffs",
            column: "Id");

        migrationBuilder.AddForeignKey(
            name: "FK_Staffs_Accounts_AccountId",
            table: "Staffs",
            column: "AccountId",
            principalTable: "Accounts",
            principalColumn: "Id",
            onDelete: ReferentialAction.Cascade);

        migrationBuilder.AddForeignKey(
            name: "FK_Staffs_AspNetUsers_ApplicationUserId",
            table: "Staffs",
            column: "ApplicationUserId",
            principalTable: "AspNetUsers",
            principalColumn: "Id",
            onDelete: ReferentialAction.Restrict);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropForeignKey(
            name: "FK_Staffs_Accounts_AccountId",
            table: "Staffs");

        migrationBuilder.DropForeignKey(
            name: "FK_Staffs_AspNetUsers_ApplicationUserId",
            table: "Staffs");

        migrationBuilder.DropPrimaryKey(
            name: "PK_Staffs",
            table: "Staffs");

        migrationBuilder.RenameTable(
            name: "Staffs",
            newName: "AccountUsers");

        migrationBuilder.RenameIndex(
            name: "IX_Staffs_ApplicationUserId",
            table: "AccountUsers",
            newName: "IX_AccountUsers_ApplicationUserId");

        migrationBuilder.RenameIndex(
            name: "IX_Staffs_AccountId",
            table: "AccountUsers",
            newName: "IX_AccountUsers_AccountId");

        migrationBuilder.AddPrimaryKey(
            name: "PK_AccountUsers",
            table: "AccountUsers",
            column: "Id");

        migrationBuilder.AddForeignKey(
            name: "FK_AccountUsers_Accounts_AccountId",
            table: "AccountUsers",
            column: "AccountId",
            principalTable: "Accounts",
            principalColumn: "Id",
            onDelete: ReferentialAction.Cascade);

        migrationBuilder.AddForeignKey(
            name: "FK_AccountUsers_AspNetUsers_ApplicationUserId",
            table: "AccountUsers",
            column: "ApplicationUserId",
            principalTable: "AspNetUsers",
            principalColumn: "Id",
            onDelete: ReferentialAction.Restrict);
    }

How to send push notification to web browser?

So here I am answering my own question. I have got answers to all my queries from people who have build push notification services in the past.

Update (May 2018): Here is a comprehensive and a very well written doc on web push notification from Google.

Answer to the original questions asked 3 years ago:

  1. Can we use GCM/APNS to send push notification to all Web Browsers including Firefox & Safari?

Answer: Google has deprecated GCM as of April 2018. You can now use Firebase Cloud Messaging (FCM). This supports all platforms including web browsers.

  1. If not via GCM can we have our own back-end to do the same?

Answer: Yes, push notification can be sent from our own back-end. Support for the same has come to all major browsers.

Check this codelab from Google to better understand the implementation.

Some Tutorials:

  • Implementing push notification in Django Here.
  • Using flask to send push notification Here & Here.
  • Sending push notifcaiton from Nodejs Here
  • Sending push notification using php Here & Here
  • Sending push notification from Wordpress. Here & Here
  • Sending push notification from Drupal. Here

Implementing own backend in various programming languages.:

Further Readings: - - Documentation from Firefox website can be read here. - A very good overview of Web Push by Google can be found here. - An FAQ answering most common confusions and questions.

Are there any free services to do the same? There are some companies that provide a similar solution in free, freemium and paid models. Am listing few below:

  1. https://onesignal.com/ (Free | Support all platforms)
  2. https://firebase.google.com/products/cloud-messaging/ (Free)
  3. https://clevertap.com/ (Has free plan)
  4. https://goroost.com/

Note: When choosing a free service remember to read the TOS. Free services often work by collecting user data for various purposes including analytics.

Apart from that, you need to have HTTPS to send push notifications. However, you can get https freely via letsencrypt.org

Sorting data based on second column of a file

For tab separated values the code below can be used

sort -t$'\t' -k2 -n

-r can be used for getting data in descending order.
-n for numerical sort
-k, --key=POS1[,POS2] where k is column in file
For descending order below is the code

sort -t$'\t' -k2 -rn

PHP Regex to check date is in YYYY-MM-DD format

If it is of any help, here is a regex for j-n-Y format (year has to be greater than 2018):

if (preg_match('/^([1-9]|[1-2][0-9]|[3][0-1])\-([1-9]|[1][0-2])\-(?:20)([1][8-9]|[2-9][0-9])$/', $date)) {
   // Do stuff
}

How does Access-Control-Allow-Origin header work?

In Python I have been using the Flask-CORS library with great success. It makes dealing with CORS super easy and painless. I added some code from the library's documentation below.

Installing:

$ pip install -U flask-cors

Simple example that allows CORS for all domains on all routes:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
  return "Hello, cross-origin-world!"

For more specific examples see the documentation. I have used the simple example above to get around the CORS issue in an ionic application I am building that has to access a separate flask server.

How to specify credentials when connecting to boto3 S3?

This is older but placing this here for my reference too. boto3.resource is just implementing the default Session, you can pass through boto3.resource session details.

Help on function resource in module boto3:

resource(*args, **kwargs)
    Create a resource service client by name using the default session.

    See :py:meth:`boto3.session.Session.resource`.

https://github.com/boto/boto3/blob/86392b5ca26da57ce6a776365a52d3cab8487d60/boto3/session.py#L265

you can see that it just takes the same arguments as Boto3.Session

import boto3
S3 = boto3.resource('s3', region_name='us-west-2', aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY, aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY)
S3.Object( bucket_name, key_name ).delete()

Insert current date into a date column using T-SQL?

You could use getdate() in a default as this SO question's accepted answer shows. This way you don't provide the date, you just insert the rest and that date is the default value for the column.

You could also provide it in the values list of your insert and do it manually if you wish.

Select single item from a list

just saw this now, if you are working with a list of object you can try this

 public class user
{
    public string username { get; set; }
    public string password { get; set; }
}

  List<user> userlist = new List<user>();

        userlist.Add(new user { username = "macbruno", password = "1234" });
        userlist.Add(new user { username = "james", password = "5678" });
        string myusername = "james";
        string mypassword = "23432";

  user theUser = userlist.Find(
            delegate (user thisuser)
            {
                return thisuser.username== myusername && thisuser.password == mypassword;
            }
            );

            if (theUser != null)
            {
               Dosomething();
            }
            else
            {
                DoSomethingElse();

            }

What is the behavior of integer division?

Dirkgently gives an excellent description of integer division in C99, but you should also know that in C89 integer division with a negative operand has an implementation-defined direction.

From the ANSI C draft (3.3.5):

If either operand is negative, whether the result of the / operator is the largest integer less than the algebraic quotient or the smallest integer greater than the algebraic quotient is implementation-defined, as is the sign of the result of the % operator. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

So watch out with negative numbers when you are stuck with a C89 compiler.

It's a fun fact that C99 chose truncation towards zero because that was how FORTRAN did it. See this message on comp.std.c.

How to calculate an age based on a birthday?

Stackoverflow uses such function to determine the age of a user.

Calculate age in C#

The given answer is

DateTime now = DateTime.Today;
int age = now.Year - bday.Year;
if (now < bday.AddYears(age)) age--;

So your helper method would look like

public static string Age(this HtmlHelper helper, DateTime birthday)
{
    DateTime now = DateTime.Today;
    int age = now.Year - birthday.Year;
    if (now < birthday.AddYears(age)) age--;

    return age.ToString();
}

Today, I use a different version of this function to include a date of reference. This allow me to get the age of someone at a future date or in the past. This is used for our reservation system, where the age in the future is needed.

public static int GetAge(DateTime reference, DateTime birthday)
{
    int age = reference.Year - birthday.Year;
    if (reference < birthday.AddYears(age)) age--;

    return age;
}

Angular.js How to change an elements css class on click and to remove all others

Create a scope property called selectedIndex, and an itemClicked function:

function MyController ($scope) {
  $scope.collection = ["Item 1", "Item 2"];

  $scope.selectedIndex = 0; // Whatever the default selected index is, use -1 for no selection

  $scope.itemClicked = function ($index) {
    $scope.selectedIndex = $index;
  };
}

Then my template would look something like this:

<div>
      <span ng-repeat="item in collection"
             ng-class="{ 'selected-class-name': $index == selectedIndex }"
             ng-click="itemClicked($index)"> {{ item }} </span>
</div>

Just for reference $index is a magic variable available within ng-repeat directives.

You can use this same sample within a directive and template as well.

Here is a working plnkr:

http://plnkr.co/edit/jOO8YdPiSJEaOcayEP1X?p=preview

'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data)

An alternative that works for me is to simply convert to a CSV.

Bootstrap with jQuery Validation Plugin

I know this question is for Bootstrap 3, but as some Bootstrap 4 related question are redirected to this one as duplicates, here's the snippet Bootstrap 4-compatible:

$.validator.setDefaults({
    highlight: function(element) {
        $(element).closest('.form-group').addClass('has-danger');
    },
    unhighlight: function(element) {
        $(element).closest('.form-group').removeClass('has-danger');
    },
    errorElement: 'small',
    errorClass: 'form-control-feedback d-block',
    errorPlacement: function(error, element) {
        if(element.parent('.input-group').length) {
            error.insertAfter(element.parent());
        } else if(element.prop('type') === 'checkbox') {
            error.appendTo(element.parent().parent().parent());
        } else if(element.prop('type') === 'radio') {
            error.appendTo(element.parent().parent().parent());
        } else {
            error.insertAfter(element);
        }
    },
});

The few differences are:

  • The use of class has-danger instead of has-error
  • Better error positioning radios and checkboxes

Accessing JSON object keys having spaces

The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?

For example, we have i values and get the value of id field

alert(obj[i].id); //works!

But what if we need key with spaces?

In this case, the following construction can help (without point between [] blocks):

alert(obj[i]["No. of interfaces"]); //works too!

getElementsByClassName not working

If you want to do it by ClassName you could do:

<script type="text/javascript">
function hideTd(className){
    var elements;

    if (document.getElementsByClassName)
    {
        elements = document.getElementsByClassName(className);
    }
    else
    {
        var elArray = [];
        var tmp = document.getElementsByTagName(elements);  
        var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
        for ( var i = 0; i < tmp.length; i++ ) {

            if ( regex.test(tmp[i].className) ) {
                elArray.push(tmp[i]);
            }
        }

        elements = elArray;
    }

    for(var i = 0, i < elements.length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>

Why does the JFrame setSize() method not set the size correctly?

It's probably because size of a frame includes the size of the border.

A Frame is a top-level window with a title and a border. The size of the frame includes any area designated for the border. The dimensions of the border area may be obtained using the getInsets method. Since the border area is included in the overall size of the frame, the border effectively obscures a portion of the frame, constraining the area available for rendering and/or displaying subcomponents to the rectangle which has an upper-left corner location of (insets.left, insets.top), and has a size of width - (insets.left + insets.right) by height - (insets.top + insets.bottom).

Source: http://download.oracle.com/javase/tutorial/uiswing/components/frame.html

How to show x and y axes in a MATLAB graph?

Easiest solution:

plot([0,0],[0.0], xData, yData);

This creates an invisible line between the points [0,0] to [0,0] and since Matlab wants to include these points it will shows the axis.

Speed tradeoff of Java's -Xms and -Xmx options

This was always the question I had when I was working on one of my application which created massive number of threads per request.

So this is a really good question and there are two aspects of this:
1. Whether my Xms and Xmx value should be same
       - Most websites and even oracle docs suggest it to be the same. However, I suggest to have some 10-20% of buffer between those values to give heap resizing an option to your application in case sudden high traffic spikes OR a incidental memory leak.

2. Whether I should start my Application with lower heap size
       - So here's the thing - no matter what GC Algo you use (even G1), large heap always has some trade off. The goal is to identify the behavior of your application to what heap size you can allow your GC pauses in terms of latency and throughput.
              - For example, if your application has lot of threads (each thread has 1 MB stack in native memory and not in heap) but does not occupy heavy object space, then I suggest have a lower value of Xms.
              - If your application creates lot of objects with increasing number of threads, then identify to what value of Xms you can set to tolerate those STW pauses. This means identify the max response time of your incoming requests you can tolerate and according tune the minimum heap size.

SQL Server 2008 - Login failed. The login is from an untrusted domain and cannot be used with Windows authentication

Do you specify a user name and password to log on? What exactly is your complete command line?

If you're running on your own box, you can either specify a username/password, or use the -E parameter to log on with your Windows credentials (if those are permitted in your SQL server installation).

Marc

How to give a pandas/matplotlib bar graph custom colors

You can specify the color option as a list directly to the plot function.

from matplotlib import pyplot as plt
from itertools import cycle, islice
import pandas, numpy as np  # I find np.random.randint to be better

# Make the data
x = [{i:np.random.randint(1,5)} for i in range(10)]
df = pandas.DataFrame(x)

# Make a list by cycling through the colors you care about
# to match the length of your data.
my_colors = list(islice(cycle(['b', 'r', 'g', 'y', 'k']), None, len(df)))

# Specify this list of colors as the `color` option to `plot`.
df.plot(kind='bar', stacked=True, color=my_colors)

To define your own custom list, you can do a few of the following, or just look up the Matplotlib techniques for defining a color item by its RGB values, etc. You can get as complicated as you want with this.

my_colors = ['g', 'b']*5 # <-- this concatenates the list to itself 5 times.
my_colors = [(0.5,0.4,0.5), (0.75, 0.75, 0.25)]*5 # <-- make two custom RGBs and repeat/alternate them over all the bar elements.
my_colors = [(x/10.0, x/20.0, 0.75) for x in range(len(df))] # <-- Quick gradient example along the Red/Green dimensions.

The last example yields the follow simple gradient of colors for me:

enter image description here

I didn't play with it long enough to figure out how to force the legend to pick up the defined colors, but I'm sure you can do it.

In general, though, a big piece of advice is to just use the functions from Matplotlib directly. Calling them from Pandas is OK, but I find you get better options and performance calling them straight from Matplotlib.

What is the significance of 1/1/1753 in SQL Server?

Incidentally, Windows no longer knows how to correctly convert UTC to U.S. local time for certain dates in March/April or October/November of past years. UTC-based timestamps from those dates are now somewhat nonsensical. It would be very icky for the OS to simply refuse to handle any timestamps prior to the U.S. government's latest set of DST rules, so it simply handles some of them wrong. SQL Server refuses to process dates before 1753 because lots of extra special logic would be required to handle them correctly and it doesn't want to handle them wrong.

How to run bootRun with spring profile via gradle task

Using this shell command it will work:

SPRING_PROFILES_ACTIVE=test gradle clean bootRun

Sadly this is the simplest way I have found. It sets environment property for that call and then runs the app.

Why is python setup.py saying invalid command 'bdist_wheel' on Travis CI?

Jan 2020

2 hours wasted.

On a AWS Ubuntu 18.04 new machine, below installations are required:

sudo apt-get install gcc libpq-dev -y
sudo apt-get install python-dev  python-pip -y
sudo apt-get install python3-dev python3-pip python3-venv python3-wheel -y
pip3 install wheel

Especially the last line is must.
However before 3 lines might be required as prerequisites.

Hope that helps.

Bulk Record Update with SQL

Your way is correct, and here is another way you can do it:

update      Table1
set         Description = t2.Description
from        Table1 t1
inner join  Table2 t2
on          t1.DescriptionID = t2.ID

The nested select is the long way of just doing a join.

Calculating Distance between two Latitude and Longitude GeoCoordinates

Calculating Distance between Latitude and Longitude points...

        double Lat1 = Convert.ToDouble(latitude);
        double Long1 = Convert.ToDouble(longitude);

        double Lat2 = 30.678;
        double Long2 = 45.786;
        double circumference = 40000.0; // Earth's circumference at the equator in km
        double distance = 0.0;
        double latitude1Rad = DegreesToRadians(Lat1);
        double latititude2Rad = DegreesToRadians(Lat2);
        double longitude1Rad = DegreesToRadians(Long1);
        double longitude2Rad = DegreesToRadians(Long2);
        double logitudeDiff = Math.Abs(longitude1Rad - longitude2Rad);
        if (logitudeDiff > Math.PI)
        {
            logitudeDiff = 2.0 * Math.PI - logitudeDiff;
        }
        double angleCalculation =
            Math.Acos(
              Math.Sin(latititude2Rad) * Math.Sin(latitude1Rad) +
              Math.Cos(latititude2Rad) * Math.Cos(latitude1Rad) * Math.Cos(logitudeDiff));
        distance = circumference * angleCalculation / (2.0 * Math.PI);
        return distance;

Remove useless zero digits from decimals in PHP

Be careful with adding +0.

echo number_format(1500.00, 2,".",",")+0;
//1

Result of this is 1.

echo floatval('1,000.00');
// 1

echo floatval('1000.00');
//1000

How do I tell Maven to use the latest version of a dependency?

Are you possibly depending on development versions that obviously change a lot during development?

Instead of incrementing the version of development releases, you could just use a snapshot version that you overwrite when necessary, which means you wouldn't have to change the version tag on every minor change. Something like 1.0-SNAPSHOT...

But maybe you are trying to achieve something else ;)

Invalid http_host header

In your project settings.py file,set ALLOWED_HOSTS like this :

ALLOWED_HOSTS = ['62.63.141.41', 'namjoosadr.com']

and then restart your apache. in ubuntu:

/etc/init.d/apache2 restart

Parcelable encountered IOException writing serializable object getactivity()

Need to change all arraylist to Serializable wif in bean class :

public static class PremiumListBean  implements Serializable {
    private List<AddOnValueBean> AddOnValue;

    public List<AddOnValueBean> getAddOnValue() {
        return AddOnValue;
     }

    public void setAddOnValue(List<AddOnValueBean> AddOnValue) {
        this.AddOnValue = AddOnValue;
    }


    public static class AddOnValueBean  implements Serializable{

        @SerializedName("Premium")
        private String Premium;

        public String getPremium() {
            return Premium;
        }

        public void setPremium(String Premium) {
            this.Premium = Premium;
        }
    }
 }

How to send email from MySQL 5.1

If you have an SMTP service running, you can outfile to the drop directory. If you have high volume, you may result with duplicate file names, but there are ways to avoid that.

Otherwise, you will need to create a UDF.

Here's a sample trigger solution:

CREATE TRIGGER test.autosendfromdrop BEFORE INSERT ON test.emaildrop
FOR EACH ROW BEGIN
      /* START THE WRITING OF THE EMAIL FILE HERE*/      
      SELECT  concat("To: ",NEW.To),
              concat("From: ",NEW.From),
              concat("Subject: ",NEW.Subject),
              NEW.Body
          INTO OUTFILE 
                   "C:\\inetpub\\mailroot\\pickup\\mail.txt" 
              FIELDS TERMINATED by '\r\n' ESCAPED BY '';            
END;

To markup the message body you will need something like this...

CREATE FUNCTION `HTMLBody`(Msg varchar(8192)) 
    RETURNS varchar(17408) CHARSET latin1 DETERMINISTIC
BEGIN
  declare tmpMsg varchar(17408);
  set tmpMsg = cast(concat(
      'Date: ',date_format(NOW(),'%e %b %Y %H:%i:%S -0600'),'\r\n',
      'MIME-Version: 1.0','\r\n',
      'Content-Type: multipart/alternative;','\r\n',
      ' boundary=\"----=_NextPart_000_0000_01CA4B3F.8C263EE0\"','\r\n',
      'Content-Class: urn:content-classes:message','\r\n',
      'Importance: normal','\r\n',
      'Priority: normal','\r\n','','\r\n','','\r\n',
      'This is a multi-part message in MIME format.','\r\n','','\r\n',
      '------=_NextPart_000_0000_01CA4B3F.8C263EE0','\r\n',
      'Content-Type: text/plain;','\r\n',
      '  charset=\"iso-8859-1\"','\r\n',
      'Content-Transfer-Encoding: 7bit','\r\n','','\r\n','','\r\n',
      Msg,
      '\r\n','','\r\n','','\r\n',
      '------=_NextPart_000_0000_01CA4B3F.8C263EE0','\r\n',
      'Content-Type: text/html','\r\n',
      'Content-Transfer-Encoding: 7bit','\r\n','','\r\n',
      Msg,
      '\r\n','------=_NextPart_000_0000_01CA4B3F.8C263EE0--'
      ) as char);
  RETURN tmpMsg;
END ;

Using prepared statements with JDBCTemplate

I'd factor out the prepared statement handling to at least a method. In this case, because there are no results it is fairly simple (and assuming that the connection is an instance variable that doesn't change):

private PreparedStatement updateSales;
public void updateSales(int sales, String cof_name) throws SQLException {
    if (updateSales == null) {
        updateSales = con.prepareStatement(
            "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
    }
    updateSales.setInt(1, sales);
    updateSales.setString(2, cof_name);
    updateSales.executeUpdate();
}

At that point, it is then just a matter of calling:

updateSales(75, "Colombian");

Which is pretty simple to integrate with other things, yes? And if you call the method many times, the update will only be constructed once and that will make things much faster. Well, assuming you don't do crazy things like doing each update in its own transaction...

Note that the types are fixed. This is because for any particular query/update, they should be fixed so as to allow the database to do its job efficiently. If you're just pulling arbitrary strings from a CSV file, pass them in as strings. There's also no locking; far better to keep individual connections to being used from a single thread instead.

Import / Export database with SQL Server Server Management Studio

I tried the answers above but the generated script file was very large and I was having problems while importing the data. I ended up Detaching the database, then copying .mdf to my new machine, then Attaching it to my new version of SQL Server Management Studio.

I found instructions for how to do this on the Microsoft Website:
https://msdn.microsoft.com/en-us/library/ms187858.aspx

NOTE: After Detaching the database I found the .mdf file within this directory:
C:\Program Files\Microsoft SQL Server\

How can I position my jQuery dialog to center?

Following position parameter worked for me

position: { my: "right bottom", at: "center center", of: window },

Good luck!

fatal: could not create work tree dir 'kivy'

If you are working on a mac, then this is probably because you don't have permission to write to the directory. When I had this issue, I followed the following steps:

  • Opened the folder in finder -> right-click -> get info -> click on the lock on the bottom right of the pop up window, enter admin password -> then change the Sharing and Permissions to Read and Write for wheel, and everyone -> click lock again to save

MySQL dump by query

You could use --where option on mysqldump to produce an output that you are waiting for:

mysqldump -u root -p test t1 --where="1=1 limit 100" > arquivo.sql

At most 100 rows from test.t1 will be dumped from database table.

Cheers, WB

For loop in Objective-C

You mean fast enumeration? You question is very unclear.

A normal for loop would look a bit like this:

unsigned int i, cnt = [someArray count];
for(i = 0; i < cnt; i++)
{ 
   // do loop stuff
   id someObject = [someArray objectAtIndex:i];
}

And a loop with fast enumeration, which is optimized by the compiler, would look like this:

for(id someObject in someArray)
{
   // do stuff with object
}

Keep in mind that you cannot change the array you are using in fast enumeration, thus no deleting nor adding when using fast enumeration

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

So here is a simple example of how to use classes: Suppose you are a finance institute. You want your customer's accounts to be managed by a computer. So you need to model those accounts. That is where classes come in. Working with classes is called object oriented programming. With classes you model real world objects in your computer. So, what do we need to model a simple bank account? We need a variable that saves the balance and one that saves the customers name. Additionally, some methods to in- and decrease the balance. That could look like:

class bankaccount():
    def __init__(self, name, money):
        self.name = name
        self.money = money

    def earn_money(self, amount):
        self.money += amount

    def withdraw_money(self, amount):
        self.money -= amount

    def show_balance(self):
        print self.money

Now you have an abstract model of a simple account and its mechanism. The def __init__(self, name, money) is the classes' constructor. It builds up the object in memory. If you now want to open a new account you have to make an instance of your class. In order to do that, you have to call the constructor and pass the needed parameters. In Python a constructor is called by the classes's name:

spidermans_account = bankaccount("SpiderMan", 1000)

If Spiderman wants to buy M.J. a new ring he has to withdraw some money. He would call the withdraw method on his account:

spidermans_account.withdraw_money(100)

If he wants to see the balance he calls:

spidermans_account.show_balance()

The whole thing about classes is to model objects, their attributes and mechanisms. To create an object, instantiate it like in the example. Values are passed to classes with getter and setter methods like `earn_money()´. Those methods access your objects variables. If you want your class to store another object you have to define a variable for that object in the constructor.

How do I change button size in Python?

Configuring a button (or any widget) in Tkinter is done by calling a configure method "config"

To change the size of a button called button1 you simple call

button1.config( height = WHATEVER, width = WHATEVER2 )

If you know what size you want at initialization these options can be added to the constructor.

button1 = Button(self, text = "Send", command = self.response1, height = 100, width = 100) 

Adding Only Untracked Files

git ls-files -o --exclude-standard gives untracked files, so you can do something like below ( or add an alias to it):

git add $(git ls-files -o --exclude-standard)

Eslint: How to disable "unexpected console statement" in Node.js?

Create a .eslintrc.js in the directory of your file, and put the following contents in it:

module.exports = {
    rules: {
        'no-console': 'off',
    },
};

GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion

Try a different protocol. git:// may have problems from your firewall, for example; try a git clone with https: instead.

How to set default value for form field in Symfony2?

My solution:

$defaultvalue = $options['data']->getMyField();
$builder->add('myField', 'number', array(
            'data' => !empty($defaultvalue) ? $options['data']->getMyField() : 0
        )) ;

Where can I download an offline installer of Cygwin?

You can download from below link. ftp://ftp.comtrol.com/dev_mstr/sdk/other/1800136.tar.gz After downloading just extract the image and install.

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

Many of the examples here will not work for 11, 12, 13. This is more generic and will work for all case.

switch (date) {
                case 1:
                case 21:
                case 31:
                    return "" + date + "st";

                case 2:
                case 22:
                    return "" + date + "nd";

                case 3:
                case 23:
                    return "" + date + "rd";

                default:
                    return "" + date + "th";
}

Pull all images from a specified directory and then display them

In case anyone is looking for recursive.

<?php

echo scanDirectoryImages("images");

/**
 * Recursively search through directory for images and display them
 * 
 * @param  array  $exts
 * @param  string $directory
 * @return string
 */
function scanDirectoryImages($directory, array $exts = array('jpeg', 'jpg', 'gif', 'png'))
{
    if (substr($directory, -1) == '/') {
        $directory = substr($directory, 0, -1);
    }
    $html = '';
    if (
        is_readable($directory)
        && (file_exists($directory) || is_dir($directory))
    ) {
        $directoryList = opendir($directory);
        while($file = readdir($directoryList)) {
            if ($file != '.' && $file != '..') {
                $path = $directory . '/' . $file;
                if (is_readable($path)) {
                    if (is_dir($path)) {
                        return scanDirectoryImages($path, $exts);
                    }
                    if (
                        is_file($path)
                        && in_array(end(explode('.', end(explode('/', $path)))), $exts)
                    ) {
                        $html .= '<a href="' . $path . '"><img src="' . $path
                            . '" style="max-height:100px;max-width:100px" /></a>';
                    }
                }
            }
        }
        closedir($directoryList);
    }
    return $html;
}

Changing CSS for last <li>

If you know there are three li's in the list you're looking at, for example, you could do this:

li + li + li { /* Selects third to last li */
}

In IE6 you can use expressions:

li {
    color: expression(this.previousSibling ? 'red' : 'green'); /* 'green' if last child */
}

I would recommend using a specialized class or Javascript (not IE6 expressions), though, until the :last-child selector gets better support.

Could not resolve '...' from state ''

Had the same issue with Ionic routing.

Simple solution is to use the name of the state - basically state.go(state name)

.state('tab.search', {
    url: '/search',
    views: {
      'tab-search': {
        templateUrl: 'templates/search.html',
        controller: 'SearchCtrl'
      }
    }
  })

And in controller you can use $state.go('tab.search');

How to let an ASMX file output JSON

A quick gotcha that I learned the hard way (basically spending 4 hours on Google), you can use PageMethods in your ASPX file to return JSON (with the [ScriptMethod()] marker) for a static method, however if you decide to move your static methods to an asmx file, it cannot be a static method.

Also, you need to tell the web service Content-Type: application/json in order to get JSON back from the call (I'm using jQuery and the 3 Mistakes To Avoid When Using jQuery article was very enlightening - its from the same website mentioned in another answer here).

How to add element to C++ array?

Use a vector:

#include <vector>

void foo() {
    std::vector <int> v;
    v.push_back( 1 );       // equivalent to v[0] = 1
}

python convert list to dictionary

If you are still thinking what the! You would not be alone, its actually not that complicated really, let me explain.

How to turn a list into a dictionary using built-in functions only

We want to turn the following list into a dictionary using the odd entries (counting from 1) as keys mapped to their consecutive even entries.

l = ["a", "b", "c", "d", "e"]

dict()

To create a dictionary we can use the built in dict function for Mapping Types as per the manual the following methods are supported.

dict(one=1, two=2)
dict({'one': 1, 'two': 2})
dict(zip(('one', 'two'), (1, 2)))
dict([['two', 2], ['one', 1]])

The last option suggests that we supply a list of lists with 2 values or (key, value) tuples, so we want to turn our sequential list into:

l = [["a", "b"], ["c", "d"], ["e",]]

We are also introduced to the zip function, one of the built-in functions which the manual explains:

returns a list of tuples, where the i-th tuple contains the i-th element from each of the arguments

In other words if we can turn our list into two lists a, c, e and b, d then zip will do the rest.

slice notation

Slicings which we see used with Strings and also further on in the List section which mainly uses the range or short slice notation but this is what the long slice notation looks like and what we can accomplish with step:

>>> l[::2]
['a', 'c', 'e']

>>> l[1::2]
['b', 'd']

>>> zip(['a', 'c', 'e'], ['b', 'd'])
[('a', 'b'), ('c', 'd')]

>>> dict(zip(l[::2], l[1::2]))
{'a': 'b', 'c': 'd'}

Even though this is the simplest way to understand the mechanics involved there is a downside because slices are new list objects each time, as can be seen with this cloning example:

>>> a = [1, 2, 3]
>>> b = a
>>> b
[1, 2, 3]

>>> b is a
True

>>> b = a[:]
>>> b
[1, 2, 3]

>>> b is a
False

Even though b looks like a they are two separate objects now and this is why we prefer to use the grouper recipe instead.

grouper recipe

Although the grouper is explained as part of the itertools module it works perfectly fine with the basic functions too.

Some serious voodoo right? =) But actually nothing more than a bit of syntax sugar for spice, the grouper recipe is accomplished by the following expression.

*[iter(l)]*2

Which more or less translates to two arguments of the same iterator wrapped in a list, if that makes any sense. Lets break it down to help shed some light.

zip for shortest

>>> l*2
['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e']

>>> [l]*2
[['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']]

>>> [iter(l)]*2
[<listiterator object at 0x100486450>, <listiterator object at 0x100486450>]

>>> zip([iter(l)]*2)
[(<listiterator object at 0x1004865d0>,),(<listiterator object at 0x1004865d0>,)]

>>> zip(*[iter(l)]*2)
[('a', 'b'), ('c', 'd')]

>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd'}

As you can see the addresses for the two iterators remain the same so we are working with the same iterator which zip then first gets a key from and then a value and a key and a value every time stepping the same iterator to accomplish what we did with the slices much more productively.

You would accomplish very much the same with the following which carries a smaller What the? factor perhaps.

>>> it = iter(l)     
>>> dict(zip(it, it))
{'a': 'b', 'c': 'd'}

What about the empty key e if you've noticed it has been missing from all the examples which is because zip picks the shortest of the two arguments, so what are we to do.

Well one solution might be adding an empty value to odd length lists, you may choose to use append and an if statement which would do the trick, albeit slightly boring, right?

>>> if len(l) % 2:
...     l.append("")

>>> l
['a', 'b', 'c', 'd', 'e', '']

>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': ''}

Now before you shrug away to go type from itertools import izip_longest you may be surprised to know it is not required, we can accomplish the same, even better IMHO, with the built in functions alone.

map for longest

I prefer to use the map() function instead of izip_longest() which not only uses shorter syntax doesn't require an import but it can assign an actual None empty value when required, automagically.

>>> l = ["a", "b", "c", "d", "e"]
>>> l
['a', 'b', 'c', 'd', 'e']

>>> dict(map(None, *[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': None} 

Comparing performance of the two methods, as pointed out by KursedMetal, it is clear that the itertools module far outperforms the map function on large volumes, as a benchmark against 10 million records show.

$ time python -c 'dict(map(None, *[iter(range(10000000))]*2))'
real    0m3.755s
user    0m2.815s
sys     0m0.869s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(10000000))]*2, fillvalue=None))'
real    0m2.102s
user    0m1.451s
sys     0m0.539s

However the cost of importing the module has its toll on smaller datasets with map returning much quicker up to around 100 thousand records when they start arriving head to head.

$ time python -c 'dict(map(None, *[iter(range(100))]*2))'
real    0m0.046s
user    0m0.029s
sys     0m0.015s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100))]*2, fillvalue=None))'
real    0m0.067s
user    0m0.042s
sys     0m0.021s

$ time python -c 'dict(map(None, *[iter(range(100000))]*2))'
real    0m0.074s
user    0m0.050s
sys     0m0.022s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100000))]*2, fillvalue=None))'
real    0m0.075s
user    0m0.047s
sys     0m0.024s

See nothing to it! =)

nJoy!

Representing null in JSON

I would pick "default" for data type of variable (null for strings/objects, 0 for numbers), but indeed check what code that will consume the object expects. Don't forget there there is sometimes distinction between null/default vs. "not present".

Check out null object pattern - sometimes it is better to pass some special object instead of null (i.e. [] array instead of null for arrays or "" for strings).

Select a Dictionary<T1, T2> with LINQ

var dictionary = (from x in y 
                  select new SomeClass
                  {
                      prop1 = value1,
                      prop2 = value2
                  }
                  ).ToDictionary(item => item.prop1);

That's assuming that SomeClass.prop1 is the desired Key for the dictionary.

Easy way to use variables of enum types as string in C?

Here is a solution using macros with the following features:

  1. only write each value of the enum once, so there are no double lists to maintain

  2. don't keep the enum values in a separate file that is later #included, so I can write it wherever I want

  3. don't replace the enum itself, I still want to have the enum type defined, but in addition to it I want to be able to map every enum name to the corresponding string (to not affect legacy code)

  4. the searching should be fast, so preferably no switch-case, for those huge enums

https://stackoverflow.com/a/20134475/1812866

Best practice for using assert?

"assert" statements are removed when the compilation is optimized. So, yes, there are both performance and functional differences.

The current code generator emits no code for an assert statement when optimization is requested at compile time. - Python 2 Docs Python 3 Docs

If you use assert to implement application functionality, then optimize the deployment to production, you will be plagued by "but-it-works-in-dev" defects.

See PYTHONOPTIMIZE and -O -OO

how to create a list of lists

Use append method, eg:

lst = []
line = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1)
lst.append(line)

Android: alternate layout xml for landscape mode

In the current version of Android Studio (v1.0.2) you can simply add a landscape layout by clicking on the button in the visual editor shown in the screenshot below. Select "Create Landscape Variation"

Android Studio add landscape layout

Replace whitespace with a comma in a text file in Linux

without looking at your input file, only a guess

awk '{$1=$1}1' OFS=","

redirect to another file and rename as needed

How to make the Facebook Like Box responsive?

I was trying to do this on Drupal 7 with the " fb_likebox" module (https://drupal.org/project/fb_likebox). To get it to be responsive. Turns out I had to write my own Contrib module Variation and stripe out the width setting option. (the default height option didn't matter for me). Once I removed the width, I added the <div id="likebox-wrapper"> in the fb_likebox.tpl.php.

Here's my CSS to style it:

 `#likebox-wrapper * {
  width: 100% !important;
  background: url('../images/block.png') repeat 0 0;
  color: #fbfbfb;
 -webkit-border-radius: 7px;
  -moz-border-radius: 7px;
   -o-border-radius: 7px;
  border-radius: 7px;
   border: 1px solid #DDD;}`

How to get the hostname of the docker host from inside a docker container on that host without env vars

You can pass it as an environment variable like this. Generally Node is the host that it is running in. The hostname is defaulted to the host name of the node when it is created.

docker service create -e 'FOO={{.Node.Hostname}}' nginx  

Then you can do docker ps to get the process ID and look at the env

$ docker exec -it c81640b6d1f1 env                                                                                                                                    PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=c81640b6d1f1
TERM=xterm
FOO=docker-desktop
NGINX_VERSION=1.17.4
NJS_VERSION=0.3.5
PKG_RELEASE=1~buster
HOME=/root

An example of usage would be with metricbeats so you know which node is having system issues which I put in https://github.com/trajano/elk-swarm:

  metricbeat:
    image: docker.elastic.co/beats/metricbeat:7.4.0
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - /sys/fs/cgroup:/hostfs/sys/fs/cgroup:ro
      - /proc:/hostfs/proc:ro
      - /:/hostfs:ro
    user: root
    hostname: "{{.Node.Hostname}}"
    command:
      - -E
      - |
        metricbeat.modules=[
          {
            module:docker,
            hosts:[unix:///var/run/docker.sock],
            period:10s,
            enabled:true
          }
        ] 
      - -E
      - processors={1:{add_docker_metadata:{host:unix:///var/run/docker.sock}}} 
      - -E
      - output.elasticsearch.enabled=false
      - -E
      - output.logstash.enabled=true
      - -E
      - output.logstash.hosts=["logstash:5044"]
    deploy:
      mode: global

How to construct a std::string from a std::vector<char>?

I think you can just do

std::string s( MyVector.begin(), MyVector.end() );

where MyVector is your std::vector.

Installing Oracle Instant Client

The instantclient works only by defining the folder in the windows PATH environment variable. But you can "install" manually to create some keys in the Windows registry. How?

1) Download instantclient (http://www.oracle.com/technetwork/topics/winsoft-085727.html)

2) Unzip the ZIP file (eg c:\oracle\instantclient).

3) Include the above path in the PATH. Set PATH in Windows

4) Create the registry key:

  • Windows 32bit: [HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE]
  • Windows 64bit: [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE]

5) In the above registry key, create a sub-key starts with "KEY_" followed by the name of the installation you want:

  • Windows 32bit: [HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\KEY_INSTANTCLIENT]
  • Windows 64bit: [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE\KEY_INSTANTCLIENT]

6) Now create at least three string values ??in the above key:

registry keys for Oracle Home

For those who use Quest SQL Navigator or Quest Toad for Oracle will see that it works. Displays the message "Home is valid.":

Displays the message "Home is valid." in Quest Toad (or SQL Navigator)

The registry keys are now displayed for selecting the oracle client:

selecting the oracle client in Quest SQL Navigator

C# Clear Session

The other big difference is Abandon does not remove items immediately, but when it does then cleanup it does a loop over session items to check for STA COM objects it needs to handle specially. And this can be a problem.

Under high load it's possible for two (or more) requests to make it to the server for the same session (that is two requests with the same session cookie). Their execution will be serialized, but since Abandon doesn't clear out the items synchronously but rather sets a flag it's possible for both requests to run, and both requests to schedule a work item to clear out session "later". Both these work items can then run at the same time, and both are checking the session objects, and both are clearing out the array of objects, and what happens when you have two things iterating over a list and changing it?? Boom! And since this happens in a queueuserworkitem callback and is NOT done in a try/catch (thanks MS), it will bring down your entire app domain. Been there.

How to configure the web.config to allow requests of any length

In my case ( Visual Studio 2012 / IIS Express / ASP.NET MVC 4 app / .Net Framework 4.5 ) what really worked after 30 minutes of trial and error was setting the maxQueryStringLength property in the <httpRuntime> tag:

<httpRuntime targetFramework="4.5" maxQueryStringLength="10240" enable="true" />

maxQueryStringLength defaults to 2048.

More about it here:

Expanding the Range of Allowable URLs


I tried setting it in <system.webServer> as @MattVarblow suggests, but it didn't work... and this is because I'm using IIS Express (based on IIS 8) on my dev machine with Windows 8.

When I deployed my app to the production environment (Windows Server 2008 R2 with IIS 7), IE 10 started returning 404 errors in AJAX requests with long query strings. Then I thought that the problem was related to the query string and tried @MattVarblow's answer. It just worked on IIS 7. :)

How to capture a JFrame's close button click event?

Try this:

setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

It will work.

java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

I had the same exception in the simulator (Android Studio on OSX) but connecting to the same URL on the iOS simulator worked fine... Looks like it all stemmed from the fact I'd be running the simulator whilst connected to a personal hotspot for my internet connection and then came back later while connected to wifi and the simulator didn't like the new internet connection for some reason, seems like it thought the old hotspot was the current connection, which was no longer working..

Closing and relaunching the simulator worked!

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

How to read a file into a variable in shell?

You can access 1 line at a time by for loop

#!/bin/bash -eu

#This script prints contents of /etc/passwd line by line

FILENAME='/etc/passwd'
I=0
for LN in $(cat $FILENAME)
do
    echo "Line number $((I++)) -->  $LN"
done

Copy the entire content to File (say line.sh ) ; Execute

chmod +x line.sh
./line.sh

Including one C source file in another?

is it ok? yes, it will compile

is it recommended? no - .c files compile to .obj files, which are linked together after compilation (by the linker) into the executable (or library), so there is no need to include one .c file in another. What you probably want to do instead is to make a .h file that lists the functions/variables available in the other .c file, and include the .h file

What is the Windows equivalent of the diff command?

Well, on Windows I happily run diff and many other of the GNU tools. You can do it with cygwin, but I personally prefer GnuWin32 because it is a much lighter installation experience.

So, my answer is that the Windows equivalent of diff, is none other than diff itself!

How to list the properties of a JavaScript object?

if you are trying to get the elements only but not the functions then this code can help you

this.getKeys = function() {

    var keys = new Array();
    for(var key in this) {

        if( typeof this[key] !== 'function') {

            keys.push(key);
        }
    }
    return keys;
}

this is part of my implementation of the HashMap and I only want the keys, "this" is the hashmap object that contains the keys

Using Server.MapPath in external C# Classes in ASP.NET

Whether you're running within the context of ASP.NET or not, you should be able to use HostingEnvironment.ApplicationPhysicalPath

How to right align widget in horizontal linear layout Android?

In case with TextView:

<TextView 
    android:text="TextView" 
    android:id="@+id/textView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"   
    android:gravity="right"
    android:textAlignment="gravity">    
</TextView>

How to implement a material design circular progress bar in android

Nice implementation for material design circular progress bar (from rahatarmanahmed/CircularProgressView),

<com.github.rahatarmanahmed.cpv.CircularProgressView
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/progress_view"
    android:layout_width="40dp"
    android:layout_height="40dp"
    app:cpv_indeterminate="true"/>

enter image description here

Best way to find os name and version in Unix/Linux platform

I prepared following commands to find concise information about a Linux system:

clear
echo "\n----------OS Information------------"
hostnamectl | grep "Static hostname:"
hostnamectl | tail -n 3
echo "\n----------Memory Information------------"
cat /proc/meminfo | grep MemTotal
echo "\n----------CPU Information------------"
echo -n "Number of core(s): "
cat /proc/cpuinfo | grep "processor" | wc -l
cat /proc/cpuinfo | grep "model name" | head -n 1
echo "\n----------Disk Information------------"
echo -n "Total Size: "
df -h --total | tail -n 1| awk '{print $2}'
echo -n "Used: "
df -h --total | tail -n 1| awk '{print $3}'
echo -n "Available: "
df -h --total | tail -n 1| awk '{print $4}'
echo "\n-------------------------------------\n"

Copy and paste in an sh file like info.sh and then run it using command sh info.sh

DateTime and CultureInfo

InvariantCulture is similar to en-US, so i would use the correct CultureInfo instead:

var dutchCulture = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCulture);

Demo

And what about when the culture is en-us? Will I have to code for every single language there is out there?

If you want to know how to display the date in another culture like "en-us", you can use date1.ToString(CultureInfo.CreateSpecificCulture("en-US")).

Find Locked Table in SQL Server

sp_lock

When reading sp_lock information, use the OBJECT_NAME( ) function to get the name of a table from its ID number, for example:

SELECT object_name(16003073)

EDIT :

There is another proc provided by microsoft which reports objects without the ID translation : http://support.microsoft.com/kb/q255596/

Redirecting from cshtml page

Change to this:

@{ Response.Redirect("~/HOME/NoResults");}

Argparse: Required arguments listed under "optional arguments"?

Since I prefer to list required arguments before optional, I hack around it via:

    parser = argparse.ArgumentParser()
    parser._action_groups.pop()
    required = parser.add_argument_group('required arguments')
    optional = parser.add_argument_group('optional arguments')
    required.add_argument('--required_arg', required=True)
    optional.add_argument('--optional_arg')
    return parser.parse_args()

and this outputs:

usage: main.py [-h] [--required_arg REQUIRED_ARG]
               [--optional_arg OPTIONAL_ARG]

required arguments:
  --required_arg REQUIRED_ARG

optional arguments:
  --optional_arg OPTIONAL_ARG

I can live without 'help' showing up in the optional arguments group.

Tar archiving that takes input from a list of files

Yes:

tar -cvf allfiles.tar -T mylist.txt

Rounding a number to the nearest 5 or 10 or X

Try this function

--------------start----------------

Function Round_Up(ByVal d As Double) As Integer
    Dim result As Integer
    result = Math.Round(d)
    If result >= d Then
        Round_Up = result
    Else
        Round_Up = result + 1
    End If
End Function

-------------end ------------