Programs & Examples On #Xmi

XML Metadata Interchange

Flutter: RenderBox was not laid out

You can add some code like this

ListView.builder{
   shrinkWrap: true,
}

How to completely uninstall python 2.7.13 on Ubuntu 16.04

How I do:

# Remove python2
sudo apt purge -y python2.7-minimal

# You already have Python3 but 
# don't care about the version 
sudo ln -s /usr/bin/python3 /usr/bin/python

# Same for pip
sudo apt install -y python3-pip
sudo ln -s /usr/bin/pip3 /usr/bin/pip

# Confirm the new version of Python: 3
python --version

Forward X11 failed: Network error: Connection refused

PuTTY can't find where your X server is, because you didn't tell it. (ssh on Linux doesn't have this problem because it runs under X so it just uses that one.) Fill in the blank box after "X display location" with your Xming server's address.

Alternatively, try MobaXterm. It has an X server builtin.

Is there any way to show a countdown on the lockscreen of iphone?

There is no way to display interactive elements on the lockscreen or wallpaper with a non jailbroken iPhone.

I would recommend Countdown Widget it's free an you can display countdowns in the notification center which you can also access from your lockscreen.

IndexError: too many indices for array

I think the problem is given in the error message, although it is not very easy to spot:

IndexError: too many indices for array
xs  = data[:, col["l1"     ]]

'Too many indices' means you've given too many index values. You've given 2 values as you're expecting data to be a 2D array. Numpy is complaining because data is not 2D (it's either 1D or None).

This is a bit of a guess - I wonder if one of the filenames you pass to loadfile() points to an empty file, or a badly formatted one? If so, you might get an array returned that is either 1D, or even empty (np.array(None) does not throw an Error, so you would never know...). If you want to guard against this failure, you can insert some error checking into your loadfile function.

I highly recommend in your for loop inserting:

print(data)

This will work in Python 2.x or 3.x and might reveal the source of the issue. You might well find it is only one value of your outputs_l1 list (i.e. one file) that is giving the issue.

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

Saving binary data as file using JavaScript from a browser

This is possible if the browser supports the download property in anchor elements.

var sampleBytes = new Int8Array(4096);

var saveByteArray = (function () {
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    return function (data, name) {
        var blob = new Blob(data, {type: "octet/stream"}),
            url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = name;
        a.click();
        window.URL.revokeObjectURL(url);
    };
}());

saveByteArray([sampleBytes], 'example.txt');


JSFiddle: http://jsfiddle.net/VB59f/2

How to use a parameter in ExecStart command line?

To attempt command line arguments directly is not possible.

One alternative might be environment variables (https://superuser.com/questions/728951/systemd-giving-my-service-multiple-arguments).

This is where I found the answer: http://www.freedesktop.org/software/systemd/man/systemctl.html

so sudo systemctl restart myprog -v -- systemctl will think you're trying to set one of its flags, not myprog's flag.

sudo systemctl restart myprog someotheroption -- systemctl will restart myprog and the someotheroption service, if it exists.

How to Create simple drag and Drop in angularjs

adapt-strap has very light weight module for this. here is the fiddle. Here are some attributes that are supported. There are more.

ad-drag="true"
ad-drag-data="car"
ad-drag-begin="onDragStart($data, $dragElement, $event);"
ad-drag-end="onDataEnd($data, $dragElement, $event);"

Error LNK2019: Unresolved External Symbol in Visual Studio

When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.

pandas resample documentation

There's more to it than this, but you're probably looking for this list:

B   business day frequency
C   custom business day frequency (experimental)
D   calendar day frequency
W   weekly frequency
M   month end frequency
BM  business month end frequency
MS  month start frequency
BMS business month start frequency
Q   quarter end frequency
BQ  business quarter endfrequency
QS  quarter start frequency
BQS business quarter start frequency
A   year end frequency
BA  business year end frequency
AS  year start frequency
BAS business year start frequency
H   hourly frequency
T   minutely frequency
S   secondly frequency
L   milliseconds
U   microseconds

Source: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases

vertical & horizontal lines in matplotlib

If you want to add a bounding box, use a rectangle:

ax = plt.gca()
r = matplotlib.patches.Rectangle((.5, .5), .25, .1, fill=False)
ax.add_artist(r)

Rectangle doc

How to automatically close cmd window after batch file execution?

Sometimes you can reference a Windows "shortcut" file to launch an application instead of using a ".bat" file, and it won't have the residual prompt problem. But it's not as flexible as bat files.

Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7

before start make sure of installation:

yum install -y xorg-x11-server-Xorg xorg-x11-xauth xorg-x11-apps
  1. start xming or cygwin
  2. make connection with X11 forwarding (in putty don't forget to set localhost:0.0 for X display location)
  3. edit sshd.cong and restart
     cat /etc/ssh/sshd_config | grep X
                             X11Forwarding yes
                             X11DisplayOffset 10
AddressFamily inet
  1. Without the X11 forwarding, you are subjected to the X11 SECURITY and then you must: authorize the remote server to make a connection with the local X Server using a method (for instance, the xhost command) set the display environment variable to redirect the output to the X server of your local computer. In this example: 192.168.2.223 is the IP of the server 192.168.2.2 is the IP of the local computer where the x server is installed. localhost can also be used.
blablaco@blablaco01 ~
$ xhost 192.168.2.223
192.168.2.223 being added to access control list

blablaco@blablaco01 ~
$ ssh -l root 192.168.2.223
[email protected] password:
Last login: Sat May 22 18:59:04 2010 from etcetc
[root@oel5u5 ~]# export DISPLAY=192.168.2.2:0.0
[root@oel5u5 ~]# echo $DISPLAY
192.168.2.2:0.0
[root@oel5u5 ~]# xclock&

Then the xclock application must launch.

Check it on putty or mobaxterm and don't check in remote desktop Manager software. Be careful for user that sudo in.

How to convert image into byte array and byte array to base64 String in android?

Try this simple solution to convert file to base64 string

String base64String = imageFileToByte(file);

public String imageFileToByte(File file){

    Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
    byte[] b = baos.toByteArray();
    return Base64.encodeToString(b, Base64.DEFAULT);
}

Where can I get a list of Countries, States and Cities?

This may be a sideways answer, but if you download Virtuemart (A Joomla component), it has a countries table and all the related states all set up for you included in the installation SQL. They're called jos_virtuemart_countries and jos_virtuemart_states. It also includes the 2 and 3 character country codes. I'd attach it to my answer, but don't see a way of doing it.

How do I compile jrxml to get jasper?

If you are using iReport you can easily do it.

  1. When you click preview it will automatically compile.
  2. There is an option to make it complie. You can compile by selecting the page then right click you will get the compile option.

How to extract the decimal part from a floating point number in C?

Try this:

int main() {
  double num = 23.345;
  int intpart = (int)num;
  double decpart = num - intpart;
  printf("Num = %f, intpart = %d, decpart = %f\n", num, intpart, decpart);
}

For me, it produces:

Num = 23.345000, intpart = 23, decpart = 0.345000

Which appears to be what you're asking for.

In practice, what are the main uses for the new "yield from" syntax in Python 3.3?

Let's get one thing out of the way first. The explanation that yield from g is equivalent to for v in g: yield v does not even begin to do justice to what yield from is all about. Because, let's face it, if all yield from does is expand the for loop, then it does not warrant adding yield from to the language and preclude a whole bunch of new features from being implemented in Python 2.x.

What yield from does is it establishes a transparent bidirectional connection between the caller and the sub-generator:

  • The connection is "transparent" in the sense that it will propagate everything correctly too, not just the elements being generated (e.g. exceptions are propagated).

  • The connection is "bidirectional" in the sense that data can be both sent from and to a generator.

(If we were talking about TCP, yield from g might mean "now temporarily disconnect my client's socket and reconnect it to this other server socket".)

BTW, if you are not sure what sending data to a generator even means, you need to drop everything and read about coroutines first—they're very useful (contrast them with subroutines), but unfortunately lesser-known in Python. Dave Beazley's Curious Course on Coroutines is an excellent start. Read slides 24-33 for a quick primer.

Reading data from a generator using yield from

def reader():
    """A generator that fakes a read from a file, socket, etc."""
    for i in range(4):
        yield '<< %s' % i

def reader_wrapper(g):
    # Manually iterate over data produced by reader
    for v in g:
        yield v

wrap = reader_wrapper(reader())
for i in wrap:
    print(i)

# Result
<< 0
<< 1
<< 2
<< 3

Instead of manually iterating over reader(), we can just yield from it.

def reader_wrapper(g):
    yield from g

That works, and we eliminated one line of code. And probably the intent is a little bit clearer (or not). But nothing life changing.

Sending data to a generator (coroutine) using yield from - Part 1

Now let's do something more interesting. Let's create a coroutine called writer that accepts data sent to it and writes to a socket, fd, etc.

def writer():
    """A coroutine that writes data *sent* to it to fd, socket, etc."""
    while True:
        w = (yield)
        print('>> ', w)

Now the question is, how should the wrapper function handle sending data to the writer, so that any data that is sent to the wrapper is transparently sent to the writer()?

def writer_wrapper(coro):
    # TBD
    pass

w = writer()
wrap = writer_wrapper(w)
wrap.send(None)  # "prime" the coroutine
for i in range(4):
    wrap.send(i)

# Expected result
>>  0
>>  1
>>  2
>>  3

The wrapper needs to accept the data that is sent to it (obviously) and should also handle the StopIteration when the for loop is exhausted. Evidently just doing for x in coro: yield x won't do. Here is a version that works.

def writer_wrapper(coro):
    coro.send(None)  # prime the coro
    while True:
        try:
            x = (yield)  # Capture the value that's sent
            coro.send(x)  # and pass it to the writer
        except StopIteration:
            pass

Or, we could do this.

def writer_wrapper(coro):
    yield from coro

That saves 6 lines of code, make it much much more readable and it just works. Magic!

Sending data to a generator yield from - Part 2 - Exception handling

Let's make it more complicated. What if our writer needs to handle exceptions? Let's say the writer handles a SpamException and it prints *** if it encounters one.

class SpamException(Exception):
    pass

def writer():
    while True:
        try:
            w = (yield)
        except SpamException:
            print('***')
        else:
            print('>> ', w)

What if we don't change writer_wrapper? Does it work? Let's try

# writer_wrapper same as above

w = writer()
wrap = writer_wrapper(w)
wrap.send(None)  # "prime" the coroutine
for i in [0, 1, 2, 'spam', 4]:
    if i == 'spam':
        wrap.throw(SpamException)
    else:
        wrap.send(i)

# Expected Result
>>  0
>>  1
>>  2
***
>>  4

# Actual Result
>>  0
>>  1
>>  2
Traceback (most recent call last):
  ... redacted ...
  File ... in writer_wrapper
    x = (yield)
__main__.SpamException

Um, it's not working because x = (yield) just raises the exception and everything comes to a crashing halt. Let's make it work, but manually handling exceptions and sending them or throwing them into the sub-generator (writer)

def writer_wrapper(coro):
    """Works. Manually catches exceptions and throws them"""
    coro.send(None)  # prime the coro
    while True:
        try:
            try:
                x = (yield)
            except Exception as e:   # This catches the SpamException
                coro.throw(e)
            else:
                coro.send(x)
        except StopIteration:
            pass

This works.

# Result
>>  0
>>  1
>>  2
***
>>  4

But so does this!

def writer_wrapper(coro):
    yield from coro

The yield from transparently handles sending the values or throwing values into the sub-generator.

This still does not cover all the corner cases though. What happens if the outer generator is closed? What about the case when the sub-generator returns a value (yes, in Python 3.3+, generators can return values), how should the return value be propagated? That yield from transparently handles all the corner cases is really impressive. yield from just magically works and handles all those cases.

I personally feel yield from is a poor keyword choice because it does not make the two-way nature apparent. There were other keywords proposed (like delegate but were rejected because adding a new keyword to the language is much more difficult than combining existing ones.

In summary, it's best to think of yield from as a transparent two way channel between the caller and the sub-generator.

References:

  1. PEP 380 - Syntax for delegating to a sub-generator (Ewing) [v3.3, 2009-02-13]
  2. PEP 342 - Coroutines via Enhanced Generators (GvR, Eby) [v2.5, 2005-05-10]

Find and copy files

for i in $(ls); do cp -r "$i" "$i"_dev; done;

Auto highlight text in a textbox control

 textBoxX1.Focus();
 this.ActiveControl = textBoxX1;
 textBoxX1.SelectAll();

How to use _CRT_SECURE_NO_WARNINGS

I was getting the same error in Visual Studio 2017 and to fix it just added #define _CRT_SECURE_NO_WARNINGS after #include "pch.h"

#include "pch.h"
#define _CRT_SECURE_NO_WARNINGS
....

Clear form fields with jQuery

Why does it need to be done with any JavaScript at all?

<form>
    <!-- snip -->
    <input type="reset" value="Reset"/>
</form>

http://www.w3.org/TR/html5/the-input-element.html#attr-input-type-keywords


Tried that one first, it won't clear fields with default values.

Here's a way to do it with jQuery, then:

$('.reset').on('click', function() {
    $(this).closest('form').find('input[type=text], textarea').val('');
});

Use of String.Format in JavaScript?

Without a third party function:

string format = "Hi {0}".replace('{0}', name)

With multiple params:

string format = "Hi {0} {1}".replace('{0}', name).replace('{1}', lastname)

Print all but the first three columns

Perl solution which does not add leading or trailing whitespace:

perl -lane 'splice @F,0,3; print join " ",@F' file

The perl @F autosplit array starts at index 0 while awk fields start with $1


Perl solution for comma-delimited data:

perl -F, -lane 'splice @F,0,3; print join ",",@F' file

Python solution:

python -c "import sys;[sys.stdout.write(' '.join(line.split()[3:]) + '\n') for line in sys.stdin]" < file

cell format round and display 2 decimal places

I use format, Number, 2 decimal places & tick ' use 1000 separater ', then go to 'File', 'Options', 'Advanced', scroll down to 'When calculating this workbook' and tick 'set precision as displayed'. You get an error message about losing accuracy, that's good as it means it is rounding to 2 decimal places. So much better than bothering with adding a needless ROUND function.

Why can templates only be implemented in the header file?

It's because of the requirement for separate compilation and because templates are instantiation-style polymorphism.

Lets get a little closer to concrete for an explanation. Say I've got the following files:

  • foo.h
    • declares the interface of class MyClass<T>
  • foo.cpp
    • defines the implementation of class MyClass<T>
  • bar.cpp
    • uses MyClass<int>

Separate compilation means I should be able to compile foo.cpp independently from bar.cpp. The compiler does all the hard work of analysis, optimization, and code generation on each compilation unit completely independently; we don't need to do whole-program analysis. It's only the linker that needs to handle the entire program at once, and the linker's job is substantially easier.

bar.cpp doesn't even need to exist when I compile foo.cpp, but I should still be able to link the foo.o I already had together with the bar.o I've only just produced, without needing to recompile foo.cpp. foo.cpp could even be compiled into a dynamic library, distributed somewhere else without foo.cpp, and linked with code they write years after I wrote foo.cpp.

"Instantiation-style polymorphism" means that the template MyClass<T> isn't really a generic class that can be compiled to code that can work for any value of T. That would add overhead such as boxing, needing to pass function pointers to allocators and constructors, etc. The intention of C++ templates is to avoid having to write nearly identical class MyClass_int, class MyClass_float, etc, but to still be able to end up with compiled code that is mostly as if we had written each version separately. So a template is literally a template; a class template is not a class, it's a recipe for creating a new class for each T we encounter. A template cannot be compiled into code, only the result of instantiating the template can be compiled.

So when foo.cpp is compiled, the compiler can't see bar.cpp to know that MyClass<int> is needed. It can see the template MyClass<T>, but it can't emit code for that (it's a template, not a class). And when bar.cpp is compiled, the compiler can see that it needs to create a MyClass<int>, but it can't see the template MyClass<T> (only its interface in foo.h) so it can't create it.

If foo.cpp itself uses MyClass<int>, then code for that will be generated while compiling foo.cpp, so when bar.o is linked to foo.o they can be hooked up and will work. We can use that fact to allow a finite set of template instantiations to be implemented in a .cpp file by writing a single template. But there's no way for bar.cpp to use the template as a template and instantiate it on whatever types it likes; it can only use pre-existing versions of the templated class that the author of foo.cpp thought to provide.

You might think that when compiling a template the compiler should "generate all versions", with the ones that are never used being filtered out during linking. Aside from the huge overhead and the extreme difficulties such an approach would face because "type modifier" features like pointers and arrays allow even just the built-in types to give rise to an infinite number of types, what happens when I now extend my program by adding:

  • baz.cpp
    • declares and implements class BazPrivate, and uses MyClass<BazPrivate>

There is no possible way that this could work unless we either

  1. Have to recompile foo.cpp every time we change any other file in the program, in case it added a new novel instantiation of MyClass<T>
  2. Require that baz.cpp contains (possibly via header includes) the full template of MyClass<T>, so that the compiler can generate MyClass<BazPrivate> during compilation of baz.cpp.

Nobody likes (1), because whole-program-analysis compilation systems take forever to compile , and because it makes it impossible to distribute compiled libraries without the source code. So we have (2) instead.

How do I implement a progress bar in C#?

When you perform operations on Background thread and you want to update UI, you can not call or set anything from background thread. In case of WPF you need Dispatcher.BeginInvoke and in case of WinForms you need Invoke method.

WPF:

// assuming "this" is the window containing your progress bar..
// following code runs in background worker thread...
for(int i=0;i<count;i++)
{
    DoSomething();
    this.Dispatcher.BeginInvoke((Action)delegate(){
         this.progressBar.Value = (int)((100*i)/count);
    });
}

WinForms:

// assuming "this" is the window containing your progress bar..
// following code runs in background worker thread...
for(int i=0;i<count;i++)
{
    DoSomething();
    this.Invoke(delegate(){
         this.progressBar.Value = (int)((100*i)/count);
    });
}

for WinForms delegate may require some casting or you may need little help there, dont remember the exact syntax now.

CSS grid wrapping

Here's my attempt. Excuse the fluff, I was feeling extra creative.

My method is a parent div with fixed dimensions. The rest is just fitting the content inside that div accordingly.

This will rescale the images regardless of the aspect ratio. There will be no hard cropping either.

_x000D_
_x000D_
body {_x000D_
    background: #131418;_x000D_
    text-align: center;_x000D_
    margin: 0 auto;_x000D_
}_x000D_
_x000D_
.my-image-parent {_x000D_
    display: inline-block;_x000D_
    width: 300px;_x000D_
    height: 300px;_x000D_
    line-height: 300px; /* Should match your div height */_x000D_
    text-align: center;_x000D_
    font-size: 0;_x000D_
}_x000D_
_x000D_
/* Start demonstration background fluff */_x000D_
    .bg1 {background: url(https://unsplash.it/801/799);}_x000D_
    .bg2 {background: url(https://unsplash.it/799/800);}_x000D_
    .bg3 {background: url(https://unsplash.it/800/799);}_x000D_
    .bg4 {background: url(https://unsplash.it/801/801);}_x000D_
    .bg5 {background: url(https://unsplash.it/802/800);}_x000D_
    .bg6 {background: url(https://unsplash.it/800/802);}_x000D_
    .bg7 {background: url(https://unsplash.it/802/802);}_x000D_
    .bg8 {background: url(https://unsplash.it/803/800);}_x000D_
    .bg9 {background: url(https://unsplash.it/800/803);}_x000D_
    .bg10 {background: url(https://unsplash.it/803/803);}_x000D_
    .bg11 {background: url(https://unsplash.it/803/799);}_x000D_
    .bg12 {background: url(https://unsplash.it/799/803);}_x000D_
    .bg13 {background: url(https://unsplash.it/806/799);}_x000D_
    .bg14 {background: url(https://unsplash.it/805/799);}_x000D_
    .bg15 {background: url(https://unsplash.it/798/804);}_x000D_
    .bg16 {background: url(https://unsplash.it/804/799);}_x000D_
    .bg17 {background: url(https://unsplash.it/804/804);}_x000D_
    .bg18 {background: url(https://unsplash.it/799/804);}_x000D_
    .bg19 {background: url(https://unsplash.it/798/803);}_x000D_
    .bg20 {background: url(https://unsplash.it/803/797);}_x000D_
/* end demonstration background fluff */_x000D_
_x000D_
.my-image {_x000D_
    width: auto;_x000D_
    height: 100%;_x000D_
    vertical-align: middle;_x000D_
    background-size: contain;_x000D_
    background-position: center;_x000D_
    background-repeat: no-repeat;_x000D_
}
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg1"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg2"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg3"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg4"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg5"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg6"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg7"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg8"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg9"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg10"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg11"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg12"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg13"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg14"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg15"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg16"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg17"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg18"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg19"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg20"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

Place @JsonIgnore on the field or its getter, or create a custom dto

@JsonIgnore
private String encryptedPwd;

or as mentioned above by ceekay annotate it with @JsonProperty where access attribute is set to write only

@JsonProperty( value = "password", access = JsonProperty.Access.WRITE_ONLY)
private String encryptedPwd;

Export data to Excel file with ASP.NET MVC 4 C# is rendering into view

You can call helper class in any controller

//view 
 @Html.ActionLink("Export to Excel", "Excel")

//controller Action
public void Excel()
{
    var model = db.GetModel()

    Export export = new Export();
    export.ToExcel(Response, model);
}

//helper class
public class Export
{        public void ToExcel(HttpResponseBase Response, object clientsList)
    {
        var grid = new System.Web.UI.WebControls.GridView();
        grid.DataSource = clientsList;
        grid.DataBind();
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
        Response.ContentType = "application/excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);

        grid.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }
}

Renaming columns in Pandas

Another way we could replace the original column labels is by stripping the unwanted characters (here '$') from the original column labels.

This could have been done by running a for loop over df.columns and appending the stripped columns to df.columns.

Instead, we can do this neatly in a single statement by using list comprehension like below:

df.columns = [col.strip('$') for col in df.columns]

(strip method in Python strips the given character from beginning and end of the string.)

How to fix missing dependency warning when using useEffect React Hook?

./src/components/BusinessesList.js
Line 51:  React Hook useEffect has a missing dependency: 'fetchBusinesses'.
Either include it or remove the dependency array  react-hooks/exhaustive-deps

It's not JS/React error but eslint (eslint-plugin-react-hooks) warning.

It's telling you that hook depends on function fetchBusinesses, so you should pass it as dependency.

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

It could result in invoking function every render if function is declared in component like:

const Component = () => {
  /*...*/

  //new function declaration every render
  const fetchBusinesses = () => {
    fetch('/api/businesses/')
      .then(...)
  }

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

  /*...*/
}

because every time function is redeclared with new reference

Correct way of doing this stuff is:

const Component = () => {
  /*...*/

  // keep function reference
  const fetchBusinesses = useCallback(() => {
    fetch('/api/businesses/')
      .then(...)
  }, [/* additional dependencies */]) 

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

  /*...*/
}

or just defining function in useEffect

More: https://github.com/facebook/react/issues/14920

android:layout_height 50% of the screen size

This kind of worked for me. Though FAB doesn't float independently, but now it isn't getting pushed down.

Observe the weights given inside the LinearLayout

<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:id="@+id/andsanddkasd">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/sharedResourcesRecyclerView"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="4"
                />

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/fab"
                android:layout_width="wrap_content"
                android:layout_height="0dp"
                android:layout_gravity="bottom|right"
                android:src="@android:drawable/ic_input_add"
                android:layout_weight="1"/>

        </LinearLayout>

Hope this helps :)

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

WebAPI 2 now has a package for CORS which can be installed using : Install-Package Microsoft.AspNet.WebApi.Cors -pre -project WebServic

Once this is installed, follow this for the code :http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

How is CountDownLatch used in Java Multithreading?

CountDownLatch in Java is a type of synchronizer which allows one Thread to wait for one or more Threads before it starts processing.

CountDownLatch works on latch principle, thread will wait until gate is open. One thread waits for n number of threads specified while creating CountDownLatch.

e.g. final CountDownLatch latch = new CountDownLatch(3);

Here we set the counter to 3.

Any thread, usually main thread of application, which calls CountDownLatch.await() will wait until count reaches zero or it's interrupted by another Thread. All other threads are required to do count down by calling CountDownLatch.countDown() once they are completed or ready to the job. as soon as count reaches zero, the Thread awaiting starts running.

Here the count is get decremented by CountDownLatch.countDown() method.

The Thread which calls the await() method will wait until the initial count reaches to zero.

To make count zero other threads need to call the countDown() method. Once the count become zero the thread which invoked the await() method will resume (start its execution).

The disadvantage of CountDownLatch is that it's not reusable: once the count become zero it is no longer usable.

Does Android support near real time push notification?

Firebase Cloud Messaging FCM FAQ is the new version of GCM. It inherits GCM’s core infrastructure to deliver messages reliably on Android, iOS and Chrome. However they'll continue to support GCM because lot of developers are using GCM SDKs today to handle notifications, and client app upgrade takes time.

As of June 26, 2012, Google Cloud Messaging is the preferred way of sending messages to applications running on devices.

Previously (and now deprecated), the service was called Cloud To Device Messaging.

Using grep to help subset a data frame in R

It's pretty straightforward using [ to extract:

grep will give you the position in which it matched your search pattern (unless you use value = TRUE).

grep("^G45", My.Data$x)
# [1] 2

Since you're searching within the values of a single column, that actually corresponds to the row index. So, use that with [ (where you would use My.Data[rows, cols] to get specific rows and columns).

My.Data[grep("^G45", My.Data$x), ]
#      x y
# 2 G459 2

The help-page for subset shows how you can use grep and grepl with subset if you prefer using this function over [. Here's an example.

subset(My.Data, grepl("^G45", My.Data$x))
#      x y
# 2 G459 2

As of R 3.3, there's now also the startsWith function, which you can again use with subset (or with any of the other approaches above). According to the help page for the function, it's considerably faster than using substring or grepl.

subset(My.Data, startsWith(as.character(x), "G45"))
#      x y
# 2 G459 2

How does "make" app know default target to build if no target is specified?

GNU Make also allows you to specify the default make target using a special variable called .DEFAULT_GOAL. You can even unset this variable in the middle of the Makefile, causing the next target in the file to become the default target.

Ref: The Gnu Make manual - Special Variables

Is it better to use std::memcpy() or std::copy() in terms to performance?

Always use std::copy because memcpy is limited to only C-style POD structures, and the compiler will likely replace calls to std::copy with memcpy if the targets are in fact POD.

Plus, std::copy can be used with many iterator types, not just pointers. std::copy is more flexible for no performance loss and is the clear winner.

Android; Check if file exists without creating a new one

When you use this code, you are not creating a new File, it's just creating an object reference for that file and testing if it exists or not.

File file = new File(filePath);
if(file.exists()) 
    //do something

"cannot resolve symbol R" in Android Studio

I was using gradle 3.3.0. It was the main culprit. Wasted 6.50 hours from my life. Gradle 3.2.1 removed the error.

classpath 'com.android.tools.build:gradle:3.2.1'

Problem resolved after changing the gradle version. Details history can be found here.

Directory-tree listing in Python

The one worked with me is kind of a modified version from Saleh's answer elsewhere on this page.

The code is as follows:

dir = 'given_directory_name'
filenames = [os.path.abspath(os.path.join(dir,i)) for i in os.listdir(dir)]

Incrementing a date in JavaScript

Tomorrow in one line in pure JS but it's ugly !

new Date(new Date().setDate(new Date().getDate() + 1))

Here is the result :

Thu Oct 12 2017 08:53:30 GMT+0200 (Romance Summer Time)

Nginx: Job for nginx.service failed because the control process exited

In my case, nginx was not able to open the log file which is located here /var/log/nginx/error.log

This was because I had deleted the log directory to free up space in root (which turned out to be stupid)

I then created a log folder in var and an nginx folder in log.

Then simply run sudo service nginx start

How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

I modified from @PsychoCoder. All controls could be found now (include nested).

public static IEnumerable<T> GetChildrens<T>(Control control)
{
  var type = typeof (T);

  var allControls = GetAllChildrens(control);

  return allControls.Where(c => c.GetType() == type).Cast<T>();
}

private static IEnumerable<Control> GetAllChildrens(Control control)
{
  var controls = control.Controls.Cast<Control>();
  return controls.SelectMany(c => GetAllChildrens(c))
    .Concat(controls);
}

How do I check out a specific version of a submodule using 'git submodule'?

Submodule repositories stay in a detached HEAD state pointing to a specific commit. Changing that commit simply involves checking out a different tag or commit then adding the change to the parent repository.

$ cd submodule
$ git checkout v2.0
Previous HEAD position was 5c1277e... bumped version to 2.0.5
HEAD is now at f0a0036... version 2.0

git-status on the parent repository will now report a dirty tree:

# On branch dev [...]
#
#   modified:   submodule (new commits)

Add the submodule directory and commit to store the new pointer.

What is the meaning of "int(a[::-1])" in Python?

Assuming a is a string. The Slice notation in python has the syntax -

list[<start>:<stop>:<step>]

So, when you do a[::-1], it starts from the end towards the first taking each element. So it reverses a. This is applicable for lists/tuples as well.

Example -

>>> a = '1234'
>>> a[::-1]
'4321'

Then you convert it to int and then back to string (Though not sure why you do that) , that just gives you back the string.

Measure string size in Bytes in php

You can use mb_strlen() to get the byte length using a encoding that only have byte-characters, without worring about multibyte or singlebyte strings. For example, as drake127 saids in a comment of mb_strlen, you can use '8bit' encoding:

<?php
    $string = 'Cién cañones por banda';
    echo mb_strlen($string, '8bit');
?>

You can have problems using strlen function since php have an option to overload strlen to actually call mb_strlen. See more info about it in http://php.net/manual/en/mbstring.overload.php

For trim the string by byte length without split in middle of a multibyte character you can use:

mb_strcut(string $str, int $start [, int $length [, string $encoding ]] )

Adding timestamp to a filename with mv in BASH

A single line method within bash works like this.

[some out put] >$(date "+%Y.%m.%d-%H.%M.%S").ver

will create a file with a timestamp name with ver extension. A working file listing snap shot to a date stamp file name as follows can show it working.

find . -type f -exec ls -la {} \; | cut -d ' ' -f 6- >$(date "+%Y.%m.%d-%H.%M.%S").ver

Of course

cat somefile.log > $(date "+%Y.%m.%d-%H.%M.%S").ver

or even simpler

ls > $(date "+%Y.%m.%d-%H.%M.%S").ver

Java: Calculating the angle between two points in degrees

angle = Math.toDegrees(Math.atan2(target.x - x, target.y - y));

now for orientation of circular values to keep angle between 0 and 359 can be:

angle = angle + Math.ceil( -angle / 360 ) * 360

Problems when trying to load a package in R due to rJava

Answer in link resolved my issue.

Before resolution, I tried by adding JAVA_HOME to windows environments. It resolved this error but created another issue. The solution in above link resolves this issue without creating additional issues.

Get url parameters from a string in .NET

Use static ParseQueryString method of System.Web.HttpUtility class that returns NameValueCollection.

Uri myUri = new Uri("http://www.example.com?param1=good&param2=bad");
string param1 = HttpUtility.ParseQueryString(myUri.Query).Get("param1");

Check documentation at http://msdn.microsoft.com/en-us/library/ms150046.aspx

Removing an element from an Array (Java)

You could use commons lang's ArrayUtils.

array = ArrayUtils.removeElement(array, element)

commons.apache.org library:Javadocs

<code> vs <pre> vs <samp> for inline and block code snippets

This works for me to display code in frontend:

<style>
.content{
    height:50vh;
    width: 100%;
    background: transparent;
    border: none;
    border-radius: 0;
    resize: none;
    outline: none;
}
.content:focus{
    border: none;
    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;
}
</style>

<textarea class="content">
<div>my div</div><p>my paragraph</p>
</textarea>

View Live Demo: https://jsfiddle.net/bytxj50e/

How to detect scroll position of page using jQuery

You can extract the scroll position using jQuery's .scrollTop() method

$(window).scroll(function (event) {
    var scroll = $(window).scrollTop();
    // Do something
});

Return value in a Bash function

Git Bash on Windows using arrays for multiple return values

BASH CODE:

#!/bin/bash

##A 6-element array used for returning
##values from functions:
declare -a RET_ARR
RET_ARR[0]="A"
RET_ARR[1]="B"
RET_ARR[2]="C"
RET_ARR[3]="D"
RET_ARR[4]="E"
RET_ARR[5]="F"


function FN_MULTIPLE_RETURN_VALUES(){

   ##give the positional arguments/inputs
   ##$1 and $2 some sensible names:
   local out_dex_1="$1" ##output index
   local out_dex_2="$2" ##output index

   ##Echo for debugging:
   echo "running: FN_MULTIPLE_RETURN_VALUES"

   ##Here: Calculate output values:
   local op_var_1="Hello"
   local op_var_2="World"

   ##set the return values:
   RET_ARR[ $out_dex_1 ]=$op_var_1
   RET_ARR[ $out_dex_2 ]=$op_var_2
}


echo "FN_MULTIPLE_RETURN_VALUES EXAMPLES:"
echo "-------------------------------------------"
fn="FN_MULTIPLE_RETURN_VALUES"
out_dex_a=0
out_dex_b=1
eval $fn $out_dex_a $out_dex_b  ##<--Call function
a=${RET_ARR[0]} && echo "RET_ARR[0]: $a "
b=${RET_ARR[1]} && echo "RET_ARR[1]: $b "
echo
##----------------------------------------------##
c="2"
d="3"
FN_MULTIPLE_RETURN_VALUES $c $d ##<--Call function
c_res=${RET_ARR[2]} && echo "RET_ARR[2]: $c_res "
d_res=${RET_ARR[3]} && echo "RET_ARR[3]: $d_res "
echo
##----------------------------------------------##
FN_MULTIPLE_RETURN_VALUES 4 5  ##<---Call function
e=${RET_ARR[4]} && echo "RET_ARR[4]: $e "
f=${RET_ARR[5]} && echo "RET_ARR[5]: $f "
echo
##----------------------------------------------##


read -p "Press Enter To Exit:"

EXPECTED OUTPUT:

FN_MULTIPLE_RETURN_VALUES EXAMPLES:
-------------------------------------------
running: FN_MULTIPLE_RETURN_VALUES
RET_ARR[0]: Hello
RET_ARR[1]: World

running: FN_MULTIPLE_RETURN_VALUES
RET_ARR[2]: Hello
RET_ARR[3]: World

running: FN_MULTIPLE_RETURN_VALUES
RET_ARR[4]: Hello
RET_ARR[5]: World

Press Enter To Exit:

Check if Cookie Exists

Response.Cookies contains the cookies that will be sent back to the browser. If you want to know whether a cookie exists, you should probably look into Request.Cookies.

Anyway, to see if a cookie exists, you can check Cookies.Get(string). However, if you use this method on the Response object and the cookie doesn't exist, then that cookie will be created.

See MSDN Reference for HttpCookieCollection.Get Method (String)

Click a button programmatically - JS

Though this question is rather old, here's a answer :)

What you are asking for can be achieved by using jQuery's .click() event method and .on() event method

So this could be the code:

// Set the global variables
var userImage = $("#img-giLkojRpuK");
var hangoutButton = $("#hangout-giLkojRpuK");

$(document).ready(function() {
    // When the document is ready/loaded, execute function

    // Hide hangoutButton
    hangoutButton.hide();

    // Assign "click"-event-method to userImage
    userImage.on("click", function() {
        console.log("in onclick");
        hangoutButton.click();
    });
});

mysqldump with create database line

By default mysqldump always creates the CREATE DATABASE IF NOT EXISTS db_name; statement at the beginning of the dump file.

[EDIT] Few things about the mysqldump file and it's options:

--all-databases, -A

Dump all tables in all databases. This is the same as using the --databases option and naming all the databases on the command line.

--add-drop-database

Add a DROP DATABASE statement before each CREATE DATABASE statement. This option is typically used in conjunction with the --all-databases or --databases option because no CREATE DATABASE statements are written unless one of those options is specified.

--databases, -B

Dump several databases. Normally, mysqldump treats the first name argument on the command line as a database name and following names as table names. With this option, it treats all name arguments as database names. CREATE DATABASE and USE statements are included in the output before each new database.

--no-create-db, -n

This option suppresses the CREATE DATABASE statements that are otherwise included in the output if the --databases or --all-databases option is given.

Some time ago, there was similar question actually asking about not having such statement on the beginning of the file (for XML file). Link to that question is here.

So to answer your question:

  • if you have one database to dump, you should have the --add-drop-database option in your mysqldump statement.
  • if you have multiple databases to dump, you should use the option --databases or --all-databases and the CREATE DATABASE syntax will be added automatically

More information at MySQL Reference Manual

android set button background programmatically

Further from @finnmglas, the Java answer as of 2021 is:

    if (Build.VERSION.SDK_INT >= 29)
        btn.getBackground().setColorFilter(new BlendModeColorFilter(color, BlendMode.MULTIPLY));
    else
        btn.getBackground().setColorFilter(color, PorterDuff.Mode.MULTIPLY);

Html.fromHtml deprecated in Android N

The framework class has been modified to require a flag to inform fromHtml() how to process line breaks. This was added in Nougat, and only touches on the challenge of incompatibilities of this class across versions of Android.

I've published a compatibility library to standardize and backport the class and include more callbacks for elements and styling:

https://github.com/Pixplicity/HtmlCompat

While it is similar to the framework's Html class, some signature changes were required to allow more callbacks. Here's the sample from the GitHub page:

Spanned fromHtml = HtmlCompat.fromHtml(context, source, 0);
// You may want to provide an ImageGetter, TagHandler and SpanCallback:
//Spanned fromHtml = HtmlCompat.fromHtml(context, source, 0,
//        imageGetter, tagHandler, spanCallback);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(fromHtml);

Shell script to set environment variables

Run the script as source= to run in debug mode as well.

source= ./myscript.sh

Auto-expanding layout with Qt-Designer

According to the documentation, there needs to be a top level layout set.

A top level layout is necessary to ensure that your widgets will resize correctly when its window is resized. To check if you have set a top level layout, preview your widget and attempt to resize the window by dragging the size grip.

You can set one by clearing the selection and right clicking on the form itself and choosing one of the layouts available in the context menu.

Qt layouts

How can I make git show a list of the files that are being tracked?

The files managed by git are shown by git ls-files. Check out its manual page.

How to get the cursor to change to the hand when hovering a <button> tag

see: https://developer.mozilla.org/en-US/docs/Web/CSS/cursor

so you need to add: cursor:pointer;

In your case use:

#more {
  background:none;
  border:none;
  color:#FFF;
  font-family:Verdana, Geneva, sans-serif;
  cursor:pointer;
}

This will apply the curser to the element with the ID "more" (can be only used once). So in your HTML use

<input type="button" id="more" />

If you want to apply this to more than one button then you have more than one possibility:

using CLASS

.more {
  background:none;
  border:none;
  color:#FFF;
  font-family:Verdana, Geneva, sans-serif;
  cursor:pointer;
}

and in your HTML use

<input type="button" class="more" value="first" />
<input type="button" class="more" value="second" />

or apply to a html context:

input[type=button] {
  background:none;
  border:none;
  color:#FFF;
  font-family:Verdana, Geneva, sans-serif;
  cursor:pointer;
}

and in your HTML use

<input type="button" value="first" />
<input type="button" value="second" />

JPA Query selecting only specific columns without using Criteria Query?

You can use something like this:

List<Object[]> list = em.createQuery("SELECT p.field1, p.field2 FROM Entity p").getResultList();

then you can iterate over it:

for (Object[] obj : list){
    System.out.println(obj[0]);
    System.out.println(obj[1]);
}

BUT if you have only one field in query, you get a list of the type not from Object[]

ComboBox SelectedItem vs SelectedValue

The ComboBox control inherits from the ListControl control.

The SelectedItem property is a proper member of the ComboBox control. The event that is fired on change is ComboBox.SelectionChangeCommitted

ComboBox.SelectionChangeCommitted

Occurs when the selected item has changed and that change is displayed in the ComboBox.

The SelectedValue property is inherited from the ListControl control. As such, this property will fire the ListControl.SelectedValueChanged event.

ListControl.SelectedValueChanged

Occurs when the SelectedValue property changes.

That said, they won't fire the INotifyPropertyChanged.PropertyChanged event the same, but they will anyway. The only difference is in the firing event. SelectedValueChanged is fired as soon as a new selection is made from the list part of the ComboBox, and SelectedItemChanged is fired when the item is displayed in the TextBox portion of the ComboBox.

In short, they both represent something in the list part of the ComboBox. So, when binding either property, the result is the same, since the PropertyChanged event is fired in either case. And since they both represent an element from the list, the they are probably treated the same.

Does this help?

EDIT #1

Assuming that the list part of the ComboBox represents a property (as I can't confirm since I didn't write the control), binding either of SelectedItem or SelectedValue affects the same collection inside the control. Then, when this property is changed, the same occurs in the end. The INotifyPropertryPropertyChanged.PropertyChanged event is fired on the same property.

What is the correct JSON content type?

Extending the accepted responses, when you are using JSON in a REST context...

There is a strong argument about using application/x-resource+json and application/x-collection+json when you are representing REST resources and collections.

And if you decide to follow the jsonapi specification, you should use of application/vnd.api+json, as it is documented.

Altough there is not an universal standard, it is clear that the added semantic to the resources being transfered justify a more explicit Content-Type than just application/json.

Following this reasoning, other contexts could justify a more specific Content-Type.

How to append text to a text file in C++?

I use this code. It makes sure that file gets created if it doesn't exist and also adds bit of error checks.

static void appendLineToFile(string filepath, string line)
{
    std::ofstream file;
    //can't enable exception now because of gcc bug that raises ios_base::failure with useless message
    //file.exceptions(file.exceptions() | std::ios::failbit);
    file.open(filepath, std::ios::out | std::ios::app);
    if (file.fail())
        throw std::ios_base::failure(std::strerror(errno));

    //make sure write fails with exception if something is wrong
    file.exceptions(file.exceptions() | std::ios::failbit | std::ifstream::badbit);

    file << line << std::endl;
}

EditText request focus

It has worked for me as follows.

ed1.requestFocus();

            return; //Faça um return para retornar o foco

How to solve "The specified service has been marked for deletion" error

This can also be caused by leaving the Services console open. Windows won't actually delete the service until it is closed.

How to delete all files from a specific folder?

You can do it via FileInfo or DirectoryInfo:

DirectoryInfo di = new DirectoryInfo("TempDir");
di.Delete(true);

And then recreate the directory

Function inside a function.?

(4+3)*(4*2) == 56

Note that PHP doesn't really support "nested functions", as in defined only in the scope of the parent function. All functions are defined globally. See the docs.

Accessing elements of Python dictionary by index

I know this is 8 years old, but no one seems to have actually read and answered the question.

You can call .values() on a dict to get a list of the inner dicts and thus access them by index.

>>> mydict = {
...  'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
...  'Grapes':{'Arabian':'25','Indian':'20'} }

>>>mylist = list(mydict.values())
>>>mylist[0]
{'American':'16', 'Mexican':10, 'Chinese':5},
>>>mylist[1]
{'Arabian':'25','Indian':'20'}

>>>myInnerList1 = list(mylist[0].values())
>>>myInnerList1
['16', 10, 5]
>>>myInnerList2 = list(mylist[1].values())
>>>myInnerList2
['25', '20']

How to check if a database exists in SQL Server?

From a Microsoft's script:

DECLARE @dbname nvarchar(128)
SET @dbname = N'Senna'

IF (EXISTS (SELECT name 
FROM master.dbo.sysdatabases 
WHERE ('[' + name + ']' = @dbname 
OR name = @dbname)))

-- code mine :)
PRINT 'db exists'

How to change the length of a column in a SQL Server table via T-SQL

So, let's say you have this table:

CREATE TABLE YourTable(Col1 VARCHAR(10))

And you want to change Col1 to VARCHAR(20). What you need to do is this:

ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)

That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5), then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE will fail.

File URL "Not allowed to load local resource" in the Internet Browser

Now we know what the actual error is can formulate an answer.

Not allowed to load local resource

is a Security exception built into Chrome and other modern browsers. The wording may be different but in some way shape or form they all have security exceptions in place to deal with this scenario.

In the past you could override certain settings or apply certain flags such as

--disable-web-security --allow-file-access-from-files --allow-file-access

in Chrome (See https://stackoverflow.com/a/22027002/692942)

It's there for a reason

At this point though it's worth pointing out that these security exceptions exist for good reason and trying to circumvent them isn't the best idea.

There is another way

As you have access to Classic ASP already you could always build a intermediary page that serves the network based files. You do this using a combination of the ADODB.Stream object and the Response.BinaryWrite() method. Doing this ensures your network file locations are never exposed to the client and due to the flexibility of the script it can be used to load resources from multiple locations and multiple file types.

Here is a basic example (getfile.asp);

<%
Option Explicit

Dim s, id, bin, file, filename, mime

id = Request.QueryString("id")

'id can be anything just use it as a key to identify the 
'file to return. It could be a simple Case statement like this
'or even pulled from a database.
Select Case id
Case "TESTFILE1"
  'The file, mime and filename can be built-up anyway they don't 
  'have to be hard coded.
  file = "\\server\share\Projecten\Protocollen\346\Uitvoeringsoverzicht.xls"     
  mime = "application/vnd.ms-excel"
  'Filename you want to display when downloading the resource.
  filename = "Uitvoeringsoverzicht.xls"

'Assuming other files 
Case ...
End Select

If Len(file & "") > 0 Then
  Set s = Server.CreateObject("ADODB.Stream")
  s.Type = adTypeBinary 'adTypeBinary = 1 See "Useful Links"
  Call s.Open()
  Call s.LoadFromFile(file)
  bin = s.Read()

  'Clean-up the stream and free memory
  Call s.Close()
  Set s = Nothing

  'Set content type header based on mime variable
  Response.ContentType = mime
  'Control how the content is returned using the 
  'Content-Disposition HTTP Header. Using "attachment" forces the resource
  'to prompt the client to download while "inline" allows the resource to
  'download and display in the client (useful for returning images
  'as the "src" of a <img> tag).
  Call Response.AddHeader("Content-Disposition", "attachment;filename=" & filename)
  Call Response.BinaryWrite(bin)
Else
  'Return a 404 if there's no file.
  Response.Status = "404 Not Found"
End If
%>

This example is pseudo coded and as such is untested.

This script can then be used in <a> like this to return the resource;

<a href="/getfile.asp?id=TESTFILE1">Click Here</a>

The could take this approach further and consider (especially for larger files) reading the file in chunks using Response.IsConnected to check whether the client is still there and s.EOS property to check for the end of the stream while the chunks are being read. You could also add to the querystring parameters to set whether you want the file to return in-line or prompt to be downloaded.


Useful Links

Kendo grid date column not formatting

This is how you do it using ASP.NET:

add .Format("{0:dd/MM/yyyy HH:mm:ss}"); 

    @(Html.Kendo().Grid<AlphaStatic.Domain.ViewModels.AttributeHistoryViewModel>()
            .Name("grid")
            .Columns(columns =>
            {

                columns.Bound(c => c.AttributeName);
                columns.Bound(c => c.UpdatedDate).Format("{0:dd/MM/yyyy HH:mm:ss}");   
            })
            .HtmlAttributes(new { @class = ".big-grid" })
            .Resizable(x => x.Columns(true))
            .Sortable()
            .Filterable()    
            .DataSource(dataSource => dataSource
                .Ajax()
                .Batch(true)
                .ServerOperation(false)
                        .Model(model =>
                        {
                            model.Id(c => c.Id);
                        })       
               .Read(read => read.Action("Read_AttributeHistory", "Attribute",  new { attributeId = attributeId })))
            )

T-SQL STOP or ABORT command in SQL Server

Try running this as a TSQL Script

SELECT 1
RETURN
SELECT 2
SELECT 3

The return ends the execution.

RETURN (Transact-SQL)

Exits unconditionally from a query or procedure. RETURN is immediate and complete and can be used at any point to exit from a procedure, batch, or statement block. Statements that follow RETURN are not executed.

PHP Array to JSON Array using json_encode();

json_encode() function will help you to encode array to JSON in php.

if you will use just json_encode function directly without any specific option, it will return an array. Like mention above question

$array = array(
  2 => array("Afghanistan",32,13),
  4 => array("Albania",32,12)
);
$out = array_values($array);
json_encode($out);
// [["Afghanistan",32,13],["Albania",32,12]]

Since you are trying to convert Array to JSON, Then I would suggest to use JSON_FORCE_OBJECT as additional option(parameters) in json_encode, Like below

<?php
$array=['apple','orange','banana','strawberry'];
echo json_encode($array, JSON_FORCE_OBJECT);
// {"0":"apple","1":"orange","2":"banana","3":"strawberry"} 
?>

How to use placeholder as default value in select2 framework

I did the following:

var defaultOption = new Option();
defaultOption.selected = true;    
$(".js-select2").append(defaultOption);

For other options I use then:

var realOption = new Option("Option Value", "id");
realOption.selected = false;    
$(".js-select2").append(realOption);

Extract first item of each sublist

lst = [['a','b','c'], [1,2,3], ['x','y','z']]
outputlist = []
for values in lst:
    outputlist.append(values[0])

print(outputlist) 

Output: ['a', 1, 'x']

Use sudo with password as parameter

echo -e "YOURPASSWORD\n" | sudo -S yourcommand

Unable to launch the IIS Express Web server, Failed to register URL, Access is denied

Yeah, I agree, top answers are really pro solutions,

here is one for intermediates,

Solutions Explorer

Right click on project select Unload project

Again Right click and select Edit ProjectName.csproj

remove these 3 lines

<DevelopmentServerPort>0</DevelopmentServerPort>
<DevelopmentServerVPath>/</DevelopmentServerVPath>
<IISUrl>http://localhost:62940/</IISUrl>

Save and reload the project and you are good to go

QLabel: set color of text and background

This one is working perfect

QColorDialog *dialog = new QColorDialog(this);
QColor color=  dialog->getColor();
QVariant variant= color;
QString colcode = variant.toString();
ui->label->setStyleSheet("QLabel { background-color :"+colcode+" ; color : blue; }");

getColor() method returns the selected color. You can change label color using stylesheet

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

How do I convert an NSString value to NSData?

For Swift 3, you will mostly be converting from String to Data.

let myString = "test"
let myData = myString.data(using: .utf8)
print(myData) // Optional(Data)

How to implement WiX installer upgrade?

I used this site to help me understand the basics about WiX Upgrade:

http://wix.tramontana.co.hu/tutorial/upgrades-and-modularization

Afterwards I created a sample Installer, (installed a test file), then created the Upgrade installer (installed 2 sample test files). This will give you a basic understanding of how the mechanism works.

And as Mike said in the book from Apress, "The Definitive Guide to Windows Installer", it will help you out to understand, but it is not written using WiX.

Another site that was pretty helpful was this one:

http://www.wixwiki.com/index.php?title=Main_Page

AssertNull should be used or AssertNotNull

I just want to add that if you want to write special text if It null than you make it like that

  Assert.assertNotNull("The object you enter return null", str1)

Working with a List of Lists in Java

ArrayList<ArrayList<String>> listOLists = new ArrayList<ArrayList<String>>();
ArrayList<String> singleList = new ArrayList<String>();
singleList.add("hello");
singleList.add("world");
listOLists.add(singleList);

ArrayList<String> anotherList = new ArrayList<String>();
anotherList.add("this is another list");
listOLists.add(anotherList);

Random word generator- Python

There are a number of dictionary files available online - if you're on linux, a lot of (all?) distros come with an /etc/dictionaries-common/words file, which you can easily parse (words = open('/etc/dictionaries-common/words').readlines(), eg) for use.

Convert a list to a string in C#

You could use string.Join:

List<string> list = new List<string>()
{
    "Red",
    "Blue",
    "Green"
};

string output = string.Join(Environment.NewLine, list.ToArray());    
Console.Write(output);

The result would be:

Red    
Blue    
Green

As an alternative to Environment.NewLine, you can replace it with a string based line-separator of your choosing.

How to resolve git stash conflict without commit?

Don't follow other answers

Well, you can follow them :). But I don't think that doing a commit and then resetting the branch to remove that commit and similar workarounds suggested in other answers are the clean way to solve this issue.

Clean solution

The following solution seems to be much cleaner to me and it's also suggested by the Git itself — try to execute git status in the repository with a conflict:

Unmerged paths:
  (use "git reset HEAD <file>..." to unstage)
  (use "git add <file>..." to mark resolution)

So let's do what Git suggests (without doing any useless commits):

  1. Manually (or using some merge tool, see below) resolve the conflict(s).
  2. Use git reset to mark conflict(s) as resolved and unstage the changes. You can execute it without any parameters and Git will remove everything from the index. You don't have to execute git add before.
  3. Finally, remove the stash with git stash drop, because Git doesn't do that on conflict.

Translated to the command-line:

$ git stash pop

# ...resolve conflict(s)

$ git reset

$ git stash drop

Explanation of the default behavior

There are two ways of marking conflicts as resolved: git add and git reset. While git reset marks the conflicts as resolved and removes files from the index, git add also marks the conflicts as resolved, but keeps files in the index.

Adding files to the index after a conflict is resolved is on purpose. This way you can differentiate the changes from the previous stash and changes you made after the conflict was resolved. If you don't like it, you can always use git reset to remove everything from the index.

Merge tools

I highly recommend using any of 3-way merge tools for resolving conflicts, e.g. KDiff3, Meld, etc., instead of doing it manually. It usually solves all or majority of conflicts automatically itself. It's huge time-saver!

In a Git repository, how to properly rename a directory?

If you receive this error: fatal: renaming ‘foldername’ failed: Invalid argument

Try this:

*nixOS

git mv foldername tempname && git mv tempname folderName

WinOS

git config core.ignorecase false; git mv foldername tempname; git mv tempname folderName

Calculating Covariance with Python and Numpy

Thanks to unutbu for the explanation. By default numpy.cov calculates the sample covariance. To obtain the population covariance you can specify normalisation by the total N samples like this:

Covariance = numpy.cov(a, b, bias=True)[0][1]
print(Covariance)

or like this:

Covariance = numpy.cov(a, b, ddof=0)[0][1]
print(Covariance)

How to include another XHTML in XHTML using JSF 2.0 Facelets?

Included page:

<!-- opening and closing tags of included page -->
<ui:composition ...>
</ui:composition>

Including page:

<!--the inclusion line in the including page with the content-->
<ui:include src="yourFile.xhtml"/>
  • You start your included xhtml file with ui:composition as shown above.
  • You include that file with ui:include in the including xhtml file as also shown above.

Using setattr() in python

Setattr: We use setattr to add an attribute to our class instance. We pass the class instance, the attribute name, and the value. and with getattr we retrive these values

For example

Employee = type("Employee", (object,), dict())

employee = Employee()

# Set salary to 1000
setattr(employee,"salary", 1000 )

# Get the Salary
value = getattr(employee, "salary")

print(value)

Run a command shell in jenkins

Go to Jenkins -> Manage Jenkins -> Configure System -> Global properties Check the box 'Environment variables' and add the JAVA_HOME path = "C:\Program Files\Java\jdk-10.0.1"

*Don't write bin at the end

Using Git, show all commits that are in one branch, but not the other(s)

To show the commits in oldbranch but not in newbranch:

git log newbranch..oldbranch

To show the diff by these commits (note there are three dots):

git diff newbranch...oldbranch

Here is the doc with a diagram illustration https://git-scm.com/book/en/v2/Git-Tools-Revision-Selection#Commit-Ranges

Python: access class property from string

x = getattr(self, source) will work just perfectly if source names ANY attribute of self, including the other_data in your example.

Cannot construct instance of - Jackson

Your @JsonSubTypes declaration does not make sense: it needs to list implementation (sub-) classes, NOT the class itself (which would be pointless). So you need to modify that entry to list sub-class(es) there are; or use some other mechanism to register sub-classes (SimpleModule has something like addAbstractTypeMapping).

How to downgrade Xcode to previous version?

When you log in to your developer account, you can find a link at the bottom of the download section for Xcode that says "Looking for an older version of Xcode?". In there you can find download links to older versions of Xcode and other developer tools

Keyboard shortcuts in WPF

It depends on where you want to use those.

TextBoxBase-derived controls already implement those shortcuts. If you want to use custom keyboard shortcuts you should take a look on Commands and Input gestures. Here is a small tutorial from Switch on the Code: WPF Tutorial - Command Bindings and Custom Commands

What is the difference between a deep copy and a shallow copy?

Deep Copy

A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.

Shallow Copy

Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.

Get Category name from Post ID

here you go get_the_category( $post->ID ); will return the array of categories of that post you need to loop through the array

$category_detail=get_the_category('4');//$post->ID
foreach($category_detail as $cd){
echo $cd->cat_name;
}

get_the_category

Oracle SQL Query for listing all Schemas in a DB

Most likely, you want

SELECT username
  FROM dba_users

That will show you all the users in the system (and thus all the potential schemas). If your definition of "schema" allows for a schema to be empty, that's what you want. However, there can be a semantic distinction where people only want to call something a schema if it actually owns at least one object so that the hundreds of user accounts that will never own any objects are excluded. In that case

SELECT username
  FROM dba_users u
 WHERE EXISTS (
    SELECT 1
      FROM dba_objects o
     WHERE o.owner = u.username )

Assuming that whoever created the schemas was sensible about assigning default tablespaces and assuming that you are not interested in schemas that Oracle has delivered, you can filter out those schemas by adding predicates on the default_tablespace, i.e.

SELECT username
  FROM dba_users
 WHERE default_tablespace not in ('SYSTEM','SYSAUX')

or

SELECT username
  FROM dba_users u
 WHERE EXISTS (
    SELECT 1
      FROM dba_objects o
     WHERE o.owner = u.username )
   AND default_tablespace not in ('SYSTEM','SYSAUX')

It is not terribly uncommon to come across a system where someone has incorrectly given a non-system user a default_tablespace of SYSTEM, though, so be certain that the assumptions hold before trying to filter out the Oracle-delivered schemas this way.

Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

GCC does actually optimize a*a*a*a*a*a to (a*a*a)*(a*a*a) when a is an integer. I tried with this command:

$ echo 'int f(int x) { return x*x*x*x*x*x; }' | gcc -o - -O2 -S -masm=intel -x c -

There are a lot of gcc flags but nothing fancy. They mean: Read from stdin; use O2 optimization level; output assembly language listing instead of a binary; the listing should use Intel assembly language syntax; the input is in C language (usually language is inferred from input file extension, but there is no file extension when reading from stdin); and write to stdout.

Here's the important part of the output. I've annotated it with some comments indicating what's going on in the assembly language:

; x is in edi to begin with.  eax will be used as a temporary register.
mov  eax, edi  ; temp = x
imul eax, edi  ; temp = x * temp
imul eax, edi  ; temp = x * temp
imul eax, eax  ; temp = temp * temp

I'm using system GCC on Linux Mint 16 Petra, an Ubuntu derivative. Here's the gcc version:

$ gcc --version
gcc (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1

As other posters have noted, this option is not possible in floating point, because floating point arithmetic is not associative.

Concat a string to SELECT * MySql

You cannot do this on multiple fields. You can also look for this.

Can jQuery check whether input content has changed?

Since the user can go into the OS menu and select paste using their mouse, there is no safe event that will trigger this for you. The only way I found that always works is to have a setInterval that checks if the input value has changed:

var inp = $('#input'),
    val = saved = inp.val(),
    tid = setInterval(function() {
        val = inp.val();
        if ( saved != val ) {
            console.log('#input has changed');
            saved = val;
    },50);

You can also set this up using a jQuery special event.

How to make HTML open a hyperlink in another window or tab?

below example with target="_blank" works for Safari and Mozilla

<a href="http://www.starfall.com" `target="_blank"`>

Using target="new"worked for Chrome

<a href="http://www.starfall.com" `target="new"`>

How to define a preprocessor symbol in Xcode

You don't need to create a user-defined setting. The built-in setting "Preprocessor Macros" works just fine. alt text http://idisk.mac.com/cdespinosa/Public/Picture%204.png

If you have multiple targets or projects that use the same prefix file, use Preprocessor Macros Not Used In Precompiled Headers instead, so differences in your macro definition don't trigger an unnecessary extra set of precompiled headers.

Is there any way to prevent input type="number" getting negative values?

The answer to this is not helpful. as its only works when you use up/down keys, but if you type -11 it will not work. So here is a small fix that I use

this one for integers

  $(".integer").live("keypress keyup", function (event) {
    //    console.log('int = '+$(this).val());
    $(this).val($(this).val().replace(/[^\d].+/, ""));
    if (event.which != 8 && (event.which < 48 || event.which > 57))
    {
        event.preventDefault();
    }
   });

this one when you have numbers of price

        $(".numeric, .price").live("keypress keyup", function (event) {
     //    console.log('numeric = '+$(this).val());
    $(this).val($(this).val().replace(/[^0-9\,\.]/g, ''));

    if (event.which != 8 && (event.which != 44 || $(this).val().indexOf(',') != -1) && (event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }
   });

ThreadStart with parameters

The ParameterizedThreadStart takes one parameter. You can use that to send one parameter, or a custom class containing several properties.

Another method is to put the method that you want to start as an instance member in a class along with properties for the parameters that you want to set. Create an instance of the class, set the properties and start the thread specifying the instance and the method, and the method can access the properties.

Is there a command line utility for rendering GitHub flavored Markdown?

There is a really nice and simple tool for browsing GFM Markdown documents:

GFMS - Github Flavored Markdown Server

It's simple and lightweight (no configuration needed) HTTP server you can start in any directory containing markdown files to browse them.

Features:

  • Full GFM Markdown support
  • Source code syntax highlighting
  • Browsing files and directories
  • Nice looking output (and configurable CSS stylesheets)
  • Export to PDF

Only on Firefox "Loading failed for the <script> with source"

Today I ran into the exact same problem while working on a progressive web app (PWA) page and deleting some cache and service worker data for that page from Firefox. The dev console reported that none of the 4 Javascript files on the page would load anymore. The problem persisted in Safe mode, so it was not an add-on issue. The same script files loaded fine from other web pages on the same website. No amount of clearing the Firefox cache or wiping web page data from Firefox would help, nor would rebooting the Windows 10 PC. Chrome all the time worked fine on the problem page. In the end I did a restore of the entire Firefox profile folder from a day-old backup, and the problem was immediately gone, so it was not a problem with my PWA app. Apparently something in Firefox got corrupted.

Convert List<Object> to String[] in Java

There is a simple way available in Kotlin

var lst: List<Object> = ...
    
listOFStrings: ArrayList<String> = (lst!!.map { it.name })

How to include a Font Awesome icon in React's render()

I was experienced this case; I need the react/redux site that should be working perfectly in production.

but there was a 'strict mode'; Shouldn't lunch it with these commands.

yarn global add serve
serve -s build

Should working with only click the build/index.html file. When I used fontawesome with npm font-awesome, it was working in development mode but not working in the 'strict mode'.

Here is my solution:

public/css/font-awesome.min.css
public/fonts/font-awesome.eot 
*** other different types of files(4) ***
*** I copied these files for node_module/font-awesome ***
*** after copied then can delete the font-awesome from package.json ***

in public/index.html

<link rel="stylesheet" href="%PUBLIC_URL%/css/font-awesome.min.css">

After all of above steps, the fontawesome works NICELY!!!

Sending POST data in Android

This is an example of how to POST multi-part data WITHOUT using external Apache libraries:

byte[] buffer = getBuffer();

if(buffer.length > 0) {
   String lineEnd = "\r\n"; 
   String twoHyphens = "--"; 
   String boundary =  "RQdzAAihJq7Xp1kjraqf"; 

   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   DataOutputStream dos = new DataOutputStream(baos);

   // Send parameter #1
   dos.writeBytes(twoHyphens + boundary + lineEnd); 
   dos.writeBytes("Content-Disposition: form-data; name=\"param1\"" + lineEnd);
   dos.writeBytes("Content-Type: text/plain; charset=US-ASCII" + lineEnd);
   dos.writeBytes("Content-Transfer-Encoding: 8bit" + lineEnd);
   dos.writeBytes(lineEnd);
   dos.writeBytes(myStringData + lineEnd);

   // Send parameter #2
   //dos.writeBytes(twoHyphens + boundary + lineEnd); 
   //dos.writeBytes("Content-Disposition: form-data; name=\"param2\"" + lineEnd + lineEnd);
   //dos.writeBytes("foo2" + lineEnd);

   // Send a binary file
   dos.writeBytes(twoHyphens + boundary + lineEnd); 
   dos.writeBytes("Content-Disposition: form-data; name=\"param3\";filename=\"test_file.dat\"" + lineEnd); 
   dos.writeBytes("Content-Type: application/octet-stream" + lineEnd);
   dos.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
   dos.writeBytes(lineEnd); 
   dos.write(buffer);
   dos.writeBytes(lineEnd); 
   dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 
   dos.flush(); 
   dos.close();

   ByteArrayInputStream content = new ByteArrayInputStream(baos.toByteArray());
   BasicHttpEntity entity = new BasicHttpEntity();
   entity.setContent(content);

   HttpPost httpPost = new HttpPost(myURL);
   httpPost.addHeader("Connection", "Keep-Alive");
   httpPost.addHeader("Content-Type", "multipart/form-data; boundary="+boundary);

   //MultipartEntity entity = new MultipartEntity();
   //entity.addPart("param3", new ByteArrayBody(buffer, "test_file.dat"));
   //entity.addPart("param1", new StringBody(myStringData));

   httpPost.setEntity(entity);

   /*
   String httpData = "";
   ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
   entity.writeTo(baos1);
   httpData = baos1.toString("UTF-8");
   */

   /*
   Header[] hdrs = httpPost.getAllHeaders();
   for(Header hdr: hdrs) {
     httpData += hdr.getName() + " | " + hdr.getValue() + " |_| ";
   }
   */

   //Log.e(TAG, "httpPost data: " + httpData);
   response = httpClient.execute(httpPost);
}

Java Regex to Validate Full Name allow only Spaces and Letters

To validate for only letters and spaces, try this

String name1_exp = "^[a-zA-Z]+[\-'\s]?[a-zA-Z ]+$";

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

What is a "callback" in C and how are they implemented?

Callbacks in C are usually implemented using function pointers and an associated data pointer. You pass your function on_event() and data pointers to a framework function watch_events() (for example). When an event happens, your function is called with your data and some event-specific data.

Callbacks are also used in GUI programming. The GTK+ tutorial has a nice section on the theory of signals and callbacks.

HTML table headers always visible at top of window when viewing a large table

I've encountered this problem very recently. Unfortunately, I had to do 2 tables, one for the header and one for the body. It's probably not the best approach ever but here goes:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
    <title>oh hai</title>_x000D_
</head>_x000D_
<body>_x000D_
    <table id="tableHeader">_x000D_
        <tr>_x000D_
            <th style="width:100px; background-color:#CCCCCC">col header</th>_x000D_
            <th style="width:100px; background-color:#CCCCCC">col header</th>_x000D_
        </tr>_x000D_
    </table>_x000D_
    <div style="height:50px; overflow:auto; width:250px">_x000D_
        <table>_x000D_
            <tr>_x000D_
                <td style="height:50px; width:100px; background-color:#DDDDDD">data1</td>_x000D_
                <td style="height:50px; width:100px; background-color:#DDDDDD">data1</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td style="height:50px; width:100px; background-color:#DDDDDD">data2</td>_x000D_
                <td style="height:50px; width:100px; background-color:#DDDDDD">data2</td>_x000D_
            </tr>_x000D_
        </table>_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

This worked for me, it's probably not the elegant way but it does work. I'll investigate so see if I can do something better, but it allows for multiple tables.

Go read on the overflow propriety to see if it fits your need

What is the maximum number of edges in a directed graph with n nodes?

Can also be thought of as the number of ways of choosing pairs of nodes n choose 2 = n(n-1)/2. True if only any pair can have only one edge. Multiply by 2 otherwise

How to remove all CSS classes using jQuery/JavaScript?

Since not all versions of jQuery are created equal, you may run into the same issue I did which means calling $("#item").removeClass(); does not actually remove the class. (Probably a bug)

A more reliable method is to simply use raw JavaScript and remove the class attribute altogether.

document.getElementById("item").removeAttribute("class");

Does a favicon have to be 32x32 or 16x16?

May I remind everybody that the question was:

I'd like to use a single image as both a regular favicon and iPhone/iPad friendly favicon? Is this possible? Would an iPad-friendly 72x72 PNG scale if linked to as a regular browser favicon? Or do I have to use a separate 16x16 or 32x32 image?

The answer is: YES, that is possible! YES, it will be scaled. NO, you do not need a 'regular browser favicon'. Please look at this answer: https://stackoverflow.com/a/48646940/2397550

How can I pad an integer with zeros on the left?

You can use Google Guava:

Maven:

<dependency>
     <artifactId>guava</artifactId>
     <groupId>com.google.guava</groupId>
     <version>14.0.1</version>
</dependency>

Sample code:

String paddedString1 = Strings.padStart("7", 3, '0'); //"007"
String paddedString2 = Strings.padStart("2020", 3, '0'); //"2020"

Note:

Guava is very useful library, it also provides lots of features which related to Collections, Caches, Functional idioms, Concurrency, Strings, Primitives, Ranges, IO, Hashing, EventBus, etc

Ref: GuavaExplained

Convert .cer certificate to .jks

keytool comes with the JDK installation (in the bin folder):

keytool -importcert -file "your.cer" -keystore your.jks -alias "<anything>"

This will create a new keystore and add just your certificate to it.

So, you can't convert a certificate to a keystore: you add a certificate to a keystore.

How to show current user name in a cell?

The simplest way is to create a VBA macro that wraps that function, like so:

Function UserNameWindows() As String
    UserName = Environ("USERNAME")
End Function

Then call it from the cell:

=UserNameWindows()

See this article for more details, and other ways.

How to convert UTF-8 byte[] to string?

string result = System.Text.Encoding.UTF8.GetString(byteArray);

Convert DataFrame column type from string to datetime, dd/mm/yyyy format

If your date column is a string of the format '2017-01-01' you can use pandas astype to convert it to datetime.

df['date'] = df['date'].astype('datetime64[ns]')

or use datetime64[D] if you want Day precision and not nanoseconds

print(type(df_launath['date'].iloc[0]))

yields

<class 'pandas._libs.tslib.Timestamp'> the same as when you use pandas.to_datetime

You can try it with other formats then '%Y-%m-%d' but at least this works.

Java method to swap primitives

It depends on what you want to do. This code swaps two elements of an array.

void swap(int i, int j, int[] arr) {
  int t = arr[i];
  arr[i] = arr[j];
  arr[j] = t;
}

Something like this swaps the content of two int[] of equal length.

void swap(int[] arr1, int[] arr2) {
  int[] t = arr1.clone();
  System.arraycopy(arr2, 0, arr1, 0, t.length);
  System.arraycopy(t, 0, arr2, 0, t.length);
}

Something like this swaps the content of two BitSet (using the XOR swap algorithm):

void swap(BitSet s1, BitSet s2) {
  s1.xor(s2);
  s2.xor(s1);
  s1.xor(s2);
}

Something like this swaps the x and y fields of some Point class:

void swapXY(Point p) {
  int t = p.x;
  p.x = p.y;
  p.y = t;
}

jQuery Data vs Attr?

The main difference between the two is where it is stored and how it is accessed.

$.fn.attr stores the information directly on the element in attributes which are publicly visible upon inspection, and also which are available from the element's native API.

$.fn.data stores the information in a ridiculously obscure place. It is located in a closed over local variable called data_user which is an instance of a locally defined function Data. This variable is not accessible from outside of jQuery directly.

Data set with attr()

  • accessible from $(element).attr('data-name')
  • accessible from element.getAttribute('data-name'),
  • if the value was in the form of data-name also accessible from $(element).data(name) and element.dataset['name'] and element.dataset.name
  • visible on the element upon inspection
  • cannot be objects

Data set with .data()

  • accessible only from .data(name)
  • not accessible from .attr() or anywhere else
  • not publicly visible on the element upon inspection
  • can be objects

Remove border from IFrame

To remove border you can use CSS border property to none.

<iframe src="myURL" width="300" height="300" style="border: none">Browser not compatible.</iframe>

Android ImageView's onClickListener does not work

For inner classes to pass the reference of activity, I usually create a reference of activity in onCreate() and make it as a member. As inner classes have access to members of parent class you can get hold of your activity and thus its context:

class MyClass extends Activity{
    private Activity thisActivity;
    @Override
protected void onCreate(Bundle savedInstanceState) {
            thisActivity = this;
    }
}

Hope that helps.

How to use a variable inside a regular expression?

more example

I have configus.yml with flows files

"pattern":
  - _(\d{14})_
"datetime_string":
  - "%m%d%Y%H%M%f"

in python code I use

data_time_real_file=re.findall(r""+flows[flow]["pattern"][0]+"", latest_file)

How do I create a URL shortener?

Don't know if anyone will find this useful - it is more of a 'hack n slash' method, yet is simple and works nicely if you want only specific chars.

$dictionary = "abcdfghjklmnpqrstvwxyz23456789";
$dictionary = str_split($dictionary);

// Encode
$str_id = '';
$base = count($dictionary);

while($id > 0) {
    $rem = $id % $base;
    $id = ($id - $rem) / $base;
    $str_id .= $dictionary[$rem];
}


// Decode
$id_ar = str_split($str_id);
$id = 0;

for($i = count($id_ar); $i > 0; $i--) {
    $id += array_search($id_ar[$i-1], $dictionary) * pow($base, $i - 1);
} 

How can I change the Bootstrap default font family using font from Google?

Another way is to download source code then change following vaiables in variables.less

@font-family-sans-serif:  "Helvetica Neue", Helvetica, Arial, sans-serif;
@font-family-serif:       Georgia, "Times New Roman", Times, serif;
//** Default monospace fonts for `<code>`, `<kbd>`, and `<pre>`.
@font-family-monospace:   Menlo, Monaco, Consolas, "Courier New", monospace;
@font-family-base:        @font-family-sans-serif;

And then compile it to .css file

How to read an external local JSON file in JavaScript?

Depending on your browser, you may access to your local files. But this may not work for all the users of your app.

To do this, you can try the instructions from here: http://www.html5rocks.com/en/tutorials/file/dndfiles/

Once your file is loaded, you can retrieve the data using:

var jsonData = JSON.parse(theTextContentOfMyFile);

Path.Combine for URLs?

Well, I just concatenate two strings and use regular expressions to do the cleaning part.

    public class UriTool
    {
        public static Uri Join(string path1, string path2)
        {
            string url = path1 + "/" + path2;
            url = Regex.Replace(url, "(?<!http:)/{2,}", "/");

            return new Uri(url);
        }
    }

So, you can use it like this:

    string path1 = "http://someaddress.com/something/";
    string path2 = "/another/address.html";
    Uri joinedUri = UriTool.Join(path1, path2);

    // joinedUri.ToString() returns "http://someaddress.com/something/another/address.html"

Select specific row from mysql table

You can use LIMIT 2,1 instead of WHERE row_number() = 3.

As the documentation explains, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return.

Keep in mind that it's an 0-based index. So, if you want the line number n, the first argument should be n-1. The second argument will always be 1, because you just want one row. For example, if you want the line number 56 of a table customer:

SELECT * FROM customer LIMIT 55,1

CAST to DECIMAL in MySQL

An alternative, I think for your purpose, is to use the round() function:

select round((10 * 1.5),2) // prints 15.00

You can try it here:

Install a .NET windows service without InstallUtil.exe

Here is a class I use when writing services. I usually have an interactive screen that comes up when the service is not called. From there I use the class as needed. It allows for multiple named instances on the same machine -hence the InstanceID field

Sample Call

  IntegratedServiceInstaller Inst = new IntegratedServiceInstaller();
  Inst.Install("MySvc", "My Sample Service", "Service that executes something",
                    _InstanceID,
// System.ServiceProcess.ServiceAccount.LocalService,      // this is more secure, but only available in XP and above and WS-2003 and above
  System.ServiceProcess.ServiceAccount.LocalSystem,       // this is required for WS-2000
  System.ServiceProcess.ServiceStartMode.Automatic);
  if (controller == null)
  {
    controller = new System.ServiceProcess.ServiceController(String.Format("MySvc_{0}", _InstanceID), ".");
                }
                if (controller.Status == System.ServiceProcess.ServiceControllerStatus.Running)
                {
                    Start_Stop.Text = "Stop Service";
                    Start_Stop_Debugging.Enabled = false;
                }
                else
                {
                    Start_Stop.Text = "Start Service";
                    Start_Stop_Debugging.Enabled = true;
                }

The class itself

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Microsoft.Win32;

namespace MySvc
{
    class IntegratedServiceInstaller
    {
        public void Install(String ServiceName, String DisplayName, String Description,
            String InstanceID,
            System.ServiceProcess.ServiceAccount Account, 
            System.ServiceProcess.ServiceStartMode StartMode)
        {
            //http://www.theblacksparrow.com/
            System.ServiceProcess.ServiceProcessInstaller ProcessInstaller = new System.ServiceProcess.ServiceProcessInstaller();
            ProcessInstaller.Account = Account;

            System.ServiceProcess.ServiceInstaller SINST = new System.ServiceProcess.ServiceInstaller();

            System.Configuration.Install.InstallContext Context = new System.Configuration.Install.InstallContext();
            string processPath = Process.GetCurrentProcess().MainModule.FileName;
            if (processPath != null && processPath.Length > 0)
            {
                System.IO.FileInfo fi = new System.IO.FileInfo(processPath);

                String path = String.Format("/assemblypath={0}", fi.FullName);
                String[] cmdline = { path };
                Context = new System.Configuration.Install.InstallContext("", cmdline);
            }

            SINST.Context = Context;
            SINST.DisplayName = String.Format("{0} - {1}", DisplayName, InstanceID);
            SINST.Description = String.Format("{0} - {1}", Description, InstanceID);
            SINST.ServiceName = String.Format("{0}_{1}", ServiceName, InstanceID);
            SINST.StartType = StartMode;
            SINST.Parent = ProcessInstaller;

            // http://bytes.com/forum/thread527221.html
            SINST.ServicesDependedOn = new String[] { "Spooler", "Netlogon", "Netman" };

            System.Collections.Specialized.ListDictionary state = new System.Collections.Specialized.ListDictionary();
            SINST.Install(state);

            // http://www.dotnet247.com/247reference/msgs/43/219565.aspx
            using (RegistryKey oKey = Registry.LocalMachine.OpenSubKey(String.Format(@"SYSTEM\CurrentControlSet\Services\{0}_{1}", ServiceName, InstanceID), true))
            {
                try
                {
                    Object sValue = oKey.GetValue("ImagePath");
                    oKey.SetValue("ImagePath", sValue);
                }
                catch (Exception Ex)
                {
                    System.Windows.Forms.MessageBox.Show(Ex.Message);
                }
            }

        }
        public void Uninstall(String ServiceName, String InstanceID)
        {
            //http://www.theblacksparrow.com/
            System.ServiceProcess.ServiceInstaller SINST = new System.ServiceProcess.ServiceInstaller();

            System.Configuration.Install.InstallContext Context = new System.Configuration.Install.InstallContext("c:\\install.log", null);
            SINST.Context = Context;
            SINST.ServiceName = String.Format("{0}_{1}", ServiceName, InstanceID);
            SINST.Uninstall(null);
        }
    }
}

Why this line xmlns:android="http://schemas.android.com/apk/res/android" must be the first in the layout xml file?

In XML, xmlns declares a Namespace. In fact, when you do:

<LinearLayout android:id>
</LinearLayout>

Instead of calling android:id, the xml will use http://schemas.android.com/apk/res/android:id to be unique. Generally this page doesn't exist (it's a URI, not a URL), but sometimes it is a URL that explains the used namespace.

The namespace has pretty much the same uses as the package name in a Java application.

Here is an explanation.

Uniform Resource Identifier (URI)

A Uniform Resource Identifier (URI) is a string of characters which identifies an Internet Resource.

The most common URI is the Uniform Resource Locator (URL) which identifies an Internet domain address. Another, not so common type of URI is the Universal Resource Name (URN).

In our examples we will only use URLs.

How to change package name in android studio?

It can be done very easily in one step. You don't have to touch AndroidManifest. Instead do the following:

  1. right click on the root folder of your project.
  2. Click "Open Module Setting".
  3. Go to the Flavours tab.
  4. Change the applicationID to whatever package name you want. Press OK.

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

This issue is still up on keras git. I hope it gets solved as soon as possible. Until then, try downgrading your numpy version to 1.16.2. It seems to solve the problem.

!pip install numpy==1.16.1
import numpy as np

This version of numpy has the default value of allow_pickle as True.

Inline functions in C#?

Yes Exactly, the only distinction is the fact it returns a value.

Simplification (not using expressions):

List<T>.ForEach Takes an action, it doesn't expect a return result.

So an Action<T> delegate would suffice.. say:

List<T>.ForEach(param => Console.WriteLine(param));

is the same as saying:

List<T>.ForEach(delegate(T param) { Console.WriteLine(param); });

the difference is that the param type and delegate decleration are inferred by usage and the braces aren't required on a simple inline method.

Where as

List<T>.Where Takes a function, expecting a result.

So an Function<T, bool> would be expected:

List<T>.Where(param => param.Value == SomeExpectedComparison);

which is the same as:

List<T>.Where(delegate(T param) { return param.Value == SomeExpectedComparison; });

You can also declare these methods inline and asign them to variables IE:

Action myAction = () => Console.WriteLine("I'm doing something Nifty!");

myAction();

or

Function<object, string> myFunction = theObject => theObject.ToString();

string myString = myFunction(someObject);

I hope this helps.

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

The Pythonic way of summing an array is using sum. For other purposes, you can sometimes use some combination of reduce (from the functools module) and the operator module, e.g.:

def product(xs):
    return reduce(operator.mul, xs, 1)

Be aware that reduce is actually a foldl, in Haskell terms. There is no special syntax to perform folds, there's no builtin foldr, and actually using reduce with non-associative operators is considered bad style.

Using higher-order functions is quite pythonic; it makes good use of Python's principle that everything is an object, including functions and classes. You are right that lambdas are frowned upon by some Pythonistas, but mostly because they tend not to be very readable when they get complex.

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

I had the same problem. This is related to hibernate. I changed the database from dev to production in hibernate.cfg.xml but there were catalog attribute in other hbm.xml files with the old database name and it was causing the issue.

Instead of telling incorrect database name, it showed Permission denied error.

So make sure to change the database name everywhere or just remove the catalog attribute

Vue.js unknown custom element

Be sure that you have added the component to the components.

For example:

export default {
data() {
    return {}
},
components: {
    'lead-status-modal': LeadStatusModal,
},
}

Why is there an unexplainable gap between these inline-block div elements?

In this instance, your div elements have been changed from block level elements to inline elements. A typical characteristic of inline elements is that they respect the whitespace in the markup. This explains why a gap of space is generated between the elements. (example)

There are a few solutions that can be used to solve this.

Method 1 - Remove the whitespace from the markup

Example 1 - Comment the whitespace out: (example)

<div>text</div><!--
--><div>text</div><!--
--><div>text</div><!--
--><div>text</div><!--
--><div>text</div>

Example 2 - Remove the line breaks: (example)

<div>text</div><div>text</div><div>text</div><div>text</div><div>text</div>

Example 3 - Close part of the tag on the next line (example)

<div>text</div
><div>text</div
><div>text</div
><div>text</div
><div>text</div>

Example 4 - Close the entire tag on the next line: (example)

<div>text
</div><div>text
</div><div>text
</div><div>text
</div><div>text
</div>

Method 2 - Reset the font-size

Since the whitespace between the inline elements is determined by the font-size, you could simply reset the font-size to 0, and thus remove the space between the elements.

Just set font-size: 0 on the parent elements, and then declare a new font-size for the children elements. This works, as demonstrated here (example)

#parent {
    font-size: 0;
}

#child {
    font-size: 16px;
}

This method works pretty well, as it doesn't require a change in the markup; however, it doesn't work if the child element's font-size is declared using em units. I would therefore recommend removing the whitespace from the markup, or alternatively floating the elements and thus avoiding the space generated by inline elements.

Method 3 - Set the parent element to display: flex

In some cases, you can also set the display of the parent element to flex. (example)

This effectively removes the spaces between the elements in supported browsers. Don't forget to add appropriate vendor prefixes for additional support.

.parent {
    display: flex;
}
.parent > div {
    display: inline-block;
    padding: 1em;
    border: 2px solid #f00;
}

_x000D_
_x000D_
.parent {_x000D_
    display: flex;_x000D_
}_x000D_
.parent > div {_x000D_
    display: inline-block;_x000D_
    padding: 1em;_x000D_
    border: 2px solid #f00;_x000D_
}
_x000D_
<div class="parent">_x000D_
    <div>text</div>_x000D_
    <div>text</div>_x000D_
    <div>text</div>_x000D_
    <div>text</div>_x000D_
    <div>text</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Sides notes:

It is incredibly unreliable to use negative margins to remove the space between inline elements. Please don't use negative margins if there are other, more optimal, solutions.

How to make a query with group_concat in sql server

Please run the below query, it doesn't requires STUFF and GROUP BY in your case:

Select
      A.maskid
    , A.maskname
    , A.schoolid
    , B.schoolname
    , CAST((
          SELECT  T.maskdetail+','
          FROM dbo.maskdetails T
          WHERE A.maskid = T.maskid
          FOR XML PATH(''))as varchar(max)) as maskdetail 
FROM dbo.tblmask A
JOIN dbo.school B ON B.ID = A.schoolid

Git checkout: updating paths is incompatible with switching branches

Not sure if this is helpful or exactly relevant to your question, but if you are trying to fetch and checkout only a single branch from the remote repository, then the following git commands will do the trick:

url= << URL TO REPOSITORY >>
branch= << BRANCH NAME >>

git init
git remote add origin $url
git fetch origin $branch:origin/$branch
git checkout -b $branch --track origin/$branch

Regarding Java switch statements - using return and omitting breaks in each case

I think that what you have written is perfectly fine. I also don't see any readability issue with having multiple return statements.

I would always prefer to return from the point in the code when I know to return and this will avoid running logic below the return.

There can be an argument for having a single return point for debugging and logging. But, in your code, there is no issue of debugging and logging if we use it. It is very simple and readable the way you wrote.

Get content uri from file path in android

Easiest and the robust way for creating Content Uri content:// from a File is to use FileProvider. Uri provided by FileProvider can be used also providing Uri for sharing files with other apps too. To get File Uri from a absolute path of File you can use DocumentFile.fromFile(new File(path, name)), it's added in Api 22, and returns null for versions below.

File imagePath = new File(Context.getFilesDir(), "images");
File newFile = new File(imagePath, "default_image.jpg");
Uri contentUri = getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);

What is so bad about singletons?

  1. It is easily (ab)used as a global variable.
  2. Classes that depend on singletons are relatively harder to unit test in isolation.

How to change string into QString?

Alternative way:

std::string s = "This is an STL string";
QString qs = QString::fromAscii(s.data(), s.size());

This has the advantage of not using .c_str() which might cause the std::string to copy itself in case there is no place to add the '\0' at the end.

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

I think you should indeed be using the Control overload of the RegisterStartupScript.

I've tried the following code in a server control:

[ToolboxData("<{0}:AlertControl runat=server></{0}:AlertControl>")]
public class AlertControl : Control{
    protected override void OnInit(EventArgs e){
        base.OnInit(e);
        string script = "alert(\"Hello!\");";
        ScriptManager.RegisterStartupScript(this, GetType(), 
                      "ServerControlScript", script, true);
    }
}

Then in my page I have:

protected override void OnInit(EventArgs e){
    base.OnInit(e);
    Placeholder1.Controls.Add(new AlertControl());
}

Where Placeholder1 is a placeholder in an update panel. The placeholder has a couple of other controls on in it, including buttons.

This behaved exactly as you would expect, I got an alert saying "Hello" every time I loaded the page or caused the update panel to update.

The other thing you could look at is to hook into some of the page lifecycle events that are fired during an update panel request:

Sys.WebForms.PageRequestManager.getInstance()
   .add_endRequest(EndRequestHandler);

The PageRequestManager endRequestHandler event fires every time an update panel completes its update - this would allow you to call a method to set up your control.

My only other questions are:

  • What is your script actually doing?
  • Presumably you can see the script in the HTML at the bottom of the page (just before the closing </form> tag)?
  • Have you tried putting a few "alert("Here");" calls in your startup script to see if it's being called correctly?
  • Have you tried Firefox and Firebug - is that reporting any script errors?

Difference between framework vs Library vs IDE vs API vs SDK vs Toolkits?

An IDE is an integrated development environment - a suped-up text editor with additional support for developing (such as forms designers, resource editors, etc), compiling and debugging applications. e.g Eclipse, Visual Studio.

A Library is a chunk of code that you can call from your own code, to help you do things more quickly/easily. For example, a Bitmap Processing library will provide facilities for loading and manipulating bitmap images, saving you having to write all that code for yourself. Typically a library will only offer one area of functionality (processing images or operating on zip files)

An API (application programming interface) is a term meaning the functions/methods in a library that you can call to ask it to do things for you - the interface to the library.

An SDK (software development kit) is a library or group of libraries (often with extra tool applications, data files and sample code) that aid you in developing code that uses a particular system (e.g. extension code for using features of an operating system (Windows SDK), drawing 3D graphics via a particular system (DirectX SDK), writing add-ins to extend other applications (Office SDK), or writing code to make a device like an Arduino or a mobile phone do what you want). An SDK will still usually have a single focus.

A toolkit is like an SDK - it's a group of tools (and often code libraries) that you can use to make it easier to access a device or system... Though perhaps with more focus on providing tools and applications than on just code libraries.

A framework is a big library or group of libraries that provides many services (rather than perhaps only one focussed ability as most libraries/SDKs do). For example, .NET provides an application framework - it makes it easier to use most (if not all) of the disparate services you need (e.g. Windows, graphics, printing, communications, etc) to write a vast range of applications - so one "library" provides support for pretty much everything you need to do. Often a framework supplies a complete base on which you build your own code, rather than you building an application that consumes library code to do parts of its work.

There are of course many examples in the wild that won't exactly match these descriptions though.

How to solve java.lang.OutOfMemoryError trouble in Android

If you are getting this Error java.lang.OutOfMemoryError this is the most common problem occurs in Android. This error is thrown by the Java Virtual Machine (JVM) when an object cannot be allocated due to lack of memory space.

Try this android:hardwareAccelerated="false" , android:largeHeap="true"in your manifest.xml file under application like this:

<application
  android:name=".MyApplication"
  android:allowBackup="true"
  android:icon="@mipmap/ic_launcher"
  android:label="@string/app_name"
  android:theme="@style/AppTheme"
  android:hardwareAccelerated="false"
  android:largeHeap="true" />

Where is jarsigner?

This will install jdk for you and check for the jarsigner inside it

sudo apt install -y default-jdk

to find jarsigner you can use whereis jarsigner

How to unzip a list of tuples into individual lists?

If you want a list of lists:

>>> [list(t) for t in zip(*l)]
[[1, 3, 8], [2, 4, 9]]

If a list of tuples is OK:

>>> zip(*l)
[(1, 3, 8), (2, 4, 9)]

Bootstrap dropdown sub menu missing

@skelly solution is good but will not work on mobile devices as the hover state won't work.

I have added a little bit of JS to get the BS 2.3.2 behavior back.

PS: it will work with the CSS you get there: http://bootply.com/71520 though you can comment the following part:

CSS:

/*.dropdown-submenu:hover>.dropdown-menu{display:block;}*/

JS:

$('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {
  // Avoid following the href location when clicking
  event.preventDefault();
  // Avoid having the menu to close when clicking
  event.stopPropagation();
  // If a menu is already open we close it
  $('ul.dropdown-menu [data-toggle=dropdown]').parent().removeClass('open');
  // opening the one you clicked on
  $(this).parent().addClass('open');
});

The result can be found on my WordPress theme (Top of the page): http://shprinkone.julienrenaux.fr/

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

Binary floating-point numbers have interesting precision characteristics, since the value is stored as a binary integer raised to a binary power. When dealing with sub-integer values (that is, values between 0 and 1), negative powers of two "round off" very differently than negative powers of ten.

For example, the number 0.1 can be represented by 1 x 10-1, but there is no combination of base-2 exponent and mantissa that can precisely represent 0.1 -- the closest you get is 0.10000000000000001.

So if you have an application where you are working with values like 0.1 or 0.01 a great deal, but where small (less than 0.000000000000001%) errors cannot be tolerated, then binary floating-point numbers are not for you.

Conversely, if powers of ten are not "special" to your application (powers of ten are important in currency calculations, but not in, say, most applications of physics), then you are actually better off using binary floating-point, since it's usually at least an order of magnitude faster, and it is much more memory efficient.

The article from the Python documentation on floating point issues and limitations does an excellent job of explaining this issue in an easy to understand form. Wikipedia also has a good article on floating point that explains the math behind the representation.

How can I customize the tab-to-space conversion factor?

By default, Visual Studio Code auto-detects the indentation of the current open file. If you want to switch this feature off and make all indentation, for example, two spaces, you'd do the following in your User Settings or Workspace settings.

{
    "editor.tabSize": 2,

    "editor.detectIndentation": false
}

Using .htaccess to make all .html pages to run as .php files?

You may also use the H or T flag of mod_rewrite to force all .html files to be parsed by php handler :

using H (Handler) flag:

 RewriteEngine on

RewriteRule \.(html|htm)$ - [H=application/x-httpd-php5]

using T (Type) flag :

 RewriteEngine on

RewriteRule \.(html|htm)$ - [T=application/x-httpd-php5]

Or you can add more extensions to the rule pattern seprated by a pipe | that you want to be parsed by php handler

ex :

RewriteRule \.(html|htm|txt|foo)$ - [T=application/x-httpd-php5]

the example above will change the mime type of files that end with .html , .htm , .txt , .foo to php.

Note : on some servers you will have to change php5 to php to get this example to work in handler string:

Change it

[T=application/x-httpd-php5]

to

[T=application/x-httpd-php]

RelativeLayout center vertical

This is working for me.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rell_main_bg"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#096d74" > 

<ImageView 
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:src="@drawable/img_logo_large"
    android:contentDescription="@null" />

</RelativeLayout>

How do I change the UUID of a virtual disk?

The correct command is the following one.

VBoxManage internalcommands sethduuid "/home/user/VirtualBox VMs/drupal/drupal.vhd"

The path for the virtual disk contains a space, so it must be enclosed in double quotes to avoid it is parsed as two parameters.

How to change node.js's console font color?

var colorSet = {
    Reset: "\x1b[0m",
    Red: "\x1b[31m",
    Green: "\x1b[32m",
    Yellow: "\x1b[33m",
    Blue: "\x1b[34m",
    Magenta: "\x1b[35m"
};

var funcNames = ["info", "log", "warn", "error"];
var colors = [colorSet.Green, colorSet.Blue, colorSet.Yellow, colorSet.Red];

for (var i = 0; i < funcNames.length; i++) {
    let funcName = funcNames[i];
    let color = colors[i];
    let oldFunc = console[funcName];
    console[funcName] = function () {
        var args = Array.prototype.slice.call(arguments);
        if (args.length) {
            args = [color + args[0]].concat(args.slice(1), colorSet.Reset);
        }
        oldFunc.apply(null, args);
    };
}

// Test:
console.info("Info is green.");
console.log("Log is blue.");
console.warn("Warn is orange.");
console.error("Error is red.");
console.info("--------------------");
console.info("Formatting works as well. The number = %d", 123);

Horizontal Scroll Table in Bootstrap/CSS

Here is one possiblity for you if you are using Bootstrap 3

live view: http://fiddle.jshell.net/panchroma/vPH8N/10/show/

edit view: http://jsfiddle.net/panchroma/vPH8N/

I'm using the resposive table code from http://getbootstrap.com/css/#tables-responsive

ie:

<div class="table-responsive">
<table class="table">
...
</table>
</div>

How to trim whitespace from a Bash variable?

Use:

var=`expr "$var" : "^\ *\(.*[^ ]\)\ *$"`

It removes leading and trailing spaces and is the most basic solution, I believe. Not Bash built-in, but 'expr' is a part of coreutils, so at least no standalone utilities are needed like sed or AWK.

Strip HTML from strings in Python

Simple code!. This will remove all kind of tags and content inside of it.

def rm(s):
    start=False
    end=False
    s=' '+s
    for i in range(len(s)-1):
        if i<len(s):
            if start!=False:
                if s[i]=='>':
                    end=i
                    s=s[:start]+s[end+1:]
                    start=end=False
            else:
                if s[i]=='<':
                    start=i
    if s.count('<')>0:
        self.rm(s)
    else:
        s=s.replace('&nbsp;', ' ')
        return s

But it won't give full result if text contains <> symbols inside it.

Remove from the beginning of std::vector

Two suggestions:

  1. Use std::deque instead of std::vector for better performance in your specific case and use the method std::deque::pop_front().
  2. Rethink (I mean: delete) the & in std::vector<ScanRule>& topPriorityRules;

Java Spring - How to use classpath to specify a file location?

looks like you have maven project and so resources are in classpath by

go for

getClass().getResource("classpath:storedProcedures.sql")

Connecting to SQL Server with Visual Studio Express Editions

If you are using this to get a LINQ to SQL which I do and wanted for my Visual Developer, 1) get the free Visual WEB Developer, use that to connect to SQL Server instance, create your LINQ interface, then copy the generated files into your Vis-Dev project (I don't use VD because it sounds funny). Include only the *.dbml files. The Vis-Dev environment will take a second or two to recognize the supporting files. It is a little extra step but for sure better than doing it by hand or giving up on it altogether or EVEN WORSE, paying for it. Mooo ha ha haha.

AngularJS view not updating on model change

As Ajay beniwal mentioned above you need to use Apply to start digestion.

var app = angular.module('test', []);

app.controller('TestCtrl', function ($scope) {
   $scope.testValue = 0;

    setInterval(function() {
        console.log($scope.testValue++);
        $scope.$apply() 
    }, 500);
});

Summarizing multiple columns with dplyr?

All the examples are great, but I figure I'd add one more to show how working in a "tidy" format simplifies things. Right now the data frame is in "wide" format meaning the variables "a" through "d" are represented in columns. To get to a "tidy" (or long) format, you can use gather() from the tidyr package which shifts the variables in columns "a" through "d" into rows. Then you use the group_by() and summarize() functions to get the mean of each group. If you want to present the data in a wide format, just tack on an additional call to the spread() function.


library(tidyverse)

# Create reproducible df
set.seed(101)
df <- tibble(a   = sample(1:5, 10, replace=T), 
             b   = sample(1:5, 10, replace=T), 
             c   = sample(1:5, 10, replace=T), 
             d   = sample(1:5, 10, replace=T), 
             grp = sample(1:3, 10, replace=T))

# Convert to tidy format using gather
df %>%
    gather(key = variable, value = value, a:d) %>%
    group_by(grp, variable) %>%
    summarize(mean = mean(value)) %>%
    spread(variable, mean)
#> Source: local data frame [3 x 5]
#> Groups: grp [3]
#> 
#>     grp        a     b        c        d
#> * <int>    <dbl> <dbl>    <dbl>    <dbl>
#> 1     1 3.000000   3.5 3.250000 3.250000
#> 2     2 1.666667   4.0 4.666667 2.666667
#> 3     3 3.333333   3.0 2.333333 2.333333

Calculating width from percent to pixel then minus by pixel in LESS CSS

I think width: -moz-calc(25% - 1em); is what you are looking for. And you may want to give this Link a look for any further assistance

Java: Literal percent sign in printf statement

You can use StringEscapeUtils from Apache Commons Logging utility or escape manually using code for each character.

MySQL/SQL: Group by date only on a Datetime column

SELECT SUM(No), HOUR(dateofissue) 
FROM tablename 
WHERE dateofissue>='2011-07-30' 
GROUP BY HOUR(dateofissue)

It will give the hour by sum from a particular day!

How to install PIP on Python 3.6?

There are situations when your pip doesn't get downloaded along with python installation. Even your whole script folder can be empty.

You can do so manually as well.

Just head to Command Prompt and type python -m ensurepip --default-pip Press Enter.

Make sure that value of path variable is updated.

This will do the Trick

Letter Count on a string

I see a few things wrong.

  1. You reuse the identifier char, so that will cause issues.
  2. You're saying if char == word[count] instead of word[some index]
  3. You return after the first iteration of the for loop!

You don't even need the while. If you rename the char param to search,

for char in word:
    if char == search:
        count += 1
return count

Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python

In addition to the answers above, you can check the type of object using type(plt.subplots()) which returns a tuple, on the other hand, type(plt.subplot()) returns matplotlib.axes._subplots.AxesSubplot which you can't unpack.

How can I download a specific Maven artifact in one command line?

With the latest version (2.8) of the Maven Dependency Plugin, downloading an artifact from the Maven Central Repository is as simple as:

mvn org.apache.maven.plugins:maven-dependency-plugin:2.8:get -Dartifact=groupId:artifactId:version[:packaging[:classifier]]

where groupId:artifactId:version, etc. are the Maven coordinates

An example, tested with Maven 2.0.9, Maven 2.2.1, and Maven 3.0.4:

mvn org.apache.maven.plugins:maven-dependency-plugin:2.8:get -Dartifact=org.hibernate:hibernate-entitymanager:3.4.0.GA:jar:sources

(Thanks to Pascal Thivent for providing his wonderful answer in the first place. I am adding another answer, because it wouldn't fit in a comment and it would be too extensive for an edit.)

Change NULL values in Datetime format to empty string

declare @date datetime; set @date = null
--declare @date datetime; set @date = '2015-01-01'

select coalesce( convert( varchar(10), @date, 103 ), '')

How to type ":" ("colon") in regexp?

Colon does not have special meaning in a character class and does not need to be escaped. According to the PHP regex docs, the only characters that need to be escaped in a character class are the following:

All non-alphanumeric characters other than \, -, ^ (at the start) and the terminating ] are non-special in character classes, but it does no harm if they are escaped.

For more info about Java regular expressions, see the docs.

Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running?

I could be wrong, but I'm pretty sure that the "interrupt kernel" button just sends a SIGINT signal to the code that you're currently running (this idea is supported by Fernando's comment here), which is the same thing that hitting CTRL+C would do. Some processes within python handle SIGINTs more abruptly than others.

If you desperately need to stop something that is running in iPython Notebook and you started iPython Notebook from a terminal, you can hit CTRL+C twice in that terminal to interrupt the entire iPython Notebook server. This will stop iPython Notebook alltogether, which means it won't be possible to restart or save your work, so this is obviously not a great solution (you need to hit CTRL+C twice because it's a safety feature so that people don't do it by accident). In case of emergency, however, it generally kills the process more quickly than the "interrupt kernel" button.

Overlaying histograms with ggplot2 in R

Using @joran's sample data,

ggplot(dat, aes(x=xx, fill=yy)) + geom_histogram(alpha=0.2, position="identity")

note that the default position of geom_histogram is "stack."

see "position adjustment" of this page:

docs.ggplot2.org/current/geom_histogram.html

Convert Python program to C/C++ code?

I know this is an older thread but I wanted to give what I think to be helpful information.

I personally use PyPy which is really easy to install using pip. I interchangeably use Python/PyPy interpreter, you don't need to change your code at all and I've found it to be roughly 40x faster than the standard python interpreter (Either Python 2x or 3x). I use pyCharm Community Edition to manage my code and I love it.

I like writing code in python as I think it lets you focus more on the task than the language, which is a huge plus for me. And if you need it to be even faster, you can always compile to a binary for Windows, Linux, or Mac (not straight forward but possible with other tools). From my experience, I get about 3.5x speedup over PyPy when compiling, meaning 140x faster than python. PyPy is available for Python 3x and 2x code and again if you use an IDE like PyCharm you can interchange between say PyPy, Cython, and Python very easily (takes a little of initial learning and setup though).

Some people may argue with me on this one, but I find PyPy to be faster than Cython. But they're both great choices though.

Edit: I'd like to make another quick note about compiling: when you compile, the resulting binary is much bigger than your python script as it builds all dependencies into it, etc. But then you get a few distinct benefits: speed!, now the app will work on any machine (depending on which OS you compiled for, if not all. lol) without Python or libraries, it also obfuscates your code and is technically 'production' ready (to a degree). Some compilers also generate C code, which I haven't really looked at or seen if it's useful or just gibberish. Good luck.

Hope that helps.

Android Viewpager as Image Slide Gallery

In Jake's ViewPageIndicator he has implemented View pager to display a String array (i.e. ["this","is","a","text"]) which you pass from YourAdapter.java (that extends FragmentPagerAdapter) to the YourFragment.java which returns a View to the viewpager.

In order to display something different, you simply have to change the context type your passing. In this case you want to pass images instead of text, as shown in the sample below:

This is how you setup your Viewpager:

public class PlaceDetailsFragment extends SherlockFragment {
    PlaceSlidesFragmentAdapter mAdapter;
    ViewPager mPager;
    PageIndicator mIndicator;

    public static final String TAG = "detailsFragment";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_place_details,
                container, false);

        mAdapter = new PlaceSlidesFragmentAdapter(getActivity()
                .getSupportFragmentManager());

        mPager = (ViewPager) view.findViewById(R.id.pager);
        mPager.setAdapter(mAdapter);

        mIndicator = (CirclePageIndicator) view.findViewById(R.id.indicator);
        mIndicator.setViewPager(mPager);
        ((CirclePageIndicator) mIndicator).setSnap(true);

        mIndicator
                .setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {
                        Toast.makeText(PlaceDetailsFragment.this.getActivity(),
                                "Changed to page " + position,
                                Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onPageScrolled(int position,
                            float positionOffset, int positionOffsetPixels) {
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {
                    }
                });
        return view;
    }

}

your_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >



    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <com.viewpagerindicator.CirclePageIndicator
        android:id="@+id/indicator"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dip" />

</LinearLayout>

YourAdapter.java

public class PlaceSlidesFragmentAdapter extends FragmentPagerAdapter implements
        IconPagerAdapter {

    private int[] Images = new int[] { R.drawable.photo1, R.drawable.photo2,
            R.drawable.photo3, R.drawable.photo4

    };

    protected static final int[] ICONS = new int[] { R.drawable.marker,
            R.drawable.marker, R.drawable.marker, R.drawable.marker };

    private int mCount = Images.length;

    public PlaceSlidesFragmentAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return new PlaceSlideFragment(Images[position]);
    }

    @Override
    public int getCount() {
        return mCount;
    }

    @Override
    public int getIconResId(int index) {
        return ICONS[index % ICONS.length];
    }

    public void setCount(int count) {
        if (count > 0 && count <= 10) {
            mCount = count;
            notifyDataSetChanged();
        }
    }
}

YourFragment.java

// you need to return image instaed of text from here.//

public final class PlaceSlideFragment extends Fragment {
    int imageResourceId;

    public PlaceSlideFragment(int i) {
        imageResourceId = i;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        ImageView image = new ImageView(getActivity());
        image.setImageResource(imageResourceId);

        LinearLayout layout = new LinearLayout(getActivity());
        layout.setLayoutParams(new LayoutParams());

        layout.setGravity(Gravity.CENTER);
        layout.addView(image);

        return layout;
    }
}

You should get a View pager like this from the above code. enter image description here

Using multiple delimiters in awk

I see many perfect answers are up on the board, but still would like to upload my piece of code too,

awk -F"/" '{print $3 " " $5 " " $7}' sam | sed 's/ cat.* =//g'

Determine the type of an object?

As an aside to the previous answers, it's worth mentioning the existence of collections.abc which contains several abstract base classes (ABCs) that complement duck-typing.

For example, instead of explicitly checking if something is a list with:

isinstance(my_obj, list)

you could, if you're only interested in seeing if the object you have allows getting items, use collections.abc.Sequence:

from collections.abc import Sequence
isinstance(my_obj, Sequence) 

if you're strictly interested in objects that allow getting, setting and deleting items (i.e mutable sequences), you'd opt for collections.abc.MutableSequence.

Many other ABCs are defined there, Mapping for objects that can be used as maps, Iterable, Callable, et cetera. A full list of all these can be seen in the documentation for collections.abc.

Initializing select with AngularJS and ng-repeat

If you are using md-select and ng-repeat ing md-option from angular material then you can add ng-model-options="{trackBy: '$value.id'}" to the md-select tag ash shown in this pen

Code:

_x000D_
_x000D_
<md-select ng-model="user" style="min-width: 200px;" ng-model-options="{trackBy: '$value.id'}">_x000D_
  <md-select-label>{{ user ? user.name : 'Assign to user' }}</md-select-label>_x000D_
  <md-option ng-value="user" ng-repeat="user in users">{{user.name}}</md-option>_x000D_
</md-select>
_x000D_
_x000D_
_x000D_

SQL query to find Nth highest salary from a salary table

finding the highest salary

select MAX(Salary) from Employee;

finding the 2nd highest salary

Query-1

SELECT MAX(Salary) FROM Employee
WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee);

Query-2

select MAX(Salary) from Employee
WHERE Salary <> (select MAX(Salary) from Employee )

finding the nth highest salary

Query-1

SELECT * /*This is the outer query part */
FROM Employee Emp1
WHERE (N-1) = ( /* Subquery starts here */
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)

Query-2

SELECT *
FROM Employee Emp1
WHERE (1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)

nth highest salary using the TOP keyword in SQL Server

SELECT TOP 1 Salary
FROM (
      SELECT DISTINCT TOP N Salary
      FROM Employee
      ORDER BY Salary DESC
      ) AS Emp
ORDER BY Salary

Find the nth highest salary in MySQL

SELECT Salary FROM Employee 
ORDER BY Salary DESC LIMIT n-1,1

Find the nth highest salary in SQL Server

SELECT Salary FROM Employee 
ORDER BY Salary DESC OFFSET N-1 ROW(S) 
FETCH FIRST ROW ONLY

Find the nth highest salary in Oracle using rownum

select * from (
  select Emp.*, 
row_number() over (order by Salary DESC) rownumb 
from Employee Emp
)
where rownumb = n;  /*n is nth highest salary*/

Find the nth highest salary in Oracle using RANK

select * FROM (
select EmployeeID, Salary
,rank() over (order by Salary DESC) ranking
from Employee
)
WHERE ranking = N;

Load local javascript file in chrome for testing?

Windows 8.1 add:

--allow-file-access-from-files

to the end of the target text box after the quotes.

EX: "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files

Works like a charm

Latex - Change margins of only a few pages

A slight modification of this to change the \voffset works for me:

\newenvironment{changemargin}[1]{
  \begin{list}{}{
    \setlength{\voffset}{#1}
  }
  \item[]}{\end{list}}

And then put your figures in a \begin{changemargin}{-1cm}...\end{changemargin} environment.

pass post data with window.location.href

Short answer: no. window.location.href is not capable of passing POST data.

Somewhat more satisfying answer: You can use this function to clone all your form data and submit it.

var submitMe = document.createElement("form");
submitMe.action = "YOUR_URL_HERE"; // Remember to change me
submitMe.method = "post";
submitMe.enctype = "multipart/form-data";
var nameJoiner = "_";
// ^ The string used to join form name and input name
//   so that you can differentiate between forms when
//   processing the data server-side.
submitMe.importFields = function(form){
    for(k in form.elements){
        if(input = form.elements[k]){
            if(input.type!="submit"&&
                     (input.nodeName=="INPUT"
                    ||input.nodeName=="TEXTAREA"
                    ||input.nodeName=="BUTTON"
                    ||input.nodeName=="SELECT")
                     ){
                var output = input.cloneNode(true);
                output.name = form.name + nameJoiner + input.name;
                this.appendChild(output);
            }
        }
    }
}
  • Do submitMe.importFields(form_element); for each of the three forms you want to submit.
  • This function will add each form's name to the names of its child inputs (If you have an <input name="email"> in <form name="login">, the submitted name will be login_name.
  • You can change the nameJoiner variable to something other than _ so it doesn't conflict with your input naming scheme.
  • Once you've imported all the necessary forms, do submitMe.submit();

List of all index & index columns in SQL Server DB

The above solution is elegant, but according to MS, INDEXKEY_PROPERTY is being deprecated. See: http://msdn.microsoft.com/en-us/library/ms186773.aspx

how get yesterday and tomorrow datetime in c#

DateTime tomorrow = DateTime.Today.AddDays(1);
DateTime yesterday = DateTime.Today.AddDays(-1);

Python Replace \\ with \

path = "C:\\Users\\Programming\\Downloads"
# Replace \\ with a \ along with any random key multiple times
path.replace('\\', '\pppyyyttthhhooonnn')
# Now replace pppyyyttthhhooonnn with a blank string
path.replace("pppyyyttthhhooonnn", "")

print(path)

#Output... C:\Users\Programming\Downloads

NameError: uninitialized constant (rails)

In my case, I named a column name type and tried to set its value as UNPREPARED. And I got an error message like this:

Caused by: api_1 | NameError: uninitialized constant UNPREPARED

In rails, column type is reserved:

ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass: 'UNPREPARED'. This error is raised because the column 'type' is reserved for storing the class in case of inheritance. Pl ease rename this column if you didn't intend it to be used for storing the inheritance class or overwrite Food.inheritance_column to use another column for that information

Excel- compare two cell from different sheet, if true copy value from other cell

In your destination field you want to use VLOOKUP like so:

=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)

VLOOKUP Arguments:

  1. The set fields you want to lookup.
  2. The table range you want to lookup up your value against. The first column of your defined table should be the column you want compared against your lookup field. The table range should also contain the value you want to display (Column F).
  3. This defines what field you want to display upon a match.
  4. FALSE tells VLOOKUP to do an exact match.

How to check if a float value is a whole number

We can use the modulo (%) operator. This tells us how many remainders we have when we divide x by y - expresses as x % y. Every whole number must divide by 1, so if there is a remainder, it must not be a whole number.

This function will return a boolean, True or False, depending on whether n is a whole number.

def is_whole(n):
    return n % 1 == 0

Update a dataframe in pandas while iterating row by row

Well, if you are going to iterate anyhow, why don't use the simplest method of all, df['Column'].values[i]

df['Column'] = ''

for i in range(len(df)):
    df['Column'].values[i] = something/update/new_value

Or if you want to compare the new values with old or anything like that, why not store it in a list and then append in the end.

mylist, df['Column'] = [], ''

for <condition>:
    mylist.append(something/update/new_value)

df['Column'] = mylist

Convert seconds to HH-MM-SS with JavaScript?

This function should do it :

var convertTime = function (input, separator) {
    var pad = function(input) {return input < 10 ? "0" + input : input;};
    return [
        pad(Math.floor(input / 3600)),
        pad(Math.floor(input % 3600 / 60)),
        pad(Math.floor(input % 60)),
    ].join(typeof separator !== 'undefined' ?  separator : ':' );
}

Without passing a separator, it uses : as the (default) separator :

time = convertTime(13551.9941351); // --> OUTPUT = 03:45:51

If you want to use - as a separator, just pass it as the second parameter:

time = convertTime(1126.5135155, '-'); // --> OUTPUT = 00-18-46

See also this Fiddle.

Can't connect to MySQL server error 111

It probably means that your MySQL server is only listening the localhost interface.

If you have lines like this :

bind-address = 127.0.0.1

In your my.cnf configuration file, you should comment them (add a # at the beginning of the lines), and restart MySQL.

sudo service mysql restart

Of course, to do this, you must be the administrator of the server.

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

Every service that is bound in activity must be unbind on app close.

So try using

 onPause(){
   unbindService(YOUR_SERVICE);
   super.onPause();
 }

Pandas groupby month and year

There are different ways to do that.

  • I created the data frame to showcase the different techniques to filter your data.
df = pd.DataFrame({'Date':['01-Jun-13','03-Jun-13', '15-Aug-13', '20-Jan-14', '21-Feb-14'],

'abc':[100,-20,40,25,60],'xyz':[200,50,-5,15,80] })

  • I separated months/year/day and seperated month-year as you explained.
def getMonth(s):
  return s.split("-")[1]

def getDay(s):
  return s.split("-")[0]

def getYear(s):
  return s.split("-")[2]

def getYearMonth(s):
  return s.split("-")[1]+"-"+s.split("-")[2]
  • I created new columns: year, month, day and 'yearMonth'. In your case, you need one of both. You can group using two columns 'year','month' or using one column yearMonth
df['year']= df['Date'].apply(lambda x: getYear(x))
df['month']= df['Date'].apply(lambda x: getMonth(x))
df['day']= df['Date'].apply(lambda x: getDay(x))
df['YearMonth']= df['Date'].apply(lambda x: getYearMonth(x))

Output:

        Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
2  15-Aug-13   40   -5   13   Aug  15    Aug-13
3  20-Jan-14   25   15   14   Jan  20    Jan-14
4  21-Feb-14   60   80   14   Feb  21    Feb-14
  • You can go through the different groups in groupby(..) items.

In this case, we are grouping by two columns:

for key,g in df.groupby(['year','month']):
    print key,g

Output:

('13', 'Jun')         Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
('13', 'Aug')         Date  abc  xyz year month day YearMonth
2  15-Aug-13   40   -5   13   Aug  15    Aug-13
('14', 'Jan')         Date  abc  xyz year month day YearMonth
3  20-Jan-14   25   15   14   Jan  20    Jan-14
('14', 'Feb')         Date  abc  xyz year month day YearMonth

In this case, we are grouping by one column:

for key,g in df.groupby(['YearMonth']):
    print key,g

Output:

Jun-13         Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
Aug-13         Date  abc  xyz year month day YearMonth
2  15-Aug-13   40   -5   13   Aug  15    Aug-13
Jan-14         Date  abc  xyz year month day YearMonth
3  20-Jan-14   25   15   14   Jan  20    Jan-14
Feb-14         Date  abc  xyz year month day YearMonth
4  21-Feb-14   60   80   14   Feb  21    Feb-14
  • In case you wanna access to specific item, you can use get_group

print df.groupby(['YearMonth']).get_group('Jun-13')

Output:

        Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
  • Similar to get_group. This hack would help to filter values and get the grouped values.

This also would give the same result.

print df[df['YearMonth']=='Jun-13'] 

Output:

        Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13

You can select list of abc or xyz values during Jun-13

print df[df['YearMonth']=='Jun-13'].abc.values
print df[df['YearMonth']=='Jun-13'].xyz.values

Output:

[100 -20]  #abc values
[200  50]  #xyz values

You can use this to go through the dates that you have classified as "year-month" and apply cretiria on it to get related data.

for x in set(df.YearMonth): 
    print df[df['YearMonth']==x].abc.values
    print df[df['YearMonth']==x].xyz.values

I recommend also to check this answer as well.

npm not working - "read ECONNRESET"

You may also encounter this error if you have a saved bearer token that is now invalid. I've encountered this when using a private repo where the accounts were wiped and reset, invalidating the tokens. Although your repo may not require authentication, if you have a token from a previous login it will be passed and if it's invalid your connection will be closed.

You can resolve this by either logging in again with the new user name and password, or presumably by simply logging out via npm.

How to get the file path from URI?

Here is the answer to the question here

Actually we have to get it from the sharable ContentProvider of Camera Application.

EDIT . Copying answer that worked for me

private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;

}

Update multiple rows using select statement

None of above answers worked for me in MySQL, the following query worked though:

UPDATE
    Table1 t1
    JOIN
    Table2 t2 ON t1.ID=t2.ID 
SET
    t1.value =t2.value
WHERE
    ...

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

What does "make oldconfig" do exactly in the Linux kernel makefile?

From this page:

Make oldconfig takes the .config and runs it through the rules of the Kconfig files and produces a .config which is consistant with the Kconfig rules. If there are CONFIG values which are missing, the make oldconfig will ask for them.

If the .config is already consistant with the rules found in Kconfig, then make oldconfig is essentially a no-op.

If you were to run make oldconfig, and then run make oldconfig a second time, the second time won't cause any additional changes to be made.