Programs & Examples On #Rocks

Abort trap 6 error in C

Try this:

void drawInitialNim(int num1, int num2, int num3){
    int board[3][50] = {0}; // This is a local variable. It is not possible to use it after returning from this function. 

    int i, j, k;

    for(i=0; i<num1; i++)
        board[0][i] = 'O';
    for(i=0; i<num2; i++)
        board[1][i] = 'O';
    for(i=0; i<num3; i++)
        board[2][i] = 'O';

    for (j=0; j<3;j++) {
        for (k=0; k<50; k++) {
            if(board[j][k] != 0)
                printf("%c", board[j][k]);
        }
        printf("\n");
    }
}

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

Just say goodbye to minimal-ui (for now)

It's true, minimal-ui could be both useful and harmful, and I suppose the trade-off now has another balance, in favor of newer, bigger iPhones.

I've been dealing with the issue while working with my js framework for HTML5 apps. After many attempted solutions, each with their drawbacks, I surrendered to considering that space lost on iPhones previous than 6. Given the situation, I think that the only solid and predictable behavior is a pre-determined one.

In short, I ended up preventing any form of minimal-ui, so at least my screen height is always the same and you always know what actual space you have for your app.

With the help of time, enough users will have more room.


EDIT

How I do it

This is a little simplified, for demo purpose, but should work for you. Assuming you have a main container

html, body, #main {
  height: 100%;
  width: 100%;
  overflow: hidden;
}
.view {
  width: 100%;
  height: 100%;
  overflow: scroll;
}

Then:

  1. then with js, I set #main's height to the window's available height. This also helps dealing with other scrolling bugs found in both iOS and Android. It also means that you need to deal on how to update it, just note that;

  2. I block over-scrolling when reaching the boundaries of the scroll. This one is a bit more deep in my code, but I think you can as well follow the principle of this answer for basic functionality. I think it could flickr a little, but will do the job.


See the demo (on a iPhone)

As a sidenote: this app too is bookmarkable, as it uses an internal routing to hashed addresses, but I also added a prompt iOS users to add to home. I feel this way helps loyalty and returning visitors (and so the lost space is back).

canvas.toDataURL() SecurityError

I had the same error message. I had the file in a simple .html, when I passed the file to php in Apache it worked

html2canvas(document.querySelector('#toPrint')).then(canvas => {
            let pdf = new jsPDF('p', 'mm', 'a4');
            pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298);
            pdf.save(filename);
        });

How to compress an image via Javascript in the browser?

I find that there's simpler solution compared to the accepted answer.

  • Read the files using the HTML5 FileReader API with .readAsArrayBuffer
  • Create a Blob with the file data and get its url with window.URL.createObjectURL(blob)
  • Create new Image element and set it's src to the file blob url
  • Send the image to the canvas. The canvas size is set to desired output size
  • Get the scaled-down data back from canvas via canvas.toDataURL("image/jpeg",0.7) (set your own output format and quality)
  • Attach new hidden inputs to the original form and transfer the dataURI images basically as normal text
  • On backend, read the dataURI, decode from Base64, and save it

As per your question:

Is there a way to compress an image (mostly jpeg, png and gif) directly browser-side, before uploading it

My solution:

  1. Create a blob with the file directly with URL.createObjectURL(inputFileElement.files[0]).

  2. Same as accepted answer.

  3. Same as accepted answer. Worth mentioning that, canvas size is necessary and use img.width and img.height to set canvas.width and canvas.height. Not img.clientWidth.

  4. Get the scale-down image by canvas.toBlob(callbackfunction(blob){}, 'image/jpeg', 0.5). Setting 'image/jpg' has no effect. image/png is also supported. Make a new File object inside the callbackfunction body with let compressedImageBlob = new File([blob]).

  5. Add new hidden inputs or send via javascript . Server doesn't have to decode anything.

Check https://javascript.info/binary for all information. I came up the solution after reading this chapter.


Code:

    <!DOCTYPE html>
    <html>
    <body>
    <form action="upload.php" method="post" enctype="multipart/form-data">
      Select image to upload:
      <input type="file" name="fileToUpload" id="fileToUpload" multiple>
      <input type="submit" value="Upload Image" name="submit">
    </form>
    </body>
    </html>

This code looks far less scary than the other answers..

Update:

One has to put everything inside img.onload. Otherwise canvas will not be able to get the image's width and height correctly as the time canvas is assigned.

    function upload(){
        var f = fileToUpload.files[0];
        var fileName = f.name.split('.')[0];
        var img = new Image();
        img.src = URL.createObjectURL(f);
        img.onload = function(){
            var canvas = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;
            var ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0);
            canvas.toBlob(function(blob){
                    console.info(blob.size);
                    var f2 = new File([blob], fileName + ".jpeg");
                    var xhr = new XMLHttpRequest();
                    var form = new FormData();
                    form.append("fileToUpload", f2);
                    xhr.open("POST", "upload.php");
                    xhr.send(form);
            }, 'image/jpeg', 0.5);
        }
    }

3.4MB .png file compression test with image/jpeg argument set.

    |0.9| 777KB |
    |0.8| 383KB |
    |0.7| 301KB |
    |0.6| 251KB |
    |0.5| 219kB |

Optimal way to concatenate/aggregate strings

Are methods using FOR XML PATH like below really that slow? Itzik Ben-Gan writes that this method has good performance in his T-SQL Querying book (Mr. Ben-Gan is a trustworthy source, in my view).

create table #t (id int, name varchar(20))

insert into #t
values (1, 'Matt'), (1, 'Rocks'), (2, 'Stylus')

select  id
        ,Names = stuff((select ', ' + name as [text()]
        from #t xt
        where xt.id = t.id
        for xml path('')), 1, 2, '')
from #t t
group by id

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]

Is it possible to validate the size and type of input=file in html5

    <form  class="upload-form">
        <input class="upload-file" data-max-size="2048" type="file" >
        <input type=submit>
    </form>
    <script>
$(function(){
    var fileInput = $('.upload-file');
    var maxSize = fileInput.data('max-size');
    $('.upload-form').submit(function(e){
        if(fileInput.get(0).files.length){
            var fileSize = fileInput.get(0).files[0].size; // in bytes
            if(fileSize>maxSize){
                alert('file size is more then' + maxSize + ' bytes');
                return false;
            }else{
                alert('file size is correct- '+fileSize+' bytes');
            }
        }else{
            alert('choose file, please');
            return false;
        }

    });
});
    </script>

http://jsfiddle.net/9bhcB/2/

Regex: Specify "space or start of string" and "space or end of string"

(^|\s) would match space or start of string and ($|\s) for space or end of string. Together it's:

(^|\s)stackoverflow($|\s)

how to set default main class in java?

If you're creating 2 executable JAR files, each will have it's own manifest file, and each manifest file will specify the class that contains the main() method you want to use to start execution.

In each JAR file, the manifest will be a file with the following path / name inside the JAR - META-INF/MANIFEST.MF

There are ways to specify alternatively named files as a JAR's manifest using the JAR command-line parameters.

The specific class you want to use is specified using Main-Class: package.classname inside the META-INF/MANIFEST.MF file.

As for how to do this in Netbeans - not sure off the top of my head - I usually use IntelliJ and / or Eclipse and usually build the JAR through ANT or Maven anyway.

PHP foreach loop through multidimensional array

<?php
$first = reset($arr_nav); // Get the first element
$last  = end($arr_nav);   // Get the last element
// Ensure that we have a first element and that it's an array
if(is_array($first)) { 
   $first['class'] = 'first';
}
// Ensure we have a last element and that it differs from the first
if(is_array($last) && $last !== $first) {
   $last['class'] = 'last';
}

Now you could just echo the class inside you html-generator. Would probably need some kind of check to ensure that the class is set, or provide a default empty class to the array.

What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

At http://www.youtube.com/watch?v=a9xAKttWgP4 you can watch Conway's Game Of Life programmed (and simultaneously verbally commented) in about 5 lines of APL (A Programming Language).

It's fun to watch and can inspire students that programming is cool, and math, and mathematical, concise programming languages :)

BTW, Uncle Bob Martin mentioned this youtube video on a hanselminutes podcast.

Order a MySQL table by two columns

The following will order your data depending on both column in descending order.

ORDER BY article_rating DESC, article_time DESC

What good technology podcasts are out there?

My list is pretty similar to the rest - TWIT, MBW, .NET Rocks, Hanselminutes, Polymorphic Podcast and specifically for Mac developers the Mac developer network has some a couple of good podcasts

iPhone is not available. Please reconnect the device

Going to Window ? Devices and Simulators will give you a better idea of what's going on. In my case, I had to update the iPhone since Xcode updated overnight and stopped supporting my iPhone.

Enter image description here

Replace an element into a specific position of a vector

vec1[i] = vec2[i]

will set the value of vec1[i] to the value of vec2[i]. Nothing is inserted. Your second approach is almost correct. Instead of +i+1 you need just +i

v1.insert(v1.begin()+i, v2[i])

How to split a string in Java

Use:

String[] result = yourString.split("-");
if (result.length != 2) 
     throw new IllegalArgumentException("String not in correct format");

This will split your string into two parts. The first element in the array will be the part containing the stuff before the -, and the second element in the array will contain the part of your string after the -.

If the array length is not 2, then the string was not in the format: string-string.

Check out the split() method in the String class.

jQuery select child element by class with unknown path

Try this

$('#thisElement .classToSelect').each(function(i){
         // do stuff
});

Hope it will help

iOS: present view controller programmatically

If you are using Storyboard and your "add" viewController is in storyboard then set an identifier for your "add" viewcontroller in settings so you can do something like this:

UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"NameOfYourStoryBoard" 
                                                     bundle:nil];
AddTaskViewController *add = 
           [storyboard instantiateViewControllerWithIdentifier:@"viewControllerIdentifier"];

[self presentViewController:add 
                   animated:YES 
                 completion:nil];

if you do not have your "add" viewController in storyboard or a nib file and want to create the whole thing programmaticaly then appDocs says:

If you cannot define your views in a storyboard or a nib file, override the loadView method to manually instantiate a view hierarchy and assign it to the view property.

Syntax error near unexpected token 'fi'

Use Notepad ++ and use the option to Convert the file to UNIX format. That should solve this problem.

Spring MVC - How to get all request params in a map in Spring controller?

Here is the simple example of getting request params in a Map.

 @RequestMapping(value="submitForm.html", method=RequestMethod.POST)
     public ModelAndView submitForm(@RequestParam Map<String, String> reqParam) 
       {
          String name  = reqParam.get("studentName");
          String email = reqParam.get("studentEmail");

          ModelAndView model = new ModelAndView("AdmissionSuccess");
          model.addObject("msg", "Details submitted by you::
          Name: " + name + ", Email: " + email );
       }

In this case, it will bind the value of studentName and studentEmail with name and email variables respectively.

How do I read text from the clipboard?

The python standard library does it...

try:
    # Python3
    import tkinter as tk
except ImportError:
    # Python2
    import Tkinter as tk

def getClipboardText():
    root = tk.Tk()
    # keep the window from showing
    root.withdraw()
    return root.clipboard_get()

What is the facade design pattern?

A design pattern is a common way of solving a recurring problem. Classes in all design patterns are just normal classes. What is important is how they are structured and how they work together to solve a given problem in the best possible way.

The Facade design pattern simplifies the interface to a complex system; because it is usually composed of all the classes which make up the subsystems of the complex system.

A Facade shields the user from the complex details of the system and provides them with a simplified view of it which is easy to use. It also decouples the code that uses the system from the details of the subsystems, making it easier to modify the system later.

http://www.dofactory.com/Patterns/PatternFacade.aspx

http://www.blackwasp.co.uk/Facade.aspx

Also, what is important while learning design patterns is to be able to recognize which pattern fits your given problem and then using it appropriately. It is a very common thing to misuse a pattern or trying to fit it to some problem just because you know it. Be aware of those pitfalls while learning\using design patterns.

What causes imported Maven project in Eclipse to use Java 1.5 instead of Java 1.6 by default and how can I ensure it doesn't?

Simplest solution in Springboot

I'll give you the simplest one if you use Springboot:

<properties>
  <java.version>1.8</java.version>
</properties>

Then, right click on your Eclipse project: Maven > Update project > Update project configuration from pom.xml

That should do.

Rename multiple files in a directory in Python

Use os.rename(src, dst) to rename or move a file or a directory.

$ ls
cheese_cheese_type.bar  cheese_cheese_type.foo
$ python
>>> import os
>>> for filename in os.listdir("."):
...  if filename.startswith("cheese_"):
...    os.rename(filename, filename[7:])
... 
>>> 
$ ls
cheese_type.bar  cheese_type.foo

How to see data from .RData file?

I think the problem is that you load isfar data.frame but you overwrite it by value returned by load.

Try either:

load("C:/Users/isfar.RData") 
head(isfar)

Or more general way

load("C:/Users/isfar.RData", ex <- new.env())
ls.str(ex) 

Finding the index of an item in a list

And now, for something completely different...

... like confirming the existence of the item before getting the index. The nice thing about this approach is the function always returns a list of indices -- even if it is an empty list. It works with strings as well.

def indices(l, val):
    """Always returns a list containing the indices of val in the_list"""
    retval = []
    last = 0
    while val in l[last:]:
            i = l[last:].index(val)
            retval.append(last + i)
            last += i + 1   
    return retval

l = ['bar','foo','bar','baz','bar','bar']
q = 'bar'
print indices(l,q)
print indices(l,'bat')
print indices('abcdaababb','a')

When pasted into an interactive python window:

Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def indices(the_list, val):
...     """Always returns a list containing the indices of val in the_list"""
...     retval = []
...     last = 0
...     while val in the_list[last:]:
...             i = the_list[last:].index(val)
...             retval.append(last + i)
...             last += i + 1   
...     return retval
... 
>>> l = ['bar','foo','bar','baz','bar','bar']
>>> q = 'bar'
>>> print indices(l,q)
[0, 2, 4, 5]
>>> print indices(l,'bat')
[]
>>> print indices('abcdaababb','a')
[0, 4, 5, 7]
>>> 

Update

After another year of heads-down python development, I'm a bit embarrassed by my original answer, so to set the record straight, one can certainly use the above code; however, the much more idiomatic way to get the same behavior would be to use list comprehension, along with the enumerate() function.

Something like this:

def indices(l, val):
    """Always returns a list containing the indices of val in the_list"""
    return [index for index, value in enumerate(l) if value == val]

l = ['bar','foo','bar','baz','bar','bar']
q = 'bar'
print indices(l,q)
print indices(l,'bat')
print indices('abcdaababb','a')

Which, when pasted into an interactive python window yields:

Python 2.7.14 |Anaconda, Inc.| (default, Dec  7 2017, 11:07:58) 
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def indices(l, val):
...     """Always returns a list containing the indices of val in the_list"""
...     return [index for index, value in enumerate(l) if value == val]
... 
>>> l = ['bar','foo','bar','baz','bar','bar']
>>> q = 'bar'
>>> print indices(l,q)
[0, 2, 4, 5]
>>> print indices(l,'bat')
[]
>>> print indices('abcdaababb','a')
[0, 4, 5, 7]
>>> 

And now, after reviewing this question and all the answers, I realize that this is exactly what FMc suggested in his earlier answer. At the time I originally answered this question, I didn't even see that answer, because I didn't understand it. I hope that my somewhat more verbose example will aid understanding.

If the single line of code above still doesn't make sense to you, I highly recommend you Google 'python list comprehension' and take a few minutes to familiarize yourself. It's just one of the many powerful features that make it a joy to use Python to develop code.

How to connect to my http://localhost web server from Android Emulator

Try http://10.0.2.2:8080/ where 8080 is your port number. It worked perfectly. If you just try 10.0.2.2 it won't work. You need to add port number to it. Also if Microsoft IIS has been installed try turning off that feature from control panel (if using any windows os) and then try as given above.

Circle button css

Here is a flat design circle button:

enter image description here

_x000D_
_x000D_
.btn {_x000D_
  height: 80px;_x000D_
  line-height: 80px;  _x000D_
  width: 80px;  _x000D_
  font-size: 2em;_x000D_
  font-weight: bold;_x000D_
  border-radius: 50%;_x000D_
  background-color: #4CAF50;_x000D_
  color: white;_x000D_
  text-align: center;_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<div class="btn">+</div>
_x000D_
_x000D_
_x000D_

but the problem is that the + might not be perfectly centered vertically in all browsers / platforms, because of font differences... see also this question (and its answer): Vertical alignement of span inside a div when the font-size is big

Adding delay between execution of two following lines

I have a couple of turn-based games where I need the AI to pause before taking its turn (and between steps in its turn). I'm sure there are other, more useful, situations where a delay is the best solution. In Swift:

        let delay = 2.0 * Double(NSEC_PER_SEC) 
        let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) 
        dispatch_after(time, dispatch_get_main_queue()) { self.playerTapped(aiPlayView) }

I just came back here to see if the Objective-C calls were different.(I need to add this to that one, too.)

Bind TextBox on Enter-key press

Here is an approach that to me seems quite straightforward, and easier that adding an AttachedBehaviour (which is also a valid solution). We use the default UpdateSourceTrigger (LostFocus for TextBox), and then add an InputBinding to the Enter Key, bound to a command.

The xaml is as follows

       <TextBox Grid.Row="0" Text="{Binding Txt1}" Height="30" Width="150">
        <TextBox.InputBindings>
            <KeyBinding Gesture="Enter" 
                        Command="{Binding UpdateText1Command}"
                        CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type TextBox}},Path=Text}" />
        </TextBox.InputBindings>
    </TextBox>

Then the Command methods are

Private Function CanExecuteUpdateText1(ByVal param As Object) As Boolean
    Return True
End Function
Private Sub ExecuteUpdateText1(ByVal param As Object)

    If TypeOf param Is String Then
        Txt1 = CType(param, String)
    End If
End Sub

And the TextBox is bound to the Property

 Public Property Txt1 As String
    Get
        Return _txt1
    End Get
    Set(value As String)
        _txt1 = value
        OnPropertyChanged("Txt1")
    End Set
End Property

So far this seems to work well and catches the Enter Key event in the TextBox.

PHP: How to get referrer URL?

$_SERVER['HTTP_REFERER'] will give you the referrer page's URL if there exists any. If users use a bookmark or directly visit your site by manually typing in the URL, http_referer will be empty. Also if the users are posting to your page programatically (CURL) then they're not obliged to set the http_referer as well. You're missing all _, is that a typo?

Web colors in an Android color xml resource file

You have to create the colors.xml file in the res/values folder of your project. The code of colors.xml is

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <color name="orange">#ff5500</color>
 <color name="white">#ffffff</color>
 <color name="transparent">#00000000</color>
 <color name="date_color">#999999</color>
 <color name="black">#000000</color>
 <color name="gray">#999999</color>
 <color name="blue">#0066cc</color>
 <color name="gold">#e6b121</color>
 <color name="blueback">#99FFFF</color>
 <color name="articlecolor">#3399FF</color> 
 <color name="article_title">#3399FF</color> 
 <color name="cachecolor">#8ad0e8</color>
</resources>

Or, you can use Colors in your application by following way

android.graphics.Color.TRANSPARENT;

Similarly

android.graphics.Color.RED;

Why can't non-default arguments follow default arguments?

Required arguments (the ones without defaults), must be at the start to allow client code to only supply two. If the optional arguments were at the start, it would be confusing:

fun1("who is who", 3, "jack")

What would that do in your first example? In the last, x is "who is who", y is 3 and a = "jack".

Is there a job scheduler library for node.js?

later.js is a pretty good JavaScript "scheduler" library. Can run on Node.js or in a web browser.

Should I use PATCH or PUT in my REST API?

I would generally prefer something a bit simpler, like activate/deactivate sub-resource (linked by a Link header with rel=service).

POST /groups/api/v1/groups/{group id}/activate

or

POST /groups/api/v1/groups/{group id}/deactivate

For the consumer, this interface is dead-simple, and it follows REST principles without bogging you down in conceptualizing "activations" as individual resources.

Echo a blank (empty) line to the console from a Windows batch file

Note: Though my original answer attracted several upvotes, I decided that I could do much better. You can find my original (simplistic and misguided) answer in the edit history.

If Microsoft had the intent of providing a means of outputting a blank line from cmd.exe, Microsoft surely would have documented such a simple operation. It is this omission that motivated me to ask this question.

So, because a means for outputting a blank line from cmd.exe is not documented, arguably one should consider any suggestion for how to accomplish this to be a hack. That means that there is no known method for outputting a blank line from cmd.exe that is guaranteed to work (or work efficiently) in all situations.

With that in mind, here is a discussion of methods that have been recommended for outputting a blank line from cmd.exe. All recommendations are based on variations of the echo command.


echo.

While this will work in many if not most situations, it should be avoided because it is slower than its alternatives and actually can fail (see here, here, and here). Specifically, cmd.exe first searches for a file named echo and tries to start it. If a file named echo happens to exist in the current working directory, echo. will fail with:

'echo.' is not recognized as an internal or external command,
operable program or batch file.

echo:
echo\

At the end of this answer, the author argues that these commands can be slow, for instance if they are executed from a network drive location. A specific reason for the potential slowness is not given. But one can infer that it may have something to do with accessing the file system. (Perhaps because : and \ have special meaning in a Windows file system path?)

However, some may consider these to be safe options since : and \ cannot appear in a file name. For that or another reason, echo: is recommended by SS64.com here.


echo(
echo+
echo,
echo/
echo;
echo=
echo[
echo]

This lengthy discussion includes what I believe to be all of these. Several of these options are recommended in this SO answer as well. Within the cited discussion, this post ends with what appears to be a recommendation for echo( and echo:.

My question at the top of this page does not specify a version of Windows. My experimentation on Windows 10 indicates that all of these produce a blank line, regardless of whether files named echo, echo+, echo,, ..., echo] exist in the current working directory. (Note that my question predates the release of Windows 10. So I concede the possibility that older versions of Windows may behave differently.)

In this answer, @jeb asserts that echo( always works. To me, @jeb's answer implies that other options are less reliable but does not provide any detail as to why that might be. Note that @jeb contributed much valuable content to other references I have cited in this answer.


Conclusion: Do not use echo.. Of the many other options I encountered in the sources I have cited, the support for these two appears most authoritative:

echo(
echo:

But I have not found any strong evidence that the use of either of these will always be trouble-free.


Example Usage:

@echo off
echo Here is the first line.
echo(
echo There is a blank line above this line.

Expected output:

Here is the first line.

There is a blank line above this line.

What is Func, how and when is it used

Func<T1,R> and the other predefined generic Func delegates (Func<T1,T2,R>, Func<T1,T2,T3,R> and others) are generic delegates that return the type of the last generic parameter.

If you have a function that needs to return different types, depending on the parameters, you can use a Func delegate, specifying the return type.

SELECT list is not in GROUP BY clause and contains nonaggregated column

As @Brian Riley already said you should either remove 1 column in your select

select countrylanguage.language ,sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language
order by sum(country.population*countrylanguage.percentage) desc ;

or add it to your grouping

select countrylanguage.language, country.code, sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language, country.code
order by sum(country.population*countrylanguage.percentage) desc ;

Python != operation vs "is not"

Consider the following:

class Bad(object):
    def __eq__(self, other):
        return True

c = Bad()
c is None # False, equivalent to id(c) == id(None)
c == None # True, equivalent to c.__eq__(None)

Insert multiple rows with one query MySQL

If you would like to insert multiple values lets say from multiple inputs that have different post values but the same table to insert into then simply use:

mysql_query("INSERT INTO `table` (a,b,c,d,e,f,g) VALUES 
('$a','$b','$c','$d','$e','$f','$g'),
('$a','$b','$c','$d','$e','$f','$g'),
('$a','$b','$c','$d','$e','$f','$g')")
or die (mysql_error()); // Inserts 3 times in 3 different rows

C# LINQ select from list

In likeness of how I found this question using Google, I wanted to take it one step further. Lets say I have a string[] states and a db Entity of StateCounties and I just want the states from the list returned and not all of the StateCounties.

I would write:

db.StateCounties.Where(x => states.Any(s => x.State.Equals(s))).ToList();

I found this within the sample of CheckBoxList for nu-get.

git with IntelliJ IDEA: Could not read from remote repository

Adding this answer since none of the answers worked for me.

I had certificates issue - so following command did the trick.

git config --global http.sslVerify false

taken from https://confluence.atlassian.com/fishkb/unable-to-clone-git-repository-due-to-self-signed-certificate-376838977.html

Open source face recognition for Android

You can try Microsoft's Face API. It can detect and identify people. learn more about face API here.

Add image in title bar

you should be searching about how to add favicon.ico . You can try adding favicon.ico directly in your html pages like this

<link rel="shortcut icon" href="/favicon.png" type="image/png">
<link rel="shortcut icon" type="image/png" href="http://www.example.com/favicon.png" />

Or you can update that in your webserver. It is advised to add in your webserver as you don't need to add this in each of your html pages (assuming no includes).

To add in your apache place the favicon.ico in your root website director and add this in httpd.conf

AddType image/x-icon .ico

no default constructor exists for class

Because you have this:

Blowfish(BlowfishAlgorithm algorithm);

It's not a default constructor. The default constructor is one which takes no parameters. i.e.

Blowfish();

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

I like the WMILinq solution. While not exactly the solution to your problem, find below a taste of it :

using (WmiContext context = new WmiContext(@"\\.")) {

  context.ManagementScope.Options.Impersonation = ImpersonationLevel.Impersonate;
  context.Log = Console.Out;

  var dnss = from nic in context.Source<Win32_NetworkAdapterConfiguration>()
          where nic.IPEnabled
          select nic;

  var ips = from s in dnss.SelectMany(dns => dns.DNSServerSearchOrder)
          select IPAddress.Parse(s);
}  

http://www.codeplex.com/linq2wmi

Generics in C#, using type of a variable as parameter

The point about generics is to give compile-time type safety - which means that types need to be known at compile-time.

You can call generic methods with types only known at execution time, but you have to use reflection:

// For non-public methods, you'll need to specify binding flags too
MethodInfo method = GetType().GetMethod("DoesEntityExist")
                             .MakeGenericMethod(new Type[] { t });
method.Invoke(this, new object[] { entityGuid, transaction });

Ick.

Can you make your calling method generic instead, and pass in your type parameter as the type argument, pushing the decision one level higher up the stack?

If you could give us more information about what you're doing, that would help. Sometimes you may need to use reflection as above, but if you pick the right point to do it, you can make sure you only need to do it once, and let everything below that point use the type parameter in a normal way.

In Java, remove empty elements from a list of Strings

lukastymo's answer seems the best one.

But it may be worth mentioning this approach as well for it's extensibility:

List<String> list = new ArrayList<String>(Arrays.asList("", "Hi", null, "How", "are"));

list = list.stream()
           .filter(item -> item != null && !item.isEmpty())
           .collect(Collectors.toList());

System.out.println(list);

What I mean by that is you could then add additional filters, such as:

          .filter(item -> !item.startsWith("a"))

... although of course that's not specifically relevant to the question.

How do I query for all dates greater than a certain date in SQL Server?

DateTime start1 = DateTime.Parse(txtDate.Text);

SELECT * 
FROM dbo.March2010 A
WHERE A.Date >= start1;

First convert TexBox into the Datetime then....use that variable into the Query

Python - Dimension of Data Frame

Summary of all ways to get info on dimensions of DataFrame or Series

There are a number of ways to get information on the attributes of your DataFrame or Series.

Create Sample DataFrame and Series

df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df

     a  b
0  5.0  9
1  2.0  2
2  NaN  4

s = df['a']
s

0    5.0
1    2.0
2    NaN
Name: a, dtype: float64

shape Attribute

The shape attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.

df.shape
(3, 2)

s.shape
(3,)

len function

To get the number of rows of a DataFrame or get the length of a Series, use the len function. An integer will be returned.

len(df)
3

len(s)
3

size attribute

To get the total number of elements in the DataFrame or Series, use the size attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len function:

df.size
6

s.size
3

ndim attribute

The ndim attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:

df.ndim
2

s.ndim
1

The tricky count method

The count method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.

df.count() # by default, get the count of each column

a    2
b    3
dtype: int64


df.count(axis='columns') # change direction to get count of each row

0    2
1    2
2    1
dtype: int64

For a Series, there is only one axis for computation and so it just returns a scalar:

s.count()
2

Use the info method for retrieving metadata

The info method returns the number of non-missing values and data types of each column

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a    2 non-null float64
b    3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes

Use of ~ (tilde) in R programming Language

The thing on the right of <- is a formula object. It is often used to denote a statistical model, where the thing on the left of the ~ is the response and the things on the right of the ~ are the explanatory variables. So in English you'd say something like "Species depends on Sepal Length, Sepal Width, Petal Length and Petal Width".

The myFormula <- part of that line stores the formula in an object called myFormula so you can use it in other parts of your R code.


Other common uses of formula objects in R

The lattice package uses them to specify the variables to plot.
The ggplot2 package uses them to specify panels for plotting.
The dplyr package uses them for non-standard evaulation.

How to preSelect an html dropdown list with php?

First of all give a name to your select. Then do:

<select name="my_select">
<option value="1" <?= ($_POST['my_select'] == "1")? "selected":"";?>>Yes</options>
<option value="2" <?= ($_POST['my_select'] == "2")? "selected":"";?>>No</options>
<option value="3" <?= ($_POST['my_select'] == "3")? "selected":"";?>>Fine</options>
</select>

What that does is check if what was selected is the same for each and when its found echo "selected".

Python map object is not subscriptable

In Python 3, map returns an iterable object of type map, and not a subscriptible list, which would allow you to write map[i]. To force a list result, write

payIntList = list(map(int,payList))

However, in many cases, you can write out your code way nicer by not using indices. For example, with list comprehensions:

payIntList = [pi + 1000 for pi in payList]
for pi in payIntList:
    print(pi)

How to escape "&" in XML?

'&' --> '&amp;'

'<' --> '&lt;'

'>' --> '&gt;'

Fastest way to count number of occurrences in a Python list

Combination of lambda and map function can also do the job:

list_ = ['a', 'b', 'b', 'c']
sum(map(lambda x: x=="b", list_))
:2

How to round up the result of integer division?

A generic method, whose result you can iterate over may be of interest:

public static Object[][] chunk(Object[] src, int chunkSize) {

    int overflow = src.length%chunkSize;
    int numChunks = (src.length/chunkSize) + (overflow>0?1:0);
    Object[][] dest = new Object[numChunks][];      
    for (int i=0; i<numChunks; i++) {
        dest[i] = new Object[ (i<numChunks-1 || overflow==0) ? chunkSize : overflow ];
        System.arraycopy(src, i*chunkSize, dest[i], 0, dest[i].length); 
    }
    return dest;
}

Do you have to put Task.Run in a method to make it async?

First, let's clear up some terminology: "asynchronous" (async) means that it may yield control back to the calling thread before it starts. In an async method, those "yield" points are await expressions.

This is very different than the term "asynchronous", as (mis)used by the MSDN documentation for years to mean "executes on a background thread".

To futher confuse the issue, async is very different than "awaitable"; there are some async methods whose return types are not awaitable, and many methods returning awaitable types that are not async.

Enough about what they aren't; here's what they are:

  • The async keyword allows an asynchronous method (that is, it allows await expressions). async methods may return Task, Task<T>, or (if you must) void.
  • Any type that follows a certain pattern can be awaitable. The most common awaitable types are Task and Task<T>.

So, if we reformulate your question to "how can I run an operation on a background thread in a way that it's awaitable", the answer is to use Task.Run:

private Task<int> DoWorkAsync() // No async because the method does not need await
{
  return Task.Run(() =>
  {
    return 1 + 2;
  });
}

(But this pattern is a poor approach; see below).

But if your question is "how do I create an async method that can yield back to its caller instead of blocking", the answer is to declare the method async and use await for its "yielding" points:

private async Task<int> GetWebPageHtmlSizeAsync()
{
  var client = new HttpClient();
  var html = await client.GetAsync("http://www.example.com/");
  return html.Length;
}

So, the basic pattern of things is to have async code depend on "awaitables" in its await expressions. These "awaitables" can be other async methods or just regular methods returning awaitables. Regular methods returning Task/Task<T> can use Task.Run to execute code on a background thread, or (more commonly) they can use TaskCompletionSource<T> or one of its shortcuts (TaskFactory.FromAsync, Task.FromResult, etc). I don't recommend wrapping an entire method in Task.Run; synchronous methods should have synchronous signatures, and it should be left up to the consumer whether it should be wrapped in a Task.Run:

private int DoWork()
{
  return 1 + 2;
}

private void MoreSynchronousProcessing()
{
  // Execute it directly (synchronously), since we are also a synchronous method.
  var result = DoWork();
  ...
}

private async Task DoVariousThingsFromTheUIThreadAsync()
{
  // I have a bunch of async work to do, and I am executed on the UI thread.
  var result = await Task.Run(() => DoWork());
  ...
}

I have an async/await intro on my blog; at the end are some good followup resources. The MSDN docs for async are unusually good, too.

Return the characters after Nth character in a string

Alternately, you could do a Text to Columns with space as the delimiter.

How to check if a variable is set in Bash?

While most of the techniques stated here are correct, bash 4.2 supports an actual test for the presence of a variable (man bash), rather than testing the value of the variable.

[[ -v foo ]]; echo $?
# 1

foo=bar
[[ -v foo ]]; echo $?
# 0

foo=""
[[ -v foo ]]; echo $?
# 0

Notably, this approach will not cause an error when used to check for an unset variable in set -u / set -o nounset mode, unlike many other approaches, such as using [ -z.

Flutter: Run method on Widget build complete

There are 3 possible ways:

1) WidgetsBinding.instance.addPostFrameCallback((_) => yourFunc(context));

2) Future.delayed(Duration.zero, () => yourFunc(context));

3) Timer.run(() => yourFunc(context));

As for context, I needed it for use in Scaffold.of(context) after all my widgets were rendered.

But in my humble opinion, the best way to do it is this:

void main() async {
  WidgetsFlutterBinding.ensureInitialized(); //all widgets are rendered here
  await yourFunc();
  runApp( MyApp() );
}

Git Clone: Just the files, please?

The git command that would be the closest from what you are looking for would by git archive.
See backing up project which uses git: it will include in an archive all files (including submodules if you are using the git-archive-all script)

You can then use that archive anywhere, giving you back only files, no .git directory.

git archive --remote=<repository URL> | tar -t

If you need folders and files just from the first level:

git archive --remote=<repository URL> | tar -t --exclude="*/*"

To list only first-level folders of a remote repo:

git archive --remote=<repository URL> | tar -t --exclude="*/*" | grep "/"

Note: that does not work for GitHub (not supported)

So you would need to clone (shallow to quicken the clone step), and then archive locally:

git clone --depth=1 [email protected]:xxx/yyy.git
cd yyy
git archive --format=tar aTag -o aTag.tar

Another option would be to do a shallow clone (as mentioned below), but locating the .git folder elsewhere.

git --git-dir=/path/to/another/folder.git clone --depth=1 /url/to/repo

The repo folder would include only the file, without .git.

Note: git --git-dir is an option of the command git, not git clone.


Update with Git 2.14.X/2.15 (Q4 2017): it will make sure to avoid adding empty folders.

"git archive", especially when used with pathspec, stored an empty directory in its output, even though Git itself never does so.
This has been fixed.

See commit 4318094 (12 Sep 2017) by René Scharfe (``).
Suggested-by: Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 62b1cb7, 25 Sep 2017)

archive: don't add empty directories to archives

While git doesn't track empty directories, git archive can be tricked into putting some into archives.
While that is supported by the object database, it can't be represented in the index and thus it's unlikely to occur in the wild.

As empty directories are not supported by git, they should also not be written into archives.
If an empty directory is really needed then it can be tracked and archived by placing an empty .gitignore file in it.

What underlies this JavaScript idiom: var self = this?

function Person(firstname, lastname) {
  this.firstname = firstname;

  this.lastname = lastname;
  this.getfullname = function () {
    return `${this.firstname}   ${this.lastname}`;
  };

  let that = this;
  this.sayHi = function() {
    console.log(`i am this , ${this.firstname}`);
    console.log(`i am that , ${that.firstname}`);
  };
}

let thisss = new Person('thatbetty', 'thatzhao');

let thatt = {firstname: 'thisbetty', lastname: 'thiszhao'};

thisss.sayHi.call(thatt);

How to limit the number of dropzone.js files uploaded?

I'd like to point out. maybe this just happens to me, HOWEVER, when I use this.removeAllFiles() in dropzone, it fires the event COMPLETE and this blows, what I did was check if the fileData was empty or not so I could actually submit the form.

unique() for more than one variable

There are a few ways to get all unique combinations of a set of factors.

with(df, interaction(yad, per, drop=TRUE))   # gives labels
with(df, yad:per)                            # ditto

aggregate(numeric(nrow(df)), df[c("yad", "per")], length)    # gives a data frame

Design Android EditText to show error message as described by google

Your EditText should be wrapped in a TextInputLayout

<android.support.design.widget.TextInputLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tilEmail">

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:id="@+id/etEmail"
        android:hint="Email"
        android:layout_marginTop="10dp"
        />

</android.support.design.widget.TextInputLayout>

To get an error message like you wanted, set error to TextInputLayout

TextInputLayout tilEmail = (TextInputLayout) findViewById(R.id.tilEmail);
if (error){
    tilEmail.setError("Invalid email id");    
}

You should add design support library dependency. Add this line in your gradle dependencies

compile 'com.android.support:design:22.2.0'

Reset ID autoincrement ? phpmyadmin

ALTER TABLE `table_name` AUTO_INCREMENT=1

Index of Currently Selected Row in DataGridView

Use the Index property in your DGV's SelectedRows collection:

int index = yourDGV.SelectedRows[0].Index;

jQuery exclude elements with certain class in selector

To add some info that helped me today, a jQuery object/this can also be passed in to the .not() selector.

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $(".navitem").click(function(){_x000D_
        $(".navitem").removeClass("active");_x000D_
        $(".navitem").not($(this)).addClass("active");_x000D_
    });_x000D_
});
_x000D_
.navitem_x000D_
{_x000D_
    width: 100px;_x000D_
    background: red;_x000D_
    color: white;_x000D_
    display: inline-block;_x000D_
    position: relative;_x000D_
    text-align: center;_x000D_
}_x000D_
.navitem.active_x000D_
{_x000D_
    background:green;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="navitem">Home</div>_x000D_
<div class="navitem">About</div>_x000D_
<div class="navitem">Pricing</div>
_x000D_
_x000D_
_x000D_

The above example can be simplified, but wanted to show the usage of this in the not() selector.

How to override the path of PHP to use the MAMP path?

If you have to type

/Applications/MAMP/bin/php5.3/bin/php

in your command line then add

/Applications/MAMP/bin/php5.3/bin

to your PATH to be able to call php from anywhere.

How do I choose the URL for my Spring Boot webapp?

The issue of changing the context path of a Spring application is handled very well in the post titled Spring Boot Change Context Path

Basically the post discusses multiple ways of realizing this viz.

  1. Java Config
  2. Command Line Arguments
  3. Java System Properties
  4. OS Environment Variables
  5. application.properties in Current Directory
  6. application.properties in the classpath (src/main/resources or the packaged jar file)

Force table column widths to always be fixed regardless of contents

You can also work with "overflow: hidden" or "overflow-x: hidden" (for just the width). This requires a defined width (and/or height?) and maybe a "display: block" as well.

"Overflow:Hidden" hides the whole content, which does not fit into the defined box.

Example:

http://jsfiddle.net/NAJvp/

HTML:

<table border="1">
    <tr>
        <td><div>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</div></td>
        <td>bbb</td>
        <td>cccc</td>
    </tr>
</table>

CSS:

td div { width: 100px; overflow-y: hidden; }

EDIT: Shame on me, I've seen, you already use "overflow". I guess it doesn't work, because you don't set "display: block" to your element ...

Schedule automatic daily upload with FileZilla

FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.

Some references:


Though you can use any other client that allows automation.

You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).

Combine WinSCP scripting capabilities with Windows Scheduler:

A typical WinSCP script for upload (with SFTP) looks like:

open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close

With FTP, just replace the sftp:// with the ftp:// and remove the -hostkey="..." switch.


Similarly for download: How to schedule an automatic FTP download on Windows?


WinSCP can even generate a script from an imported FileZilla session.

For details, see the guide to FileZilla automation.

(I'm the author of WinSCP)


Another option, if you are using SFTP, is the psftp.exe client from PuTTY suite.

Calculating Pearson correlation and significance in Python

Rather than rely on numpy/scipy, I think my answer should be the easiest to code and understand the steps in calculating the Pearson Correlation Coefficient (PCC) .

import math

# calculates the mean
def mean(x):
    sum = 0.0
    for i in x:
         sum += i
    return sum / len(x) 

# calculates the sample standard deviation
def sampleStandardDeviation(x):
    sumv = 0.0
    for i in x:
         sumv += (i - mean(x))**2
    return math.sqrt(sumv/(len(x)-1))

# calculates the PCC using both the 2 functions above
def pearson(x,y):
    scorex = []
    scorey = []

    for i in x: 
        scorex.append((i - mean(x))/sampleStandardDeviation(x)) 

    for j in y:
        scorey.append((j - mean(y))/sampleStandardDeviation(y))

# multiplies both lists together into 1 list (hence zip) and sums the whole list   
    return (sum([i*j for i,j in zip(scorex,scorey)]))/(len(x)-1)

The significance of PCC is basically to show you how strongly correlated the two variables/lists are. It is important to note that the PCC value ranges from -1 to 1. A value between 0 to 1 denotes a positive correlation. Value of 0 = highest variation (no correlation whatsoever). A value between -1 to 0 denotes a negative correlation.

Plot multiple columns on the same graph in R

Using tidyverse

df %>% tidyr::gather("id", "value", 1:4) %>% 
  ggplot(., aes(Xax, value))+
  geom_point()+
  geom_smooth(method = "lm", se=FALSE, color="black")+
  facet_wrap(~id)

DATA

df<- read.table(text =c("
A       B       C       G       Xax
0.451   0.333   0.034   0.173   0.22        
0.491   0.270   0.033   0.207   0.34    
0.389   0.249   0.084   0.271   0.54    
0.425   0.819   0.077   0.281   0.34
0.457   0.429   0.053   0.386   0.53    
0.436   0.524   0.049   0.249   0.12    
0.423   0.270   0.093   0.279   0.61    
0.463   0.315   0.019   0.204   0.23"), header = T)

Trusting all certificates using HttpClient over HTTPS

I'm adding a response for those that use the httpclient-4.5, and probably works for 4.4 as well.

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.fluent.ContentResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;



public class HttpClientUtils{

public static HttpClient getHttpClientWithoutSslValidation_UsingHttpClient_4_5_2() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), new NoopHostnameVerifier());
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); 
        return httpclient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
}

Unable to merge dex

I also had the problem.

I was able to solve by changing compileSdkVersion and targetSdkVersion to latest version.

postgres, ubuntu how to restart service on startup? get stuck on clustering after instance reboot

I guess it would be best to fix the database startup script itself. But as a work around, you can add that line to /etc/rc.local, which is executed about last in init phase.

How to use executables from a package installed locally in node_modules?

Add this script to your .bashrc. Then you can call coffee or anyhting locally. This is handy for your laptop, but don't use it on your server.

DEFAULT_PATH=$PATH;

add_local_node_modules_to_path(){
  NODE_MODULES='./node_modules/.bin';
  if [ -d $NODE_MODULES ]; then
    PATH=$DEFAULT_PATH:$NODE_MODULES;
  else
    PATH=$DEFAULT_PATH;
  fi
}

cd () {
  builtin cd "$@";
  add_local_node_modules_to_path;
}

add_local_node_modules_to_path;

note: this script makes aliase of cd command, and after each call of cd it checks node_modules/.bin and add it to your $PATH.

note2: you can change the third line to NODE_MODULES=$(npm bin);. But that would make cd command too slow.

pandas dataframe columns scaling with sklearn

I am not sure if previous versions of pandas prevented this but now the following snippet works perfectly for me and produces exactly what you want without having to use apply

>>> import pandas as pd
>>> from sklearn.preprocessing import MinMaxScaler


>>> scaler = MinMaxScaler()

>>> dfTest = pd.DataFrame({'A':[14.00,90.20,90.95,96.27,91.21],
                           'B':[103.02,107.26,110.35,114.23,114.68],
                           'C':['big','small','big','small','small']})

>>> dfTest[['A', 'B']] = scaler.fit_transform(dfTest[['A', 'B']])

>>> dfTest
          A         B      C
0  0.000000  0.000000    big
1  0.926219  0.363636  small
2  0.935335  0.628645    big
3  1.000000  0.961407  small
4  0.938495  1.000000  small

Android Studio installation on Windows 7 fails, no JDK found

I got the problem that the installation stopped by "$(^name) has stopped working" error. I have installed Java SE Development kit already, also set both SDK_HOME and JAVA_HOME that point to "C:\Program Files\Java\jdk1.7.0_21\"

My laptop installed with Windows 7 64 bits

So I tried to install the 32 bit version of Java SE Developement kit, set my JAVA_HOME to "C:\Program Files (x86)\Java\jdk1.7.0_21", restart and the installation worked OK.

Nested ifelse statement

Try something like the following:

# some sample data
idnat <- sample(c("french","foreigner"),100,TRUE)
idbp <- rep(NA,100)
idbp[idnat=="french"] <- sample(c("mainland","overseas","colony"),sum(idnat=="french"),TRUE)

# recoding
out <- ifelse(idnat=="french" & !idbp %in% c("overseas","colony"), "mainland",
              ifelse(idbp %in% c("overseas","colony"),"overseas",
                     "foreigner"))
cbind(idnat,idbp,out) # check result

Your confusion comes from how SAS and R handle if-else constructions. In R, if and else are not vectorized, meaning they check whether a single condition is true (i.e., if("french"=="french") works) and cannot handle multiple logicals (i.e., if(c("french","foreigner")=="french") doesn't work) and R gives you the warning you're receiving.

By contrast, ifelse is vectorized, so it can take your vectors (aka input variables) and test the logical condition on each of their elements, like you're used to in SAS. An alternative way to wrap your head around this would be to build a loop using if and else statements (as you've started to do here) but the vectorized ifelse approach will be more efficient and involve generally less code.

How to add elements of a string array to a string array list?

Arrays.asList() method simply returns List type

char [] arr = { 'c','a','t'};    
ArrayList<Character> chars = new ArrayList<Character>();

To add the array into the list, first convert it to list and then call addAll

List arrList = Arrays.asList(arr);
chars.addAll(arrList);

The following line will cause compiler error

chars.addAll(Arrays.asList(arr));

How to check if the URL contains a given string?

Easier it gets

<script type="text/javascript">
$(document).ready(function () {
    var url = window.location.href;
    if(url.includes('franky'))    //includes() method determines whether a string contains specified string.
    {
         alert("url contains franky");
    }
});
</script>

Calling filter returns <filter object at ... >

It looks like you're using python 3.x. In python3, filter, map, zip, etc return an object which is iterable, but not a list. In other words,

filter(func,data) #python 2.x

is equivalent to:

list(filter(func,data)) #python 3.x

I think it was changed because you (often) want to do the filtering in a lazy sense -- You don't need to consume all of the memory to create a list up front, as long as the iterator returns the same thing a list would during iteration.

If you're familiar with list comprehensions and generator expressions, the above filter is now (almost) equivalent to the following in python3.x:

( x for x in data if func(x) ) 

As opposed to:

[ x for x in data if func(x) ]

in python 2.x

WinError 2 The system cannot find the file specified (Python)

I believe you need to .f file as a parameter, not as a command-single-string. same with the "--domain "+i, which i would split in two elements of the list. Assuming that:

  • you have the path set for FORTRAN executable,
  • the ~/ is indeed the correct way for the FORTRAN executable

I would change this line:

subprocess.Popen(["FORTRAN ~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain "+i])

to

subprocess.Popen(["FORTRAN", "~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain", i])

If that doesn't work, you should do a os.path.exists() for the .f file, and check that you can launch the FORTRAN executable without any path, and set the path or system path variable accordingly

[EDIT 6-Mar-2017]

As the exception, detailed in the original post, is a python exception from subprocess; it is likely that the WinError 2 is because it cannot find FORTRAN

I highly suggest that you specify full path for your executable:

for i in input:
    exe = r'c:\somedir\fortrandir\fortran.exe'
    fortran_script = r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f'
    subprocess.Popen([exe, fortran_script, "--domain", i])

if you need to convert the forward-slashes to backward-slashes, as suggested in one of the comments, you can do this:

for i in input:
    exe = os.path.normcase(r'c:\somedir\fortrandir\fortran.exe')
    fortran_script = os.path.normcase(r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
    i = os.path.normcase(i)
    subprocess.Popen([exe, fortran_script, "--domain", i])

[EDIT 7-Mar-2017]

The following line is incorrect:

exe = os.path.normcase(r'~/C:/Program Files (x86)/Silverfrost/ftn95.exe'

I am not sure why you have ~/ as a prefix for every path, don't do that.

for i in input:
    exe = os.path.normcase(r'C:/Program Files (x86)/Silverfrost/ftn95.exe'
    fortran_script = os.path.normcase(r'C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
    i = os.path.normcase(i)
    subprocess.Popen([exe, fortran_script, "--domain", i])

[2nd EDIT 7-Mar-2017]

I do not know this FORTRAN or ftn95.exe, does it need a shell to function properly?, in which case you need to launch as follows:

subprocess.Popen([exe, fortran_script, "--domain", i], shell = True)

You really need to try to launch the command manually from the working directory which your python script is operating from. Once you have the command which is actually working, then build up the subprocess command.

How to pass credentials to the Send-MailMessage command for sending emails

And here is a simple Send-MailMessage example with username/password for anyone looking for just that

$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("username", $secpasswd)
Send-MailMessage -SmtpServer mysmptp -Credential $cred -UseSsl -From '[email protected]' -To '[email protected]' -Subject 'TEST'

What is the string concatenation operator in Oracle?

There's also concat, but it doesn't get used much

select concat('a','b') from dual;

How do I programmatically set the value of a select box element using JavaScript?

Not answering the question, but you can also select by index, where i is the index of the item you wish to select:

var formObj = document.getElementById('myForm');
formObj.leaveCode[i].selected = true;

You can also loop through the items to select by display value with a loop:

for (var i = 0, len < formObj.leaveCode.length; i < len; i++) 
    if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;

Insert array into MySQL database with PHP

<?php
 function mysqli_insert_array($table, $data, $exclude = array()) {
    $con=  mysqli_connect("localhost", "root","","test");
     $fields = $values = array();
    if( !is_array($exclude) ) $exclude = array($exclude);
    foreach( array_keys($data) as $key ) {
        if( !in_array($key, $exclude) ) {
            $fields[] = "`$key`";
            $values[] = "'" . mysql_real_escape_string($data[$key]) . "'";
        }
    }
    $fields = implode(",", $fields);
    $values = implode(",", $values);
    if( mysqli_query($con,"INSERT INTO `$table` ($fields) VALUES ($values)") ) {
        return array( "mysql_error" => false,
                      "mysql_insert_id" => mysqli_insert_id($con),
                      "mysql_affected_rows" => mysqli_affected_rows($con),
                      "mysql_info" => mysqli_info($con)
                    );
    } else {
        return array( "mysql_error" => mysqli_error($con) );
    }
}

 $a['firstname']="abc";
 $a['last name']="xyz";
 $a['birthdate']="1993-09-12";
 $a['profilepic']="img.jpg";
 $a['gender']="male";
 $a['email']="[email protected]";
 $a['likechoclate']="Dm";
 $a['status']="1";
$result=mysqli_insert_array('registration',$a,'abc');
if( $result['mysql_error'] ) {
    echo "Query Failed: " . $result['mysql_error'];
} else {
    echo "Query Succeeded! <br />";
    echo "<pre>";
    print_r($result);
    echo "</pre>";
}
?>

String in function parameter

Inside the function parameter list, char arr[] is absolutely equivalent to char *arr, so the pair of definitions and the pair of declarations are equivalent.

void function(char arr[]) { ... }
void function(char *arr)  { ... }

void function(char arr[]);
void function(char *arr);

The issue is the calling context. You provided a string literal to the function; string literals may not be modified; your function attempted to modify the string literal it was given; your program invoked undefined behaviour and crashed. All completely kosher.

Treat string literals as if they were static const char literal[] = "string literal"; and do not attempt to modify them.

Inserting an image with PHP and FPDF

Please note that you should not use any png when you are testing this , first work with jpg .

$myImage = "images/logos/mylogo.jpg";  // this is where you get your Image

$pdf->Image($myImage, 5, $pdf->GetY(), 33.78);

How to change language settings in R

If you want to change R's language in terminal to English forever, this works fine for me in macOS:

Open terminal.app, and say:

touch .bash_profile

Then say:

open -a TextEdit.app .bash_profile

These two commands will help you open ".bash_profile" file in TextEdit.

Add this to ".bash_profile" file:

export LANG=en_US.UTF-8

Then save the file, reopen terminal and type R, you will find it's language has changed to english.

If you want language come back to it's original, just simply add a # before export LANG=en_US.UTF-8.

How is attr_accessible used in Rails 4?

1) Update Devise so that it can handle Rails 4.0 by adding this line to your application's Gemfile:

gem 'devise', '3.0.0.rc' 

Then execute:

$ bundle

2) Add the old functionality of attr_accessible again to rails 4.0

Try to use attr_accessible and don't comment this out.

Add this line to your application's Gemfile:

gem 'protected_attributes'

Then execute:

$ bundle

PivotTable's Report Filter using "greater than"

After some research I finally got a VBA code to show the filter value in another cell:

Dim bRepresentAsRange As Boolean, bRangeBroken As Boolean
Dim sSelection As String
Dim tbl As Variant
bRepresentAsRange = False
bRangeBroker = False

With Worksheets("Forecast").PivotTables("ForecastbyDivision")
            ReDim tbl(.PageFields("Probability").PivotItems.Count)
            For Each fld In .PivotFields("Probability").PivotItems

                If fld.Visible Then
                    tbl(n) = fld.Name
                    sSelection = sSelection & fld.Name & ","
                    n = n + 1
                    bRepresentAsRange = True
                Else
                    If bRepresentAsRange Then
                        bRepresentAsRange = False
                        bRangeBroken = True
                    End If
                End If

            Next fld

            If Not bRangeBroken Then
                Worksheets("Forecast").Range("ProbSelection") = " >= " & tbl(0)
            Else
                Worksheets("Forecast").Range("ProbSelection") = Left(sSelection, Len(sSelection) - 1)
            End If

        End With

How do I print a double value with full precision using cout?

printf("%.12f", M_PI);

%.12f means floating point, with precision of 12 digits.

Group by with union mysql select query

Try this EDITED:

(SELECT COUNT(motorbike.owner_id),owner.name,transport.type FROM transport,owner,motorbike WHERE transport.type='motobike' AND owner.owner_id=motorbike.owner_id AND transport.type_id=motorbike.motorbike_id GROUP BY motorbike.owner_id)

UNION ALL

(SELECT COUNT(car.owner_id),owner.name,transport.type FROM transport,owner,car WHERE transport.type='car' AND owner.owner_id=car.owner_id AND transport.type_id=car.car_id GROUP BY car.owner_id)

How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?

Try this:

str.replace("\"", "\\\""); // (Escape backslashes and embedded double-quotes)

Or, use single-quotes to quote your search and replace strings:

str.replace('"', '\\"');   // (Still need to escape the backslash)

As pointed out by helmus, if the first parameter passed to .replace() is a string it will only replace the first occurrence. To replace globally, you have to pass a regex with the g (global) flag:

str.replace(/"/g, "\\\"");
// or
str.replace(/"/g, '\\"');

But why are you even doing this in JavaScript? It's OK to use these escape characters if you have a string literal like:

var str = "Dude, he totally said that \"You Rock!\"";

But this is necessary only in a string literal. That is, if your JavaScript variable is set to a value that a user typed in a form field you don't need to this escaping.

Regarding your question about storing such a string in an SQL database, again you only need to escape the characters if you're embedding a string literal in your SQL statement - and remember that the escape characters that apply in SQL aren't (usually) the same as for JavaScript. You'd do any SQL-related escaping server-side.

Calling a php function by onclick event

In Your HTML

<input type="button" name="Release" onclick="hello();" value="Click to Release" />

In Your JavaScript

<script type="text/javascript">
    function hello(){
        alert('Your message here');
    }
</script>

If you need to run PHP in JavaScript You need to use JQuery Ajax Function

<script type="text/javascript">
function hello(){
    $.ajax(
{     
 type:    'post',
 url:     'folder/my_php_file.php',
 data:    '&id=' + $('#id').val() + '&name=' +     $('#name').val(),
 dataType: 'json',
 //alert(data);
 success: function(data) 
 {
  //alert(data);
 }   
});
}
</script>

Now in your my_php_file.php file

<?php 
    echo 'hello';
?>

Good Luck !!!!!

what does the __file__ variable mean/do?

When a module is loaded from a file in Python, __file__ is set to its path. You can then use that with other functions to find the directory that the file is located in.

Taking your examples one at a time:

A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.

B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.

C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.

You can see the various values returned from these here:

import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))

and make sure you run it from different locations (such as ./text.py, ~/python/text.py and so forth) to see what difference that makes.


I just want to address some confusion first. __file__ is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.

http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.

In this case __file__ is an attribute of a module (a module object). In Python a .py file is a module. So import amodule will have an attribute of __file__ which means different things under difference circumstances.

Taken from the docs:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

In your case the module is accessing it's own __file__ attribute in the global namespace.

To see this in action try:

# file: test.py

print globals()
print __file__

And run:

python test.py

{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
 'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py

How to enable ASP classic in IIS7.5

If you get the above problem on windows server 2008 you may need to enable ASP. To do so, follow these steps:

Add an 'Application Server' role:

  1. Click Start, point to Control Panel, click Programs, and then click Turn Windows features on or off.
  2. Right-click Server Manager, select Add Roles.
  3. On the Add Roles Wizard page, select Application Server, click Next three times, and then click Install. Windows Server installs the new role.

Then, add a 'Web Server' role:

  1. Web Server Role (IIS): in ServerManager, Roles, if the Web Server (IIS) role does not exist then add it.
  2. Under Web Server (IIS) role add role services for: ApplicationDevelopment:ASP, ApplicationDevelopment:ISAPI Exstensions, Security:Request Filtering.

More info: http://www.iis.net/learn/application-frameworks/running-classic-asp-applications-on-iis-7-and-iis-8/classic-asp-not-installed-by-default-on-iis

How do I turn a String into a InputStreamReader in java?

Does it have to be specifically an InputStreamReader? How about using StringReader?

Otherwise, you could use StringBufferInputStream, but it's deprecated because of character conversion issues (which is why you should prefer StringReader).

Quickest way to convert XML to JSON in Java

To convert XML File in to JSON include the following dependency

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20140107</version>
</dependency>

and you can Download Jar from Maven Repository here. Then implement as:

String soapmessageString = "<xml>yourStringURLorFILE</xml>";
JSONObject soapDatainJsonObject = XML.toJSONObject(soapmessageString);
System.out.println(soapDatainJsonObject);

ASP.NET page life cycle explanation

There are 10 events in ASP.NET page life cycle, and the sequence is:

  1. Init
  2. Load view state
  3. Post back data
  4. Load
  5. Validate
  6. Events
  7. Pre-render
  8. Save view state
  9. Render
  10. Unload

Below is a pictorial view of ASP.NET Page life cycle with what kind of code is expected in that event. I suggest you read this article I wrote on the ASP.NET Page life cycle, which explains each of the 10 events in detail and when to use them.

ASP.NET life cycle

Image source: my own article at https://www.c-sharpcorner.com/uploadfile/shivprasadk/Asp-Net-application-and-page-life-cycle/ from 19 April 2010

HttpClient - A task was cancelled?

Promoting @JobaDiniz's comment to an answer:

Do not do the obvious thing and dispose the HttpClient instance, even though the code "looks right":

async Task<HttpResponseMessage> Method() {
  using (var client = new HttpClient())
    return client.GetAsync(request);
}

The same happens with C#'s new RIAA syntax; slightly less obvious:

async Task<HttpResponseMessage> Method() {
  using var client = new HttpClient();
  return client.GetAsync(request);
}

Instead, cache a static instance of HttpClient for your app or library, and reuse it:

static HttpClient client = new HttpClient();

async Task<HttpResponseMessage> Method() {
  return client.GetAsync(request);
}

(The Async() request methods are all thread safe.)

How to install requests module in Python 3.4, instead of 2.7

Just answering this old thread can be installed without pip On windows or Linux:

1) Download Requests from https://github.com/kennethreitz/requests click on clone or download button

2) Unzip the files in your python directory .Exp your python is installed in C:Python\Python.exe then unzip there

3) Depending on the Os run the following command:

  • Windows use command cd to your python directory location then setup.py install
  • Linux command: python setup.py install

Thats it :)

Apply formula to the entire column

It looks like some of the other answers have become outdated, but for me this worked:

  1. Click on the cell with the text/formula to copy
  2. Shift+Click on the last cell to copy to
  3. Ctrl + Enter

(Note that this replaces text if the destination cells aren't empty)

Convert object to JSON string in C#

I have used Newtonsoft JSON.NET (Documentation) It allows you to create a class / object, populate the fields, and serialize as JSON.

public class ReturnData 
{
    public int totalCount { get; set; }
    public List<ExceptionReport> reports { get; set; }  
}

public class ExceptionReport
{
    public int reportId { get; set; }
    public string message { get; set; }  
}


string json = JsonConvert.SerializeObject(myReturnData);

How to check if element in groovy array/hash/collection/list?

def fruitBag = ["orange","banana","coconut"]
def fruit = fruitBag.collect{item -> item.contains('n')}

I did it like this so it works if someone is looking for it.

In Oracle, is it possible to INSERT or UPDATE a record through a view?

YES, you can Update and Insert into view and that edit will be reflected on the original table....
BUT
1-the view should have all the NOT NULL values on the table
2-the update should have the same rules as table... "updating primary key related to other foreign key.. etc"...

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

This happens when a session other than the one used to alter a table is holding a lock likely because of a DML (update/delete/insert). If you are developing a new system, it is likely that you or someone in your team issues the update statement and you could kill the session without much consequence. Or you could commit from that session once you know who has the session open.

If you have access to a SQL admin system use it to find the offending session. And perhaps kill it.

You could use v$session and v$lock and others but I suggest you google how to find that session and then how to kill it.

In a production system, it really depends. For oracle 10g and older, you could execute

LOCK TABLE mytable in exclusive mode;
alter table mytable modify mycolumn varchar2(5);

In a separate session but have the following ready in case it takes too long.

alter system kill session '....

It depends on what system do you have, older systems are more likely to not commit every single time. That is a problem since there may be long standing locks. So your lock would prevent any new locks and wait for a lock that who knows when will be released. That is why you have the other statement ready. Or you could look for PLSQL scripts out there that do similar things automatically.

In version 11g there is a new environment variable that sets a wait time. I think it likely does something similar to what I described. Mind you that locking issues don't go away.

ALTER SYSTEM SET ddl_lock_timeout=20;
alter table mytable modify mycolumn varchar2(5);

Finally it may be best to wait until there are few users in the system to do this kind of maintenance.

angular 4: *ngIf with multiple conditions

Besides the redundant ) this expression will always be true because currentStatus will always match one of these two conditions:

currentStatus !== 'open' || currentStatus !== 'reopen'

perhaps you mean one of

!(currentStatus === 'open' || currentStatus === 'reopen')
(currentStatus !== 'open' && currentStatus !== 'reopen')

How do I wait until Task is finished in C#?

Your Print method likely needs to wait for the continuation to finish (ContinueWith returns a task which you can wait on). Otherwise the second ReadAsStringAsync finishes, the method returns (before result is assigned in the continuation). Same problem exists in your send method. Both need to wait on the continuation to consistently get the results you want. Similar to below

private static string Send(int id)
{
    Task<HttpResponseMessage> responseTask = client.GetAsync("aaaaa");
    string result = string.Empty;
    Task continuation = responseTask.ContinueWith(x => result = Print(x));
    continuation.Wait();
    return result;
}

private static string Print(Task<HttpResponseMessage> httpTask)
{
    Task<string> task = httpTask.Result.Content.ReadAsStringAsync();
    string result = string.Empty;
    Task continuation = task.ContinueWith(t =>
    {
        Console.WriteLine("Result: " + t.Result);
        result = t.Result;
    });
    continuation.Wait();  
    return result;
}

Dynamic tabs with user-click chosen components

there is component ready to use (rc5 compatible) ng2-steps which uses Compiler to inject component to step container and service for wiring everything together (data sync)

    import { Directive , Input, OnInit, Compiler , ViewContainerRef } from '@angular/core';

import { StepsService } from './ng2-steps';

@Directive({
  selector:'[ng2-step]'
})
export class StepDirective implements OnInit{

  @Input('content') content:any;
  @Input('index') index:string;
  public instance;

  constructor(
    private compiler:Compiler,
    private viewContainerRef:ViewContainerRef,
    private sds:StepsService
  ){}

  ngOnInit(){
    //Magic!
    this.compiler.compileComponentAsync(this.content).then((cmpFactory)=>{
      const injector = this.viewContainerRef.injector;
      this.viewContainerRef.createComponent(cmpFactory, 0,  injector);
    });
  }

}

Setting dynamic scope variables in AngularJs - scope.<some_string>

Create Dynamic angular variables from results

angular.forEach(results, function (value, key) {          
  if (key != null) {                       
    $parse(key).assign($scope, value);                                
  }          
});

ps. don't forget to pass in the $parse attribute into your controller's function

Undefined columns selected when subsetting data frame

You want rows where that condition is true so you need a comma:

data[data$Ozone > 14, ]

How to write PNG image to string with the PIL?

For Python3 it is required to use BytesIO:

from io import BytesIO
from PIL import Image, ImageDraw

image = Image.new("RGB", (300, 50))
draw = ImageDraw.Draw(image)
draw.text((0, 0), "This text is drawn on image")

byte_io = BytesIO()

image.save(byte_io, 'PNG')

Read more: http://fadeit.dk/blog/post/python3-flask-pil-in-memory-image

Strange PostgreSQL "value too long for type character varying(500)"

We had this same issue. We solved it adding 'length' to entity attribute definition:

@Column(columnDefinition="text", length=10485760)
private String configFileXml = ""; 

Basic Authentication Using JavaScript

EncodedParams variable is redefined as params variable will not work. You need to have same predefined call to variable, otherwise it looks possible with a little more work. Cheers! json is not used to its full capabilities in php there are better ways to call json which I don't recall at the moment.

Why use deflate instead of gzip for text files served by Apache?

if I remember correctly

  • gzip will compress a little more than deflate
  • deflate is more efficient

How do I configure Maven for offline development?

If you have a PC with internet access in your LAN, you should install a local Maven repository.

I recommend Artifactory Open Source. This is what we use in our organization, it is really easy to setup.

Artifactory acts as a proxy between your build tool (Maven, Ant, Ivy, Gradle etc.) and the outside world.

It caches remote artifacts so that you don’t have to download them over and over again.

It blocks unwanted (and sometimes security-sensitive) external requests for internal artifacts and controls how and where artifacts are deployed, and by whom.

After setting up Artifactory you just need to change Maven's settings.xml in the development machines:

<?xml version="1.0" encoding="UTF-8"?>
<settings xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd" xmlns="http://maven.apache.org/SETTINGS/1.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <mirrors>
    <mirror>
      <mirrorOf>*</mirrorOf>
      <name>repo</name>
      <url>http://maven.yourorganization.com:8081/artifactory/repo</url>
      <id>repo</id>
    </mirror>
  </mirrors>
  <profiles>
    <profile>
      <repositories>
        <repository>
          <snapshots>
            <enabled>false</enabled>
          </snapshots>
          <id>central</id>
          <name>libs-release</name>
          <url>http://maven.yourorganization.com:8081/artifactory/libs-release</url>
        </repository>
        <repository>
          <snapshots />
          <id>snapshots</id>
          <name>libs-snapshot</name>
          <url>http://maven.yourorganization.com:8081/artifactory/libs-snapshot</url>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
          <snapshots>
            <enabled>false</enabled>
          </snapshots>
          <id>central</id>
          <name>plugins-release</name>
          <url>http://maven.yourorganization.com:8081/artifactory/plugins-release</url>
        </pluginRepository>
        <pluginRepository>
          <snapshots />
          <id>snapshots</id>
          <name>plugins-snapshot</name>
          <url>http://maven.yourorganization.com:8081/artifactory/plugins-snapshot</url>
        </pluginRepository>
      </pluginRepositories>
      <id>artifactory</id>
    </profile>
  </profiles>
  <activeProfiles>
    <activeProfile>artifactory</activeProfile>
  </activeProfiles>
</settings>

We used this solution because we had problems with internet access in our development machines and some artifacts downloaded corrupted files or didn't download at all. We haven't had problems since.

Printing out all the objects in array list

You have to define public String toString() method in your Student class. For example:

public String toString() {
  return "Student: " + studentName + ", " + studentNo;
}

Download a div in a HTML page as pdf using javascript

Content inside a <div class='html-content'>....</div> can be downloaded as pdf with styles using jspdf & html2canvas.

You need to refer both js libraries,

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>

Then call below function,

//Create PDf from HTML...
function CreatePDFfromHTML() {
    var HTML_Width = $(".html-content").width();
    var HTML_Height = $(".html-content").height();
    var top_left_margin = 15;
    var PDF_Width = HTML_Width + (top_left_margin * 2);
    var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
    var canvas_image_width = HTML_Width;
    var canvas_image_height = HTML_Height;

    var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;

    html2canvas($(".html-content")[0]).then(function (canvas) {
        var imgData = canvas.toDataURL("image/jpeg", 1.0);
        var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
        pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
        for (var i = 1; i <= totalPDFPages; i++) { 
            pdf.addPage(PDF_Width, PDF_Height);
            pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height);
        }
        pdf.save("Your_PDF_Name.pdf");
        $(".html-content").hide();
    });
}

Ref: pdf genration from html canvas and jspdf.

May be this will help someone.

Android Intent Cannot resolve constructor

You may use this:

Intent intent = new Intent(getApplicationContext(), ClassName.class);

Sending images using Http Post

The loopj library can be used straight-forward for this purpose:

SyncHttpClient client = new SyncHttpClient();
RequestParams params = new RequestParams();
params.put("text", "some string");
params.put("image", new File(imagePath));

client.post("http://example.com", params, new TextHttpResponseHandler() {
  @Override
  public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
    // error handling
  }

  @Override
  public void onSuccess(int statusCode, Header[] headers, String responseString) {
    // success
  }
});

http://loopj.com/

Using both Python 2.x and Python 3.x in IPython Notebook

Under Windows 7 I had anaconda and anaconda3 installed. I went into \Users\me\anaconda\Scripts and executed

sudo .\ipython kernelspec install-self

then I went into \Users\me\anaconda3\Scripts and executed

sudo .\ipython kernel install

(I got jupyter kernelspec install-self is DEPRECATED as of 4.0. You probably want 'ipython kernel install' to install the IPython kernelspec.)

After starting jupyter notebook (in anaconda3) I got a neat dropdown menu in the upper right corner under "New" letting me choose between Python 2 odr Python 3 kernels.

PHP code to remove everything but numbers

This is for future developers, you can also try this. Simple too

echo preg_replace('/\D/', '', '604-619-5135');

Linking a UNC / Network drive on an html page

To link to a UNC path from an HTML document, use file:///// (yes, that's five slashes).

file://///server/path/to/file.txt

Note that this is most useful in IE and Outlook/Word. It won't work in Chrome or Firefox, intentionally - the link will fail silently. Some words from the Mozilla team:

For security purposes, Mozilla applications block links to local files (and directories) from remote files.

And less directly, from Google:

Firefox and Chrome doesn't open "file://" links from pages that originated from outside the local machine. This is a design decision made by those browsers to improve security.

The Mozilla article includes a set of client settings you can use to override this behavior in Firefox, and there are extensions for both browsers to override this restriction.

Image convert to Base64

Exactly what you need:) You can choose callback version or Promise version. Note that promises will work in IE only with Promise polyfill lib.You can put this code once on a page, and this function will appear in all your files.

The loadend event is fired when progress has stopped on the loading of a resource (e.g. after "error", "abort", or "load" have been dispatched)

Callback version

        File.prototype.convertToBase64 = function(callback){
                var reader = new FileReader();
                reader.onloadend = function (e) {
                    callback(e.target.result, e.target.error);
                };   
                reader.readAsDataURL(this);
        };

        $("#asd").on('change',function(){
          var selectedFile = this.files[0];
          selectedFile.convertToBase64(function(base64){
               alert(base64);
          }) 
        });

Promise version

    File.prototype.convertToBase64 = function(){
         return new Promise(function(resolve, reject) {
                var reader = new FileReader();
                reader.onloadend = function (e) {
                    resolve({
                      fileName: this.name,
                      result: e.target.result, 
                      error: e.target.error
                    });
                };   
                reader.readAsDataURL(this);
        }.bind(this)); 
    };

    FileList.prototype.convertAllToBase64 = function(regexp){
      // empty regexp if not set
      regexp = regexp || /.*/;
      //making array from FileList
      var filesArray = Array.prototype.slice.call(this);
      var base64PromisesArray = filesArray.
           filter(function(file){
             return (regexp).test(file.name)
           }).map(function(file){
             return file.convertToBase64();
           });
      return Promise.all(base64PromisesArray);
    };

    $("#asd").on('change',function(){
      //for one file
      var selectedFile = this.files[0];
      selectedFile.convertToBase64().
          then(function(obj){
            alert(obj.result);
          });
      });
      //for all files that have file extention png, jpeg, jpg, gif
      this.files.convertAllToBase64(/\.(png|jpeg|jpg|gif)$/i).then(function(objArray){
            objArray.forEach(function(obj, i){
                  console.log("result[" + obj.fileName + "][" + i + "] = " + obj.result);
            });
      });
    })

html

<input type="file" id="asd" multiple/>

Using HTML and Local Images Within UIWebView

I had a simmilar problem, but all the suggestions didn't help.

However, the problem was the *.png itself. It had no alpha channel. Somehow Xcode ignores all png files without alpha channel during the deploy process.

GROUP BY without aggregate function

As an addition

basically the number of columns have to be equal to the number of columns in the GROUP BY clause

is not a correct statement.

  • Any attribute which is not a part of GROUP BY clause can not be used for selection
  • Any attribute which is a part of GROUP BY clause can be used for selection but not mandatory.

The Role Manager feature has not been enabled

I found this question due the exception mentioned in it. My Web.Config didn't have any <roleManager> tag. I realized that even if I added it (as Infotekka suggested), it ended up in a Database exception. After following the suggestions in the other answers in here, none fully solved the problem.

Since these Web.Config tags can be automatically generated, it felt wrong to solve it by manually adding them. If you are in a similar case, undo all the changes you made to Web.Config and in Visual Studio:

  1. Press Ctrl+Q, type nuget and click on "Manage NuGet Packages";
  2. Press Ctrl+E, type providers and in the list it should show up "Microsoft ASP.NET Universal Providers Core Libraries" and "Microsoft ASP.NET Universal Providers for LocalDB" (both created by Microsoft);
  3. Click on the Install button in both of them and close the NuGet window;
  4. Check your Web.config and now you should have at least one <providers> tag inside Profile, Membership, SessionState tags and also inside the new RoleManager tag, like this:

    <roleManager defaultProvider="DefaultRoleProvider">
        <providers>
           <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=NUMBER" connectionStringName="DefaultConnection" applicationName="/" />
        </providers>
    </roleManager>
    
  5. Add enabled="true" like so:

    <roleManager defaultProvider="DefaultRoleProvider" enabled="true">
    
  6. Press F6 to Build and now it should be OK to proceed to a database update without having that exception:

    1. Press Ctrl+Q, type manager, click on "Package Manager Console";
    2. Type update-database -verbose and the Seed method will run just fine (if you haven't messed elsewhere) and create a few tables in your Database;
    3. Press Ctrl+W+L to open the Server Explorer and you should be able to check in Data Connections > DefaultConnection > Tables the Roles and UsersInRoles tables among the newly created tables!

Undefined index with $_POST

Related question: What is the best way to access unknown array elements without generating PHP notice?

Using the answer from the question above, you can safely get a value from $_POST without generating PHP notice if the key does not exists.

echo _arr($_POST, 'username', 'no username supplied');  
// will print $_POST['username'] or 'no username supplied'

Display number with leading zeros

In Python >= 3.6, you can do this succinctly with the new f-strings that were introduced by using:

f'{val:02}'

which prints the variable with name val with a fill value of 0 and a width of 2.

For your specific example you can do this nicely in a loop:

a, b, c = 1, 10, 100
for val in [a, b, c]:
    print(f'{val:02}')

which prints:

01 
10
100

For more information on f-strings, take a look at PEP 498 where they were introduced.

How to split the screen with two equal LinearLayouts?

In order to split the ui into two equal parts you can use weightSum of 2 in the parent LinearLayout and assign layout_weight of 1 to each as shown below

<?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="horizontal"
    android:weightSum="2">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

        </LinearLayout>

       <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

       </LinearLayout>


</LinearLayout>

Using Postman to access OAuth 2.0 Google APIs

This is an old question, but it has no chosen answer, and I just solved this problem myself. Here's my solution:

  1. Make sure you are set up to work with your Google API in the first place. See Google's list of prerequisites. I was working with Google My Business, so I also went through it's Get Started process.

  2. In the OAuth 2.0 playground, Step 1 requires you to select which API you want to authenticate. Select or input as applicable for your case (in my case for Google My Business, I had to input https://www.googleapis.com/auth/plus.business.manage into the "Input your own scopes" input field). Note: this is the same as what's described in step 6 of the "Make a simple HTTP request" section of the Get Started guide.

  3. Assuming successful authentication, you should get an "Access token" returned in the "Step 1's result" step in the OAuth playground. Copy this token to your clipboard.

  4. Open Postman and open whichever collection you want as necessary.

  5. In Postman, make sure "GET" is selected as the request type, and click on the "Authorization" tab below the request type drop-down.

  6. In the Authorization "TYPE" dropdown menu, select "Bearer Token"

  7. Paste your previously copied "Access Token" which you copied from the OAuth playground into the "Token" field which displays in Postman.

  8. Almost there! To test if things work, put https://mybusiness.googleapis.com/v4/accounts/ into the main URL input bar in Postman and click the send button. You should get a JSON list of accounts back in the response that looks something like the following:

    
    {
        "accounts": [
            {
                "name": "accounts/REDACTED",
                "accountName": "REDACTED",
                "type": "PERSONAL",
                "state": {
                    "status": "UNVERIFIED"
                }
            },
            {
                "name": "accounts/REDACTED",
                "accountName": "REDACTED",
                "type": "LOCATION_GROUP",
                "role": "OWNER",
                "state": {
                    "status": "UNVERIFIED"
                },
                "permissionLevel": "OWNER_LEVEL"
            }
        ]
    }
    

Mongodb service won't start

it probably might be due to the mongod.lock file, but if the error persists even after deleting it check the paths in mongo.conf; it might be a simple issue such as the configured log Path or dbPath is not there (check the paths in mongo/conf/mongod.conf and check whether they exists, sometimes mongo cannot in its own create directory structures therefore you might have to create those directories manually before starting mongod).

How do I programmatically click a link with javascript?

For me, I managed to make it work that way. I deployed the automatic click in 5000 milliseconds and then closed the loop after 1000 milliseconds. Then there was only 1 automatic click.

<script> var myVar = setInterval(function ({document.getElementById("test").click();}, 500)); setInterval(function () {clearInterval(myVar)}, 1000));</script>

Is returning out of a switch statement considered a better practice than using break?

It depends, if your function only consists of the switch statement, then I think that its fine. However, if you want to perform any other operations within that function, its probably not a great idea. You also may have to consider your requirements right now versus in the future. If you want to change your function from option one to option two, more refactoring will be needed.

However, given that within if/else statements it is best practice to do the following:

var foo = "bar";

if(foo == "bar") {
    return 0;
}
else {
    return 100;
}

Based on this, the argument could be made that option one is better practice.

In short, there's no clear answer, so as long as your code adheres to a consistent, readable, maintainable standard - that is to say don't mix and match options one and two throughout your application, that is the best practice you should be following.

Can I check if Bootstrap Modal Shown / Hidden?

In offical way:

> ($("element").data('bs.modal') || {})._isShown    // Bootstrap 4
> ($("element").data('bs.modal') || {}).isShown     // Bootstrap <= 3

{} is used to avoid the case that modal is not opened yet (it return undefined). You can also assign it equal {isShown: false} to keep it's more make sense.

CSS: Background image and padding

Use background-position: calc(100% - 20px) center, For pixel perfection calc() is the best solution.

_x000D_
_x000D_
ul {_x000D_
  width: 100px;_x000D_
}_x000D_
ul li {_x000D_
  border: 1px solid orange;_x000D_
  background: url("http://placehold.it/30x15") no-repeat calc(100% - 10px) center;_x000D_
}_x000D_
ul li:hover {_x000D_
  background-position: calc(100% - 20px) center;_x000D_
}
_x000D_
<ul>_x000D_
  <li>Hello</li>_x000D_
  <li>Hello world</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

What is a difference between unsigned int and signed int in C?

ISO C states what the differences are.

The int data type is signed and has a minimum range of at least -32767 through 32767 inclusive. The actual values are given in limits.h as INT_MIN and INT_MAX respectively.

An unsigned int has a minimal range of 0 through 65535 inclusive with the actual maximum value being UINT_MAX from that same header file.

Beyond that, the standard does not mandate twos complement notation for encoding the values, that's just one of the possibilities. The three allowed types would have encodings of the following for 5 and -5 (using 16-bit data types):

        two's complement  |  ones' complement   |   sign/magnitude
    +---------------------+---------------------+---------------------+
 5  | 0000 0000 0000 0101 | 0000 0000 0000 0101 | 0000 0000 0000 0101 |
-5  | 1111 1111 1111 1011 | 1111 1111 1111 1010 | 1000 0000 0000 0101 |
    +---------------------+---------------------+---------------------+
  • In two's complement, you get a negative of a number by inverting all bits then adding 1.
  • In ones' complement, you get a negative of a number by inverting all bits.
  • In sign/magnitude, the top bit is the sign so you just invert that to get the negative.

Note that positive values have the same encoding for all representations, only the negative values are different.

Note further that, for unsigned values, you do not need to use one of the bits for a sign. That means you get more range on the positive side (at the cost of no negative encodings, of course).

And no, 5 and -5 cannot have the same encoding regardless of which representation you use. Otherwise, there'd be no way to tell the difference.


As an aside, there are currently moves underway, in both C and C++ standards, to nominate two's complement as the only encoding for negative integers.

Find PHP version on windows command line

Nothing to worry it's easy

If you are using any local server like Wamp, Xampp then Go to this Steps

  1. Go to your drive
  2. Check xampp or wamp server that you installed
  3. Inside that check php, if you got then go for next step
  4. You will find php.exe, Once you get php.exe then you are done. Just type the path like below, here i am using XAMPP and type v for checking version and you are done.

    C:>"C:\xampp\php\php.exe" -v

Thanks.

Mongod complains that there is no /data/db folder

This solution solves my problem

  1. Make a directory as

    sudo mkdir -p /data/db

  2. That will make a directory named as db and than try to start with commands

    sudo mongod

If you get another error or problem with starting mongod, You may find problem as

Failed to set up listener: SocketException: Address already in use If you find that another error than you have to kill the running process of mongod by typing to terminal as

ps ax | grep mongod
sudo kill ps_number

and find the mongod running port and kill the process. Another way is to make a specefic port when starting mongod as

sudo mongod --port 27018

Convert .cer certificate to .jks

Just to be sure that this is really the "conversion" you need, please note that jks files are keystores, a file format used to store more than one certificate and allows you to retrieve them programmatically using the Java security API, it's not a one-to-one conversion between equivalent formats.

So, if you just want to import that certificate in a new ad-hoc keystore you can do it with Keystore Explorer, a graphical tool. You'll be able to modify the keystore and the certificates contained therein like you would have done with the java terminal utilities like keytool (but in a more accessible way).

how to store Image as blob in Sqlite & how to retrieve it?

byte[] byteArray = rs.getBytes("columnname");  

Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0 ,byteArray.length);

IE11 Document mode defaults to IE7. How to reset?

By default, IE displays webpages in the Intranet zone in compatibility view. To change this:

  • Press Alt to display the IE menu.
  • Choose Tools | Compatibility View settings
  • Remove the checkmark next to Display intranet sites in Compatibility View.
  • Choose Close.

At this point, IE should rely on the webpage itself (or any relevant group policies) to determine the compatibility settings for your Intranet webpages.

Note that certain sites may no longer function correctly after making this change. You can use the same dialog box to add specific sites to enable compatibility view when needed.

generate random double numbers in c++

This should be performant, thread-safe and flexible enough for many uses:

#include <random>
#include <iostream>

template<typename Numeric, typename Generator = std::mt19937>
Numeric random(Numeric from, Numeric to)
{
    thread_local static Generator gen(std::random_device{}());

    using dist_type = typename std::conditional
    <
        std::is_integral<Numeric>::value
        , std::uniform_int_distribution<Numeric>
        , std::uniform_real_distribution<Numeric>
    >::type;

    thread_local static dist_type dist;

    return dist(gen, typename dist_type::param_type{from, to});
}

int main(int, char*[])
{
    for(auto i = 0U; i < 20; ++i)
        std::cout << random<double>(0.0, 0.3) << '\n';
}

Nesting queries in SQL

Query below should help you achieve what you want.

select scountry, headofstate from data 
where data.scountry like 'a%'and ttlppl>=100000

Button text toggle in jquery

You could also use .toggle() like so:

$(".pushme").toggle(function() {
    $(this).text("DON'T PUSH ME");
}, function() {
    $(this).text("PUSH ME");
});

More info at http://api.jquery.com/toggle-event/.

This way also makes it pretty easy to change the text or add more than just 2 differing states.

Adding 30 minutes to time formatted as H:i in PHP

$time = 30 * 60; //30 minutes
$start_time = date('Y-m-d h:i:s', time() - $time);
$end_time = date('Y-m-d h:i:s', time() + $time);

What do .c and .h file extensions mean to C?

.c : c file (where the real action is, in general)

.h : header file (to be included with a preprocessor #include directive). Contains stuff that is normally deemed to be shared with other parts of your code, like function prototypes, #define'd stuff, extern declaration for global variables (oh, the horror) and the like.

Technically, you could put everything in a single file. A whole C program. million of lines. But we humans tend to organize things. So you create different C files, each one containing particular functions. That's all nice and clean. Then suddenly you realize that a declaration you have into a given C file should exist also in another C file. So you would duplicate them. The best is therefore to extract the declaration and put it into a common file, which is the .h

For example, in the cs50.h you find what are called "forward declarations" of your functions. A forward declaration is a quick way to tell the compiler how a function should be called (e.g. what input params) and what it returns, so it can perform proper checking (for example if you call a function with the wrong number of parameters, it will complain).

Another example. Suppose you write a .c file containing a function performing regular expression matching. You want your function to accept the regular expression, the string to match, and a parameter that tells if the comparison has to be case insensitive.

in the .c you will therefore put

bool matches(string regexp, string s, int flags) { the code }

Now, assume you want to pass the following flags:

0: if the search is case sensitive

1: if the search is case insensitive

And you want to keep yourself open to new flags, so you did not put a boolean. playing with numbers is hard, so you define useful names for these flags

#define MATCH_CASE_SENSITIVE 0
#define MATCH_CASE_INSENSITIVE 1

This info goes into the .h, because if any program wants to use these labels, it has no way of knowing them unless you include the info. Of course you can put them in the .c, but then you would have to include the .c code (whole!) which is a waste of time and a source of trouble.

jQuery each loop in table row

In jQuery just use:

$('#tblOne > tbody  > tr').each(function() {...code...});

Using the children selector (>) you will walk over all the children (and not all descendents), example with three rows:

$('table > tbody  > tr').each(function(index, tr) { 
   console.log(index);
   console.log(tr);
});

Result:

0
<tr>
1 
<tr>
2
<tr>

In VanillaJS you can use document.querySelectorAll() and walk over the rows using forEach()

[].forEach.call(document.querySelectorAll('#tblOne > tbody  > tr'), function(index, tr) {
    /* console.log(index); */
    /* console.log(tr); */
});

Simple if else onclick then do?

The preferred modern method is to use addEventListener either by adding the event listener direct to the element or to a parent of the elements (delegated).

An example, using delegated events, might be

_x000D_
_x000D_
var box = document.getElementById('box');_x000D_
_x000D_
document.getElementById('buttons').addEventListener('click', function(evt) {_x000D_
  var target = evt.target;_x000D_
  if (target.id === 'yes') {_x000D_
    box.style.backgroundColor = 'red';_x000D_
  } else if (target.id === 'no') {_x000D_
    box.style.backgroundColor = 'green';_x000D_
  } else {_x000D_
    box.style.backgroundColor = 'purple';_x000D_
  }_x000D_
}, false);
_x000D_
#box {_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  background-color: red;_x000D_
}_x000D_
#buttons {_x000D_
  margin-top: 50px;_x000D_
}
_x000D_
<div id='box'></div>_x000D_
<div id='buttons'>_x000D_
  <button id='yes'>yes</button>_x000D_
  <button id='no'>no</button>_x000D_
  <p>Click one of the buttons above.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Google Maps API - how to get latitude and longitude from Autocomplete without showing the map?

You can get lat, lng from the place object i.e.

var place = autocomplete.getPlace();

var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();

Jenkins Host key verification failed

I ran into this issue and it turned out the problem was that the jenkins service wasn't being run as the jenkins user. So running the commands as the jenkins user worked just fine.

Converting Columns into rows with their respective data in sql server

select 'ScriptName', scriptName from table
union all
select 'ScriptCode', scriptCode from table
union all
select 'Price', price from table

Free FTP Library

I've just posted an article that presents both an FTP client class and an FTP user control.

They are simple and aren't very fast, but are very easy to use and all source code is included. Just drop the user control onto a form to allow users to navigate FTP directories from your application.

Declare an array in TypeScript

let arr1: boolean[] = [];

console.log(arr1[1]);

arr1.push(true);

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

[A1].End(xlUp)
[A1].End(xlDown)
[A1].End(xlToLeft)
[A1].End(xlToRight)

is the VBA equivalent of being in Cell A1 and pressing Ctrl + Any arrow key. It will continue to travel in that direction until it hits the last cell of data, or if you use this command to move from a cell that is the last cell of data it will travel until it hits the next cell containing data.

If you wanted to find that last "used" cell in Column A, you could go to A65536 (for example, in an XL93-97 workbook) and press Ctrl + Up to "snap" to the last used cell. Or in VBA you would write:

Range("A65536").End(xlUp) which again can be re-written as Range("A" & Rows.Count).End(xlUp) for compatibility reasons across workbooks with different numbers of rows.

Convert java.util.Date to java.time.LocalDate

public static LocalDate Date2LocalDate(Date date) {
        return LocalDate.parse(date.toString(), DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy"))

this format is from Date#tostring

    public String toString() {
        // "EEE MMM dd HH:mm:ss zzz yyyy";
        BaseCalendar.Date date = normalize();
        StringBuilder sb = new StringBuilder(28);
        int index = date.getDayOfWeek();
        if (index == BaseCalendar.SUNDAY) {
            index = 8;
        }
        convertToAbbr(sb, wtb[index]).append(' ');                        // EEE
        convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' ');  // MMM
        CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd

        CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':');   // HH
        CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
        CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
        TimeZone zi = date.getZone();
        if (zi != null) {
            sb.append(zi.getDisplayName(date.isDaylightTime(), TimeZone.SHORT, Locale.US)); // zzz
        } else {
            sb.append("GMT");
        }
        sb.append(' ').append(date.getYear());  // yyyy
        return sb.toString();
    }

xlrd.biffh.XLRDError: Excel xlsx file; not supported

As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:

xlrd has explicitly removed support for anything other than xls files.

In your case, the solution is to:

  • make sure you are on a recent version of Pandas, at least 1.0.1, and preferably the latest release. 1.2 will make his even clearer.
  • install openpyxl: https://openpyxl.readthedocs.io/en/stable/
  • change your Pandas code to be:
    df1 = pd.read_excel(
         os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
         engine='openpyxl',
    )
    

ValueError: could not convert string to float: id

This error is pretty verbose:

ValueError: could not convert string to float: id

Somewhere in your text file, a line has the word id in it, which can't really be converted to a number.

Your test code works because the word id isn't present in line 2.


If you want to catch that line, try this code. I cleaned your code up a tad:

#!/usr/bin/python

import os, sys
from scipy import stats
import numpy as np

for index, line in enumerate(open('data2.txt', 'r').readlines()):
    w = line.split(' ')
    l1 = w[1:8]
    l2 = w[8:15]

    try:
        list1 = map(float, l1)
        list2 = map(float, l2)
    except ValueError:
        print 'Line {i} is corrupt!'.format(i = index)'
        break

    result = stats.ttest_ind(list1, list2)
    print result[1]

How do I convert csv file to rdd

How about this?

val Delimeter = ","
val textFile = sc.textFile("data.csv").map(line => line.split(Delimeter))

In NetBeans how do I change the Default JDK?

If I remember correctly, you'll need to set the netbeans_jdkhome property in your netbeans config file. Should be in your etc/netbeans.conf file.

Programmatically get the version number of a DLL

Assembly assembly = Assembly.LoadFrom("MyAssembly.dll");
Version ver = assembly.GetName().Version;

Important: It should be noted that this is not the best answer to the original question. Don't forget to read more on this page.

Is Eclipse the best IDE for Java?

I'd have to vote for Netbeans as the best one currently. Eclipse is decent, but right now Netbeans is better.

How to set editable true/false EditText in Android programmatically?

An easy and safe method:

editText.clearFocus();
editText.setFocusable(false);

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

Hope this will help someone... Here's a little PHP script I wrote in case you need to copy some columns but not others, and/or the columns are not in the same order on both tables. As long as the columns are named the same, this will work. So if table A has [userid, handle, something] and tableB has [userID, handle, timestamp], then you'd "SELECT userID, handle, NOW() as timestamp FROM tableA", then get the result of that, and pass the result as the first parameter to this function ($z). $toTable is a string name for the table you're copying to, and $link_identifier is the db you're copying to. This is relatively fast for small sets of data. Not suggested that you try to move more than a few thousand rows at a time this way in a production setting. I use this primarily to back up data collected during a session when a user logs out, and then immediately clear the data from the live db to keep it slim.

 function mysql_multirow_copy($z,$toTable,$link_identifier) {
            $fields = "";
            for ($i=0;$i<mysql_num_fields($z);$i++) {
                if ($i>0) {
                    $fields .= ",";
                }
                $fields .= mysql_field_name($z,$i);
            }
            $q = "INSERT INTO $toTable ($fields) VALUES";
            $c = 0;
            mysql_data_seek($z,0); //critical reset in case $z has been parsed beforehand. !
            while ($a = mysql_fetch_assoc($z)) {
                foreach ($a as $key=>$as) {
                    $a[$key] = addslashes($as);
                    next ($a);
                }
                if ($c>0) {
                    $q .= ",";
                }
                $q .= "('".implode(array_values($a),"','")."')";
                $c++;
            }
            $q .= ";";
            $z = mysql_query($q,$link_identifier);
            return ($q);
        }

Scroll event listener javascript

Wont the below basic approach doesn't suffice your requirements?

HTML Code having a div

<div id="mydiv" onscroll='myMethod();'>


JS will have below code

function myMethod(){ alert(1); }

Example for boost shared_mutex (multiple reads/one write)?

Great response by Jim Morris, I stumbled upon this and it took me a while to figure. Here is some simple code that shows that after submitting a "request" for a unique_lock boost (version 1.54) blocks all shared_lock requests. This is very interesting as it seems to me that choosing between unique_lock and upgradeable_lock allows if we want write priority or no priority.

Also (1) in Jim Morris's post seems to contradict this: Boost shared_lock. Read preferred?

#include <iostream>
#include <boost/thread.hpp>

using namespace std;

typedef boost::shared_mutex Lock;
typedef boost::unique_lock< Lock > UniqueLock;
typedef boost::shared_lock< Lock > SharedLock;

Lock tempLock;

void main2() {
    cout << "10" << endl;
    UniqueLock lock2(tempLock); // (2) queue for a unique lock
    cout << "11" << endl;
    boost::this_thread::sleep(boost::posix_time::seconds(1));
    lock2.unlock();
}

void main() {
    cout << "1" << endl;
    SharedLock lock1(tempLock); // (1) aquire a shared lock
    cout << "2" << endl;
    boost::thread tempThread(main2);
    cout << "3" << endl;
    boost::this_thread::sleep(boost::posix_time::seconds(3));
    cout << "4" << endl;
    SharedLock lock3(tempLock); // (3) try getting antoher shared lock, deadlock here
    cout << "5" << endl;
    lock1.unlock();
    lock3.unlock();
}

In Visual Studio C++, what are the memory allocation representations?

There's actually quite a bit of useful information added to debug allocations. This table is more complete:

http://www.nobugs.org/developer/win32/debug_crt_heap.html#table

Address  Offset After HeapAlloc() After malloc() During free() After HeapFree() Comments
0x00320FD8  -40    0x01090009    0x01090009     0x01090009    0x0109005A     Win32 heap info
0x00320FDC  -36    0x01090009    0x00180700     0x01090009    0x00180400     Win32 heap info
0x00320FE0  -32    0xBAADF00D    0x00320798     0xDDDDDDDD    0x00320448     Ptr to next CRT heap block (allocated earlier in time)
0x00320FE4  -28    0xBAADF00D    0x00000000     0xDDDDDDDD    0x00320448     Ptr to prev CRT heap block (allocated later in time)
0x00320FE8  -24    0xBAADF00D    0x00000000     0xDDDDDDDD    0xFEEEFEEE     Filename of malloc() call
0x00320FEC  -20    0xBAADF00D    0x00000000     0xDDDDDDDD    0xFEEEFEEE     Line number of malloc() call
0x00320FF0  -16    0xBAADF00D    0x00000008     0xDDDDDDDD    0xFEEEFEEE     Number of bytes to malloc()
0x00320FF4  -12    0xBAADF00D    0x00000001     0xDDDDDDDD    0xFEEEFEEE     Type (0=Freed, 1=Normal, 2=CRT use, etc)
0x00320FF8  -8     0xBAADF00D    0x00000031     0xDDDDDDDD    0xFEEEFEEE     Request #, increases from 0
0x00320FFC  -4     0xBAADF00D    0xFDFDFDFD     0xDDDDDDDD    0xFEEEFEEE     No mans land
0x00321000  +0     0xBAADF00D    0xCDCDCDCD     0xDDDDDDDD    0xFEEEFEEE     The 8 bytes you wanted
0x00321004  +4     0xBAADF00D    0xCDCDCDCD     0xDDDDDDDD    0xFEEEFEEE     The 8 bytes you wanted
0x00321008  +8     0xBAADF00D    0xFDFDFDFD     0xDDDDDDDD    0xFEEEFEEE     No mans land
0x0032100C  +12    0xBAADF00D    0xBAADF00D     0xDDDDDDDD    0xFEEEFEEE     Win32 heap allocations are rounded up to 16 bytes
0x00321010  +16    0xABABABAB    0xABABABAB     0xABABABAB    0xFEEEFEEE     Win32 heap bookkeeping
0x00321014  +20    0xABABABAB    0xABABABAB     0xABABABAB    0xFEEEFEEE     Win32 heap bookkeeping
0x00321018  +24    0x00000010    0x00000010     0x00000010    0xFEEEFEEE     Win32 heap bookkeeping
0x0032101C  +28    0x00000000    0x00000000     0x00000000    0xFEEEFEEE     Win32 heap bookkeeping
0x00321020  +32    0x00090051    0x00090051     0x00090051    0xFEEEFEEE     Win32 heap bookkeeping
0x00321024  +36    0xFEEE0400    0xFEEE0400     0xFEEE0400    0xFEEEFEEE     Win32 heap bookkeeping
0x00321028  +40    0x00320400    0x00320400     0x00320400    0xFEEEFEEE     Win32 heap bookkeeping
0x0032102C  +44    0x00320400    0x00320400     0x00320400    0xFEEEFEEE     Win32 heap bookkeeping

Random number generator only generating one random number

Always get a positive random number.

 var nexnumber = Guid.NewGuid().GetHashCode();
        if (nexnumber < 0)
        {
            nexnumber *= -1;
        }

How can I do DNS lookups in Python, including referring to /etc/hosts?

I found this way to expand a DNS RR hostname that expands into a list of IPs, into the list of member hostnames:

#!/usr/bin/python

def expand_dnsname(dnsname):
    from socket import getaddrinfo
    from dns import reversename, resolver
    namelist = [ ]
    # expand hostname into dict of ip addresses
    iplist = dict()
    for answer in getaddrinfo(dnsname, 80):
        ipa = str(answer[4][0])
        iplist[ipa] = 0
    # run through the list of IP addresses to get hostnames
    for ipaddr in sorted(iplist):
        rev_name = reversename.from_address(ipaddr)
        # run through all the hostnames returned, ignoring the dnsname
        for answer in resolver.query(rev_name, "PTR"):
            name = str(answer)
            if name != dnsname:
                # add it to the list of answers
                namelist.append(name)
                break
    # if no other choice, return the dnsname
    if len(namelist) == 0:
        namelist.append(dnsname)
    # return the sorted namelist
    namelist = sorted(namelist)
    return namelist

namelist = expand_dnsname('google.com.')
for name in namelist:
    print name

Which, when I run it, lists a few 1e100.net hostnames:

Firebase FCM notifications click_action payload

Well this is clear from firebase docs that your onMessageReceived will not work when app is in background.

When your app is in background and click on your notification your default launcher will be launched. To launch your desired activity you need to specify click_action in your notification payload.

$noti = array
    (
    'icon' => 'new',
    'title' => 'title',
    'body' => 'new msg',
    'click_action' => 'your activity name comes here'
); 

And in your android.manifest file

Add the following code where you registered your activity

     <activity
                android:name="your activity name">
                <intent-filter>
                    <action android:name="your activity name" />
                   <category android:name="android.intent.category.DEFAULT"/>
               </intent-filter>
   </activity>

changing visibility using javascript

function loadpage (page_request, containerid)
{
  var loading = document.getElementById ( "loading" ) ;

  // when connecting to server
  if ( page_request.readyState == 1 )
      loading.style.visibility = "visible" ;

  // when loaded successfully
  if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
  {
      document.getElementById(containerid).innerHTML=page_request.responseText ;
      loading.style.visibility = "hidden" ;
  }
}

How do I pass data between Activities in Android application?

Updated Note that I had mentioned the use of SharedPreference. It has a simple API and is accessible across an application's activities. But this is a clumsy solution, and is a security risk if you pass around sensitive data. It's best to use intents. It has an extensive list of overloaded methods that can be used to better transfer many different data types between activities. Have a look at intent.putExtra. This link presents the use of putExtra quite well.

In passing data between activities, my preferred approach is to create a static method for the relevant activity that includes the required parameters launch the intent. Which then provides easily setup and retrieve parameters. So it can look like this

public class MyActivity extends Activity {
    public static final String ARG_PARAM1 = "arg_param1";
...
public static getIntent(Activity from, String param1, Long param2...) {
    Intent intent = new Intent(from, MyActivity.class);
        intent.putExtra(ARG_PARAM1, param1);
        intent.putExtra(ARG_PARAM2, param2);
        return intent;
}

....
// Use it like this.
startActivity(MyActvitiy.getIntent(FromActivity.this, varA, varB, ...));
...

Then you can create an intent for the intended activity and ensure you have all the parameters. You can adapt for fragments to. A simple example above, but you get the idea.

Matplotlib discrete colorbar

This topic is well covered already but I wanted to add something more specific : I wanted to be sure that a certain value would be mapped to that color (not to any color).

It is not complicated but as it took me some time, it might help others not lossing as much time as I did :)

import matplotlib
from matplotlib.colors import ListedColormap

# Let's design a dummy land use field
A = np.reshape([7,2,13,7,2,2], (2,3))
vals = np.unique(A)

# Let's also design our color mapping: 1s should be plotted in blue, 2s in red, etc...
col_dict={1:"blue",
          2:"red",
          13:"orange",
          7:"green"}

# We create a colormar from our list of colors
cm = ListedColormap([col_dict[x] for x in col_dict.keys()])

# Let's also define the description of each category : 1 (blue) is Sea; 2 (red) is burnt, etc... Order should be respected here ! Or using another dict maybe could help.
labels = np.array(["Sea","City","Sand","Forest"])
len_lab = len(labels)

# prepare normalizer
## Prepare bins for the normalizer
norm_bins = np.sort([*col_dict.keys()]) + 0.5
norm_bins = np.insert(norm_bins, 0, np.min(norm_bins) - 1.0)
print(norm_bins)
## Make normalizer and formatter
norm = matplotlib.colors.BoundaryNorm(norm_bins, len_lab, clip=True)
fmt = matplotlib.ticker.FuncFormatter(lambda x, pos: labels[norm(x)])

# Plot our figure
fig,ax = plt.subplots()
im = ax.imshow(A, cmap=cm, norm=norm)

diff = norm_bins[1:] - norm_bins[:-1]
tickz = norm_bins[:-1] + diff / 2
cb = fig.colorbar(im, format=fmt, ticks=tickz)
fig.savefig("example_landuse.png")
plt.show()

enter image description here

favicon not working in IE

Should anyone make it down to this answer:

Same issue: didn't work in IE (including IE 10), worked everywhere else.

Turns out that the file was not a "real" .ico file. I fixed this by uploading it to http://www.favicon.cc/ and then downloading it again.

First I tested it by generating a random .ico file on this site and using that instead of my original file. Saw that it worked.

How to encode the plus (+) symbol in a URL

The + character has a special meaning in a URL => it means whitespace - . If you want to use the literal + sign, you need to URL encode it to %2b:

body=Hi+there%2bHello+there

Here's an example of how you could properly generate URLs in .NET:

var uriBuilder = new UriBuilder("https://mail.google.com/mail");

var values = HttpUtility.ParseQueryString(string.Empty);
values["view"] = "cm";
values["tf"] = "0";
values["to"] = "[email protected]";
values["su"] = "some subject";
values["body"] = "Hi there+Hello there";

uriBuilder.Query = values.ToString();

Console.WriteLine(uriBuilder.ToString());

The result

https://mail.google.com:443/mail?view=cm&tf=0&to=someemail%40somedomain.com&su=some+subject&body=Hi+there%2bHello+there

How to set the project name/group/version, plus {source,target} compatibility in the same file?

Apparently this would be possible in settings.gradle with something like this.

rootProject.name = 'someName'
gradle.rootProject {
    it.sourceCompatibility = '1.7'
}

I recently received advice that a project property can be set by using a closure which will be called later when the Project is available.

How to do an array of hashmaps?

The Java Language Specification, section 15.10, states:

An array creation expression creates an object that is a new array whose elements are of the type specified by the PrimitiveType or ClassOrInterfaceType. It is a compile-time error if the ClassOrInterfaceType does not denote a reifiable type (§4.7).

and

The rules above imply that the element type in an array creation expression cannot be a parameterized type, other than an unbounded wildcard.

The closest you can do is use an unchecked cast, either from the raw type, as you have done, or from an unbounded wildcard:

 HashMap<String, String>[] responseArray = (Map<String, String>[]) new HashMap<?,?>[games.size()];

Your version is clearly better :-)

Sorting a Data Table

After setting the sort expression on the DefaultView (table.DefaultView.Sort = "Town ASC, Cutomer ASC" ) you should loop over the table using the DefaultView not the DataTable instance itself

foreach(DataRowView r in table.DefaultView)
{
    //... here you get the rows in sorted order
    Console.WriteLine(r["Town"].ToString());
}

Using the Select method of the DataTable instead, produces an array of DataRow. This array is sorted as from your request, not the DataTable

DataRow[] rowList = table.Select("", "Town ASC, Cutomer ASC");
foreach(DataRow r in rowList)
{
    Console.WriteLine(r["Town"].ToString());
}

Comparing chars in Java

Option 2 will work. You could also use a Set<Character> or

char[] myCharSet = new char[] {'A', 'B', 'C', ...};
Arrays.sort(myCharSet);
if (Arrays.binarySearch(myCharSet, symbol) >= 0) { ... }

Transition color fade on hover?

What do you want to fade? The background or color attribute?

Currently you're changing the background color, but telling it to transition the color property. You can use all to transition all properties.

.clicker { 
    -moz-transition: all .2s ease-in;
    -o-transition: all .2s ease-in;
    -webkit-transition: all .2s ease-in;
    transition: all .2s ease-in;
    background: #f5f5f5; 
    padding: 20px;
}

.clicker:hover { 
    background: #eee;
}

Otherwise just use transition: background .2s ease-in.

Why must wait() always be in synchronized block

A wait() only makes sense when there is also a notify(), so it's always about communication between threads, and that needs synchronization to work correctly. One could argue that this should be implicit, but that would not really help, for the following reason:

Semantically, you never just wait(). You need some condition to be satsified, and if it is not, you wait until it is. So what you really do is

if(!condition){
    wait();
}

But the condition is being set by a separate thread, so in order to have this work correctly you need synchronization.

A couple more things wrong with it, where just because your thread quit waiting doesn't mean the condition you are looking for is true:

  • You can get spurious wakeups (meaning that a thread can wake up from waiting without ever having received a notification), or

  • The condition can get set, but a third thread makes the condition false again by the time the waiting thread wakes up (and reacquires the monitor).

To deal with these cases what you really need is always some variation of this:

synchronized(lock){
    while(!condition){
        lock.wait();
    }
}

Better yet, don't mess with the synchronization primitives at all and work with the abstractions offered in the java.util.concurrent packages.

Difference between "include" and "require" in php

<?PHP
echo "Firstline";
include('classes/connection.php');
echo "I will run if include but not on Require";
?>

A very simple Practical example with code. The first echo will be displayed. No matter you use include or require because its runs before include or required.

To check the result, In second line of a code intentionally provide the wrong path to the file or make error in file name. Thus the second echo to be displayed or not will be totally dependent on whether you use require or include.

If you use require the second echo will not execute but if you use include not matter what error comes you will see the result of second echo too.

How to represent matrices in python

Python doesn't have matrices. You can use a list of lists or NumPy

C# declare empty string array

Your syntax is wrong:

string[] arr = new string[]{};

or

string[] arr = new string[0];

How can I add a new column and data to a datatable that already contains data?

Should it not be foreach instead of for!?

//call SQL helper class to get initial data  
DataTable dt = sql.ExecuteDataTable("sp_MyProc"); 

dt.Columns.Add("MyRow", **typeof**(System.Int32)); 

foreach(DataRow dr in dt.Rows) 
{ 
    //need to set value to MyRow column 
    dr["MyRow"] = 0;   // or set it to some other value 
} 

How to upload a file in Django?

Extending on Henry's example:

import tempfile
import shutil

FILE_UPLOAD_DIR = '/home/imran/uploads'

def handle_uploaded_file(source):
    fd, filepath = tempfile.mkstemp(prefix=source.name, dir=FILE_UPLOAD_DIR)
    with open(filepath, 'wb') as dest:
        shutil.copyfileobj(source, dest)
    return filepath

You can call this handle_uploaded_file function from your view with the uploaded file object. This will save the file with a unique name (prefixed with filename of the original uploaded file) in filesystem and return the full path of saved file. You can save the path in database, and do something with the file later.

How to send a stacktrace to log4j?

This answer may be not related to the question asked but related to title of the question.

public class ThrowableTest {

    public static void main(String[] args) {

        Throwable createdBy = new Throwable("Created at main()");
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PrintWriter pw = new PrintWriter(os);
        createdBy.printStackTrace(pw);
        try {
            pw.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.debug(os.toString());
    }
}

OR

public static String getStackTrace (Throwable t)
{
    StringWriter stringWriter = new StringWriter();
    PrintWriter  printWriter  = new PrintWriter(stringWriter);
    t.printStackTrace(printWriter);
    printWriter.close();    //surprise no IO exception here
    try {
        stringWriter.close();
    }
    catch (IOException e) {
    }
    return stringWriter.toString();
}

OR

StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
for(StackTraceElement stackTrace: stackTraceElements){
    logger.debug(stackTrace.getClassName()+ "  "+ stackTrace.getMethodName()+" "+stackTrace.getLineNumber());
}

Android: how to refresh ListView contents?

I'm doing the same thing using invalidateViews() and that works for me. If you want it to invalidate immediately you could try calling postInvalidate after calling invalidateViews.

Is there a way to view past mysql queries with phpmyadmin?

OK so I know I'm a little late and some of the above answers are great stuff.

As little extra though, while in any PHPMyAdmin page:

  1. Click SQL tab
  2. Click 'Get auto saved query'

this will then show your last entered query.

Difference between left join and right join in SQL Server

Select * from Table1 left join Table2 ...

and

Select * from Table2 right join Table1 ...

are indeed completely interchangeable. Try however Table2 left join Table1 (or its identical pair, Table1 right join Table2) to see a difference. This query should give you more rows, since Table2 contains a row with an id which is not present in Table1.

Array as session variable

Yes, you can put arrays in sessions, example:

$_SESSION['name_here'] = $your_array;

Now you can use the $_SESSION['name_here'] on any page you want but make sure that you put the session_start() line before using any session functions, so you code should look something like this:

 session_start();
 $_SESSION['name_here'] = $your_array;

Possible Example:

 session_start();
 $_SESSION['name_here'] = $_POST;

Now you can get field values on any page like this:

 echo $_SESSION['name_here']['field_name'];

As for the second part of your question, the session variables remain there unless you assign different array data:

 $_SESSION['name_here'] = $your_array;

Session life time is set into php.ini file.

More Info Here

How to make the division of 2 ints produce a float instead of another int?

JLS Standard

JLS 7 15.17.2. Division Operator / says:

Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d · q| = |n|. Moreover, q is positive when |n| = |d| and n and d have the same sign, but q is negative when |n| = |d| and n and d have opposite signs.

This is why 1/2 does not give a float.

Converting just either one to float as in (float)1/2 suffices because 15.17. Multiplicative Operators says:

Binary numeric promotion is performed on the operands

and 5.6.2. Binary Numeric Promotion says:

  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to float

mysql query order by multiple items

Sort by picture and then by activity:

SELECT some_cols
FROM `prefix_users`
WHERE (some conditions)
ORDER BY pic_set, last_activity DESC;

ORA-01031: insufficient privileges when selecting view

Q. When is the "with grant option" required ?

A. when you have a view executed from a third schema.

Example: schema DSDSW has a view called view_name

a) that view selects from a table in another schema  (FDR.balance)
b) a third shema  X_WORK  tries to select  from that view

Typical grants: grant select on dsdw.view_name to dsdw_select_role; grant dsdw_select_role to fdr;

But: fdr gets select count(*) from dsdw.view_name; ERROR at line 1: ORA-01031: insufficient privileges

issue the grant:

grant select on fdr.balance to dsdw with grant option;

now fdr: select count(*) from dsdw.view_name; 5 rows

Centos/Linux setting logrotate to maximum file size for all logs

As mentioned by Zeeshan, the logrotate options size, minsize, maxsize are triggers for rotation.

To better explain it. You can run logrotate as often as you like, but unless a threshold is reached such as the filesize being reached or the appropriate time passed, the logs will not be rotated.

The size options do not ensure that your rotated logs are also of the specified size. To get them to be close to the specified size you need to call the logrotate program sufficiently often. This is critical.

For log files that build up very quickly (e.g. in the hundreds of MB a day), unless you want them to be very large you will need to ensure logrotate is called often! this is critical.

Therefore to stop your disk filling up with multi-gigabyte log files you need to ensure logrotate is called often enough, otherwise the log rotation will not work as well as you want.

on Ubuntu, you can easily switch to hourly rotation by moving the script /etc/cron.daily/logrotate to /etc/cron.hourly/logrotate

Or add

*/5 * * * * /etc/cron.daily/logrotate 

To your /etc/crontab file. To run it every 5 minutes.

The size option ignores the daily, weekly, monthly time options. But minsize & maxsize take it into account.

The man page is a little confusing there. Here's my explanation.

minsize rotates only when the file has reached an appropriate size and the set time period has passed. e.g. minsize 50MB + daily If file reaches 50MB before daily time ticked over, it'll keep growing until the next day.

maxsize will rotate when the log reaches a set size or the appropriate time has passed. e.g. maxsize 50MB + daily. If file is 50MB and we're not at the next day yet, the log will be rotated. If the file is only 20MB and we roll over to the next day then the file will be rotated.

size will rotate when the log > size. Regardless of whether hourly/daily/weekly/monthly is specified. So if you have size 100M - it means when your log file is > 100M the log will be rotated if logrotate is run when this condition is true. Once it's rotated, the main log will be 0, and a subsequent run will do nothing.

So in the op's case. Specficially 50MB max I'd use something like the following:

/var/log/logpath/*.log {
    maxsize 50M
    hourly
    missingok
    rotate 8
    compress
    notifempty
    nocreate
}

Which means he'd create 8hrs of logs max. And there would be 8 of them at no more than 50MB each. Since he's saying that he's getting multi gigabytes each day and assuming they build up at a fairly constant rate, and maxsize is used he'll end up with around close to the max reached for each file. So they will be likely close to 50MB each. Given the volume they build, he would need to ensure that logrotate is run often enough to meet the target size.

Since I've put hourly there, we'd need logrotate to be run a minimum of every hour. But since they build up to say 2 gigabytes per day and we want 50MB... assuming a constant rate that's 83MB per hour. So you can imagine if we run logrotate every hour, despite setting maxsize to 50 we'll end up with 83MB log's in that case. So in this instance set the running to every 30 minutes or less should be sufficient.

Ensure logrotate is run every 30 mins.

*/30 * * * * /etc/cron.daily/logrotate 

jquery $(this).id return Undefined

this : is the DOM Element $(this) : Jquery objct, which wrapped with Dom Element, you can check this answer also this vs $(this)

try like this Attr(). Get the value of an attribute for the first element in the set of matched elements.

$(document).ready(function () {
    $(".inputs").click(function () {
         alert(" or " + $(this).attr("id"));

    });
});

Data binding for TextBox

You need a bindingsource object to act as an intermediary and assist in the binding. Then instead of updating the user interface, update the underlining model.

var model = (Fruit) bindingSource1.DataSource;

model.FruitType = "oranges";

bindingSource.ResetBindings();

Read up on BindingSource and simple data binding for Windows Forms.

How to create EditText accepts Alphabets only in android?

Try This Method

For Java :

EditText yourEditText = (EditText) findViewById(R.id.yourEditText);
yourEditText.setFilters(new InputFilter[] {
new InputFilter() {
    @Override
    public CharSequence filter(CharSequence cs, int start,
                int end, Spanned spanned, int dStart, int dEnd) {
        // TODO Auto-generated method stub
        if(cs.equals("")){ // for backspace
             return cs;
        }
        if(cs.toString().matches("[a-zA-Z ]+")){
             return cs;
        }
        return "";
    }
}});

For Kotlin :

 val yourEditText = findViewById<View>(android.R.id.yourEditText) as EditText
    val reges = Regex("^[0-9a-zA-Z ]+$")
    //this will allow user to only write letter and white space
    yourEditText.filters = arrayOf<InputFilter>(
        object : InputFilter {
            override fun filter(
                cs: CharSequence, start: Int,
                end: Int, spanned: Spanned?, dStart: Int, dEnd: Int,
            ): CharSequence? {
                if (cs == "") { // for backspace
                    return cs
                }
                return if (cs.toString().matches(reges)) {
                    cs
                } else ""
            }
        }
    )

Why an abstract class implementing an interface can miss the declaration/implementation of one of the interface's methods?

Perfectly fine.
You can't instantiate abstract classes.. but abstract classes can be used to house common implementations for m1() and m3().
So if m2() implementation is different for each implementation but m1 and m3 are not. You could create different concrete IAnything implementations with just the different m2 implementation and derive from AbstractThing -- honoring the DRY principle. Validating if the interface is completely implemented for an abstract class is futile..

Update: Interestingly, I find that C# enforces this as a compile error. You are forced to copy the method signatures and prefix them with 'abstract public' in the abstract base class in this scenario.. (something new everyday:)

MySQL Insert into multiple tables? (Database normalization?)

No, you can't insert into multiple tables in one MySQL command. You can however use transactions.

BEGIN;
INSERT INTO users (username, password)
  VALUES('test', 'test');
INSERT INTO profiles (userid, bio, homepage) 
  VALUES(LAST_INSERT_ID(),'Hello world!', 'http://www.stackoverflow.com');
COMMIT;

Have a look at LAST_INSERT_ID() to reuse autoincrement values.

Edit: you said "After all this time trying to figure it out, it still doesn't work. Can't I simply put the just generated ID in a $var and put that $var in all the MySQL commands?"

Let me elaborate: there are 3 possible ways here:

  1. In the code you see above. This does it all in MySQL, and the LAST_INSERT_ID() in the second statement will automatically be the value of the autoincrement-column that was inserted in the first statement.

    Unfortunately, when the second statement itself inserts rows in a table with an auto-increment column, the LAST_INSERT_ID() will be updated to that of table 2, and not table 1. If you still need that of table 1 afterwards, we will have to store it in a variable. This leads us to ways 2 and 3:

  2. Will stock the LAST_INSERT_ID() in a MySQL variable:

    INSERT ...
    SELECT LAST_INSERT_ID() INTO @mysql_variable_here;
    INSERT INTO table2 (@mysql_variable_here, ...);
    INSERT INTO table3 (@mysql_variable_here, ...);
    
  3. Will stock the LAST_INSERT_ID() in a php variable (or any language that can connect to a database, of your choice):

    • INSERT ...
    • Use your language to retrieve the LAST_INSERT_ID(), either by executing that literal statement in MySQL, or using for example php's mysql_insert_id() which does that for you
    • INSERT [use your php variable here]

WARNING

Whatever way of solving this you choose, you must decide what should happen should the execution be interrupted between queries (for example, your database-server crashes). If you can live with "some have finished, others not", don't read on.

If however you decide "either all queries finish, or none finish - I do not want rows in some tables but no matching rows in others, I always want my database tables to be consistent", you need to wrap all statements in a transaction. That's why I used the BEGIN and COMMIT here.

Comment again if you need more info :)

How to open a new tab in GNOME Terminal from command line?

To bring together a number of different points above, here's a script that will run any arguments passed to the script vim new_tab.sh:

#!/bin/bash
#
# Dependencies:
#   sudo apt install xdotool

WID=$(xprop -root | grep "_NET_ACTIVE_WINDOW(WINDOW)"| awk '{print $5}')
xdotool windowfocus $WID
xdotool key ctrl+shift+t
wmctrl -i -a $WID
sleep 1; xdotool type --delay 1 --clearmodifiers "$@"; xdotool key Return;

Next make it executable: chmod +x new_tab.sh

Now you can use it to run whatever you'd like in a new tab: ./new_tab.sh "watch ls -l"

How to do a deep comparison between 2 objects with lodash?

If you need only key comparison:

 _.reduce(a, function(result, value, key) {
     return b[key] === undefined ? key : []
  }, []);

How can I undo git reset --hard HEAD~1?

Made a tiny script to make it slightly easier to find the commit one is looking for:

git fsck --lost-found | grep commit | cut -d ' ' -f 3 | xargs -i git show \{\} | egrep '^commit |Date:'

Yes, it can be made considerably prettier with awk or something like it, but it's simple and I just needed it. Might save someone else 30 seconds.

Android - How to achieve setOnClickListener in Kotlin?

In case anyone else wants to achieve this while using binding. If the id of your view is button_save then this code can be written, taking advantage of the kotlin apply syntax

binding.apply {
         button_save.setOnClickListener {
             //dosomething
         }
     }

Take note binding is the name of the binding instance created for an xml file . Full code is below if you are writing the code in fragment. Activity works similarly

 private lateinit var binding: FragmentProfileBinding

  override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    binding = FragmentProfileBinding.inflate(inflater, container, false)
 
  return binding.root
}

// onActivityCreated is deprecated in fragment
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
   binding.apply {
     button_save.setOnClickListener {
         //dosomething
     }
     }
 }

How to find an object in an ArrayList by property

Following with Oleg answer, if you want to find ALL objects in a List filtered by a property, you could do something like:

//Search into a generic list ALL items with a generic property
public final class SearchTools {
       public static <T> List<T> findByProperty(Collection<T> col, Predicate<T> filter) {
           List<T> filteredList = (List<T>) col.stream().filter(filter).collect(Collectors.toList());
           return filteredList;
     }

//Search in the list "listItems" ALL items of type "Item" with the specific property "iD_item=itemID"
public static final class ItemTools {
         public static List<Item> findByItemID(Collection<Item> listItems, String itemID) {
             return SearchTools.findByProperty(listItems, item -> itemID.equals(item.getiD_Item()));
         }
     }
}

and similarly if you want to filter ALL items in a HashMap with a certain Property

//Search into a MAP ALL items with a given property
public final class SearchTools {
       public static <T> HashMap<String,T> filterByProperty(HashMap<String,T> completeMap, Predicate<? super Map.Entry<String,T>> filter) {
           HashMap<String,T> filteredList = (HashMap<String,T>) completeMap.entrySet().stream()
                                .filter(filter)
                                .collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue()));
           return filteredList;
     }

     //Search into the MAP ALL items with specific properties
public static final class ItemTools {

        public static HashMap<String,Item> filterByParentID(HashMap<String,Item> mapItems, String parentID) {
            return SearchTools.filterByProperty(mapItems, mapItem -> parentID.equals(mapItem.getValue().getiD_Parent()));
        }

        public static HashMap<String,Item> filterBySciName(HashMap<String,Item> mapItems, String sciName) {
            return SearchTools.filterByProperty(mapItems, mapItem -> sciName.equals(mapItem.getValue().getSciName()));
        }
    }

Find control by name from Windows Forms controls

You can use:

f.Controls[name];

Where f is your form variable. That gives you the control with name name.

How can I record a Video in my Android App.?

Here is another example which is working

public class EnregistrementVideoStackActivity extends Activity implements SurfaceHolder.Callback {
    private SurfaceHolder surfaceHolder;
    private SurfaceView surfaceView;
    public MediaRecorder mrec = new MediaRecorder();
    private Button startRecording = null;

    File video;
    private Camera mCamera;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera_surface);
        Log.i(null , "Video starting");
        startRecording = (Button)findViewById(R.id.buttonstart);
        mCamera = Camera.open();
        surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        menu.add(0, 0, 0, "StartRecording");
        menu.add(0, 1, 0, "StopRecording");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
        case 0:
            try {
                startRecording();
            } catch (Exception e) {
                String message = e.getMessage();
                Log.i(null, "Problem Start"+message);
                mrec.release();
            }
            break;

        case 1: //GoToAllNotes
            mrec.stop();
            mrec.release();
            mrec = null;
            break;

        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    protected void startRecording() throws IOException 
    {
        mrec = new MediaRecorder();  // Works well
        mCamera.unlock();

        mrec.setCamera(mCamera);

        mrec.setPreviewDisplay(surfaceHolder.getSurface());
        mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mrec.setAudioSource(MediaRecorder.AudioSource.MIC); 

        mrec.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
        mrec.setPreviewDisplay(surfaceHolder.getSurface());
        mrec.setOutputFile("/sdcard/zzzz.3gp"); 

        mrec.prepare();
        mrec.start();
    }

    protected void stopRecording() {
        mrec.stop();
        mrec.release();
        mCamera.release();
    }

    private void releaseMediaRecorder(){
        if (mrec != null) {
            mrec.reset();   // clear recorder configuration
            mrec.release(); // release the recorder object
            mrec = null;
            mCamera.lock();           // lock camera for later use
        }
    }

    private void releaseCamera(){
        if (mCamera != null){
            mCamera.release();        // release the camera for other applications
            mCamera = null;
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (mCamera != null){
            Parameters params = mCamera.getParameters();
            mCamera.setParameters(params);
        }
        else {
            Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
            finish();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mCamera.stopPreview();
        mCamera.release();
    }
}

camera_surface.xml

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

<SurfaceView
    android:id="@+id/surface_camera"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1" />

<Button
    android:id="@+id/buttonstart"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/record_start" />

</RelativeLayout>

And of course include these permission in manifest:

<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />