Programs & Examples On #Couchone

Ways to implement data versioning in MongoDB

If you're looking for a ready-to-roll solution -

Mongoid has built in simple versioning

http://mongoid.org/en/mongoid/docs/extras.html#versioning

mongoid-history is a Ruby plugin that provides a significantly more complicated solution with auditing, undo and redo

https://github.com/aq1018/mongoid-history

How to access form methods and controls from a class in C#?

You are trying to access the class as opposed to the object. That statement can be confusing to beginners, but you are effectively trying to open your house door by picking up the door on your house plans.

If you actually wanted to access the form components directly from a class (which you don't) you would use the variable that instantiates your form.

Depending on which way you want to go you'd be better of either sending the text of a control or whatever to a method in your classes eg

public void DoSomethingWithText(string formText)
{
   // do something text in here
}

or exposing properties on your form class and setting the form text in there - eg

string SomeProperty
{
   get 
   {
      return textBox1.Text;
   }
   set
   {
      textBox1.Text = value;
   }
}

passing several arguments to FUN of lapply (and others *apply)

If you look up the help page, one of the arguments to lapply is the mysterious .... When we look at the Arguments section of the help page, we find the following line:

...: optional arguments to ‘FUN’.

So all you have to do is include your other argument in the lapply call as an argument, like so:

lapply(input, myfun, arg1=6)

and lapply, recognizing that arg1 is not an argument it knows what to do with, will automatically pass it on to myfun. All the other apply functions can do the same thing.

An addendum: You can use ... when you're writing your own functions, too. For example, say you write a function that calls plot at some point, and you want to be able to change the plot parameters from your function call. You could include each parameter as an argument in your function, but that's annoying. Instead you can use ... (as an argument to both your function and the call to plot within it), and have any argument that your function doesn't recognize be automatically passed on to plot.

Adding :default => true to boolean in existing Rails column

As a variation on the accepted answer you could also use the change_column_default method in your migrations:

def up
  change_column_default :profiles, :show_attribute, true
end

def down
  change_column_default :profiles, :show_attribute, nil
end

Rails API-docs

JavaScript query string

I like to keep it simple, readable and small.

function searchToObject(search) {
    var pairs = search.substring(1).split("&"),
        obj = {}, pair;

    for (var i in pairs) {
        if (pairs[i] === "") continue;
        pair = pairs[i].split("=");
        obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
    }
    return obj;
}

searchToObject(location.search);

Example:

searchToObject('?query=myvalue')['query']; // spits out: 'myvalue'

A regex for version number parsing

It seems pretty hard to have a regex that does exactly what you want (i.e. accept only the cases that you need and reject all others and return some groups for the three components). I've give it a try and come up with this:

^(\*|(\d+(\.(\d+(\.(\d+|\*))?|\*))?))$

IMO (I've not tested extensively) this should work fine as a validator for the input, but the problem is that this regex doesn't offer a way of retrieving the components. For that you still have to do a split on period.

This solution is not all-in-one, but most times in programming it doesn't need to. Of course this depends on other restrictions that you might have in your code.

How to create a GUID/UUID using iOS

I've uploaded my simple but fast implementation of a Guid class for ObjC here: obj-c GUID

Guid* guid = [Guid randomGuid];
NSLog("%@", guid.description);

It can parse to and from various string formats as well.

Can you remove elements from a std::list while iterating through it?

If you think of the std::list like a queue, then you can dequeue and enqueue all the items that you want to keep, but only dequeue (and not enqueue) the item you want to remove. Here's an example where I want to remove 5 from a list containing the numbers 1-10...

std::list<int> myList;

int size = myList.size(); // The size needs to be saved to iterate through the whole thing

for (int i = 0; i < size; ++i)
{
    int val = myList.back()
    myList.pop_back() // dequeue
    if (val != 5)
    {
         myList.push_front(val) // enqueue if not 5
    }
}

myList will now only have numbers 1-4 and 6-10.

Checking for empty or null List<string>

Try and use:

if(myList.Any())
{

}

Note: this assmumes myList is not null.

WPF Add a Border to a TextBlock

A TextBlock does not actually inherit from Control so it does not have properties that you would generally associate with a Control. Your best bet for adding a border in a style is to replace the TextBlock with a Label

See this link for more on the differences between a TextBlock and other Controls

Read String line by line

The easiest and most universal approach would be to just use the regex Linebreak matcher \R which matches Any Unicode linebreak sequence:

Pattern NEWLINE = Pattern.compile("\\R")
String lines[] = NEWLINE.split(input)

@see https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/regex/Pattern.html

403 Forbidden You don't have permission to access /folder-name/ on this server

if permission issue and you have ssh access in root folder

find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;

will resolve your error

How to convert an Stream into a byte[] in C#?

Call next function like

byte[] m_Bytes = StreamHelper.ReadToEnd (mystream);

Function:

public static byte[] ReadToEnd(System.IO.Stream stream)
{
    long originalPosition = 0;

    if(stream.CanSeek)
    {
         originalPosition = stream.Position;
         stream.Position = 0;
    }

    try
    {
        byte[] readBuffer = new byte[4096];

        int totalBytesRead = 0;
        int bytesRead;

        while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
        {
            totalBytesRead += bytesRead;

            if (totalBytesRead == readBuffer.Length)
            {
                int nextByte = stream.ReadByte();
                if (nextByte != -1)
                {
                    byte[] temp = new byte[readBuffer.Length * 2];
                    Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                    Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                    readBuffer = temp;
                    totalBytesRead++;
                }
            }
        }

        byte[] buffer = readBuffer;
        if (readBuffer.Length != totalBytesRead)
        {
            buffer = new byte[totalBytesRead];
            Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
        }
        return buffer;
    }
    finally
    {
        if(stream.CanSeek)
        {
             stream.Position = originalPosition; 
        }
    }
}

How to remove duplicate values from a multi-dimensional array in PHP

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => john
        )

    [1] => Array
        (
            [id] => 2
            [name] => smith
        )

    [2] => Array
        (
            [id] => 3
            [name] => john
        )

    [3] => Array
        (
            [id] => 4
            [name] => robert
        )

)

$temp = array_unique(array_column($array, 'name'));
$unique_arr = array_intersect_key($array, $temp);

This will remove the duplicate names from array. unique by key

What does '--set-upstream' do?

git branch --set-upstream <<origin/branch>> is officially not supported anymore and is replaced by git branch --set-upstream-to <<origin/branch>>

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

1) When to use include directive ?

To prevent duplication of same output logic across multiple jsp's of the web app ,include mechanism is used ie.,to promote the re-usability of presentation logic include directive is used

  <%@ include file="abc.jsp" %>

when the above instruction is received by the jsp engine,it retrieves the source code of the abc.jsp and copy's the same inline in the current jsp. After copying translation is performed for the current page

Simply saying it is static instruction to jsp engine ie., whole source code of "abc.jsp" is copied into the current page

2) When to use include action ?

include tag doesn't include the source code of the included page into the current page instead the output generated at run time by the included page is included into the current page response

include tag functionality is similar to that of include mechanism of request dispatcher of servlet programming

include tag is run-time instruction to jsp engine ie., rather copying whole code into current page a method call is made to "abc.jsp" from current page

How to fill background image of an UIView

For Swift 3.0 use the following code:

    UIGraphicsBeginImageContext(self.view.frame.size)
    UIImage(named: "bg.png")?.drawAsPattern(in: self.view.bounds)
    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    self.view.backgroundColor = UIColor(patternImage: image)

How to go to a specific element on page?

The standard technique in plugin form would look something like this:

(function($) {
    $.fn.goTo = function() {
        $('html, body').animate({
            scrollTop: $(this).offset().top + 'px'
        }, 'fast');
        return this; // for chaining...
    }
})(jQuery);

Then you could just say $('#div_element2').goTo(); to scroll to <div id="div_element2">. Options handling and configurability is left as an exercise for the reader.

MVC pattern on Android

Android UI creation using layouts, resources, activities and intents is an implementation of the MVC pattern. Please see the following link for more on this - http://www.cs.otago.ac.nz/cosc346/labs/COSC346-lab2.2up.pdf

mirror for the pdf

How to embed an autoplaying YouTube video in an iframe?

Nowadays I include a new attribute "allow" on iframe tag, for example:

allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"

The final code is:

<iframe src="https://www.youtube.com/embed/[VIDEO-CODE]?autoplay=1" 
frameborder="0" style="width: 100%; height: 100%;"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"></iframe>

How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

This is the classic "unicode issue". I believe that explaining this is beyond the scope of a StackOverflow answer to completely explain what is happening.

It is well explained here.

In very brief summary, you have passed something that is being interpreted as a string of bytes to something that needs to decode it into Unicode characters, but the default codec (ascii) is failing.

The presentation I pointed you to provides advice for avoiding this. Make your code a "unicode sandwich". In Python 2, the use of from __future__ import unicode_literals helps.

Update: how can the code be fixed:

OK - in your variable "source" you have some bytes. It is not clear from your question how they got in there - maybe you read them from a web form? In any case, they are not encoded with ascii, but python is trying to convert them to unicode assuming that they are. You need to explicitly tell it what the encoding is. This means that you need to know what the encoding is! That is not always easy, and it depends entirely on where this string came from. You could experiment with some common encodings - for example UTF-8. You tell unicode() the encoding as a second parameter:

source = unicode(source, 'utf-8')

Convert timestamp in milliseconds to string formatted time in Java

I'll show you three ways to (a) get the minute field from a long value, and (b) print it using the Date format you want. One uses java.util.Calendar, another uses Joda-Time, and the last uses the java.time framework built into Java 8 and later.

The java.time framework supplants the old bundled date-time classes, and is inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.

The java.time framework is the way to go when using Java 8 and later. Otherwise, such as Android, use Joda-Time. The java.util.Date/.Calendar classes are notoriously troublesome and should be avoided.

java.util.Date & .Calendar

final long timestamp = new Date().getTime();

// with java.util.Date/Calendar api
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
// here's how to get the minutes
final int minutes = cal.get(Calendar.MINUTE);
// and here's how to get the String representation
final String timeString =
    new SimpleDateFormat("HH:mm:ss:SSS").format(cal.getTime());
System.out.println(minutes);
System.out.println(timeString);

Joda-Time

// with JodaTime 2.4
final DateTime dt = new DateTime(timestamp);
// here's how to get the minutes
final int minutes2 = dt.getMinuteOfHour();
// and here's how to get the String representation
final String timeString2 = dt.toString("HH:mm:ss:SSS");
System.out.println(minutes2);
System.out.println(timeString2);

Output:

24
09:24:10:254
24
09:24:10:254

java.time

long millisecondsSinceEpoch = 1289375173771L;
Instant instant = Instant.ofEpochMilli ( millisecondsSinceEpoch );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , ZoneOffset.UTC );

DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "HH:mm:ss:SSS" );
String output = formatter.format ( zdt );

System.out.println ( "millisecondsSinceEpoch: " + millisecondsSinceEpoch + " instant: " + instant + " output: " + output );

millisecondsSinceEpoch: 1289375173771 instant: 2010-11-10T07:46:13.771Z output: 07:46:13:771

RecyclerView - How to smooth scroll to top of item on a certain position?

I want to more fully address the issue of scroll duration, which, should you choose any earlier answer, will in fact will vary dramatically (and unacceptably) according to the amount of scrolling necessary to reach the target position from the current position .

To obtain a uniform scroll duration the velocity (pixels per millisecond) must account for the size of each individual item - and when the items are of non-standard dimension then a whole new level of complexity is added.

This may be why the RecyclerView developers deployed the too-hard basket for this vital aspect of smooth scrolling.

Assuming that you want a semi-uniform scroll duration, and that your list contains semi-uniform items then you will need something like this.

/** Smoothly scroll to specified position allowing for interval specification. <br>
 * Note crude deceleration towards end of scroll
 * @param rv        Your RecyclerView
 * @param toPos     Position to scroll to
 * @param duration  Approximate desired duration of scroll (ms)
 * @throws IllegalArgumentException */
private static void smoothScroll(RecyclerView rv, int toPos, int duration) throws IllegalArgumentException {
    int TARGET_SEEK_SCROLL_DISTANCE_PX = 10000;     // See androidx.recyclerview.widget.LinearSmoothScroller
    int itemHeight = rv.getChildAt(0).getHeight();  // Height of first visible view! NB: ViewGroup method!
    itemHeight = itemHeight + 33;                   // Example pixel Adjustment for decoration?
    int fvPos = ((LinearLayoutManager)rv.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
    int i = Math.abs((fvPos - toPos) * itemHeight);
    if (i == 0) { i = (int) Math.abs(rv.getChildAt(0).getY()); }
    final int totalPix = i;                         // Best guess: Total number of pixels to scroll
    RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(rv.getContext()) {
        @Override protected int getVerticalSnapPreference() {
            return LinearSmoothScroller.SNAP_TO_START;
        }
        @Override protected int calculateTimeForScrolling(int dx) {
            int ms = (int) ( duration * dx / (float)totalPix );
            // Now double the interval for the last fling.
            if (dx < TARGET_SEEK_SCROLL_DISTANCE_PX ) { ms = ms*2; } // Crude deceleration!
            //lg(format("For dx=%d we allot %dms", dx, ms));
            return ms;
        }
    };
    //lg(format("Total pixels from = %d to %d = %d [ itemHeight=%dpix ]", fvPos, toPos, totalPix, itemHeight));
    smoothScroller.setTargetPosition(toPos);
    rv.getLayoutManager().startSmoothScroll(smoothScroller);
}

PS: I curse the day I began indiscriminately converting ListView to RecyclerView.

executing shell command in background from script

Leave off the quotes

$cmd &
$othercmd &

eg:

nicholas@nick-win7 /tmp
$ cat test
#!/bin/bash

cmd="ls -la"

$cmd &


nicholas@nick-win7 /tmp
$ ./test

nicholas@nick-win7 /tmp
$ total 6
drwxrwxrwt+ 1 nicholas root    0 2010-09-10 20:44 .
drwxr-xr-x+ 1 nicholas root 4096 2010-09-10 14:40 ..
-rwxrwxrwx  1 nicholas None   35 2010-09-10 20:44 test
-rwxr-xr-x  1 nicholas None   41 2010-09-10 20:43 test~

GCC fatal error: stdio.h: No such file or directory

I had the same problem. I installed "XCode: development tools" from the app store and it fixed the problem for me.

I think this link will help: https://itunes.apple.com/us/app/xcode/id497799835?mt=12&ls=1

Credit to Yann Ramin for his advice. I think there is a better solution with links, but this was easy and fast.

Good luck!

Document Root PHP

<a href="<?php echo $_SERVER['DOCUMENT_ROOT'].'/hello.html'; ?>">go with php</a>
    <br />
<a href="/hello.html">go to with html</a>

Try this yourself and find that they are not exactly the same.

$_SERVER['DOCUMENT_ROOT'] renders an actual file path (on my computer running as it's own server, C:/wamp/www/

HTML's / renders the root of the server url, in my case, localhost/

But C:/wamp/www/hello.html and localhost/hello.html are in fact the same file

How to completely hide the navigation bar in iPhone / HTML5

Remy Sharp has a good description of the process in his article "Doing it right: skipping the iPhone url bar":

Making the iPhone hide the url bar is fairly simple, you need run the following JavaScript:

window.scrollTo(0, 1); 

However there's the question of when? You have to do this once the height is correct so that the iPhone can scroll to the first pixel of the document, otherwise it will try, then the height will load forcing the url bar back in to view.

You could wait until the images have loaded and the window.onload event fires, but this doesn't always work, if everything is cached, the event fires too early and the scrollTo never has a chance to jump. Here's an example using window.onload: http://jsbin.com/edifu4/4/

I personally use a timer for 1 second - which is enough time on a mobile device while you wait to render, but long enough that it doesn't fire too early:

setTimeout(function () {   window.scrollTo(0, 1); }, 1000);

However, you only want this to setup if it's an iPhone (or just mobile) browser, so a sneaky sniff (I don't generally encourage this, but I'm comfortable with this to prevent "normal" desktop browsers from jumping one pixel):

/mobile/i.test(navigator.userAgent) && setTimeout(function
() {   window.scrollTo(0, 1); }, 1000); 

The very last part of this, and this is the part that seems to be missing from some examples I've seen around the web is this: if the user specifically linked to a url fragment, i.e. the url has a hash on it, you don't want to jump. So if I navigate to http://full-frontal.org/tickets#dayconf - I want the browser to scroll naturally to the element whose id is dayconf, and not jump to the top using scrollTo(0, 1):

/mobile/i.test(navigator.userAgent) && !location.hash &&
setTimeout(function () {   window.scrollTo(0, 1); }, 1000);?

Try this out on an iPhone (or simulator) http://jsbin.com/edifu4/10 and you'll see it will only scroll when you've landed on the page without a url fragment.

SVN check out linux

There should be svn utility on you box, if installed:

$ svn checkout http://example.com/svn/somerepo somerepo

This will check out a working copy from a specified repository to a directory somerepo on our file system.

You may want to print commands, supported by this utility:

$ svn help

uname -a output in your question is identical to one, used by Parallels Virtuozzo Containers for Linux 4.0 kernel, which is based on Red Hat 5 kernel, thus your friends are rpm or the following command:

$ sudo yum install subversion

Why doesn't logcat show anything in my Android?

For one plus devices and ubuntu os:-

  • Install wine on ubuntu
  • Install adb tools on ubuntu

    sudo apt-get install android-tools-adb

  • Now, attach your device to PC with USB.

  • Open mounted "One Plus Drivers". A disc like icon

  • Right click on OnePlus_USB_Drivers_setup.exe and run with wine

  • Then open terminal in the present drive where your these "OnePlus_USB_Drivers_setup.exe" and other driver files exists. And run

    ./adb_config_Linux_OSX.sh or sh adb_config_Linux_OSX.sh

  • Close this terminal

  • Open a new termianl and run

    adb server-start

Your one plus device should prompt you to recognise your pc as a dubugging agent. Now, run on terminal. It should show your device.

adb devices

Reference :- https://forums.oneplus.com/threads/solved-android-studio-does-not-recognise-my-one-plus-two-in-linux.365221/#post-13208160

iOS download and save image inside app

You can download image without blocking UI with using NSURLSessionDataTask.

+(void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
 {
 NSURLSessionDataTask*  _sessionTask = [[NSURLSession sharedSession] dataTaskWithRequest:[NSURLRequest requestWithURL:url]
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error != nil)
        {
          if ([error code] == NSURLErrorAppTransportSecurityRequiresSecureConnection)
                {
                    completionBlock(NO,nil);
                }
         }
    else
     {
      [[NSOperationQueue mainQueue] addOperationWithBlock: ^{
                        dispatch_async(dispatch_get_main_queue(), ^{
                        UIImage *image = [[UIImage alloc] initWithData:data];
                        completionBlock(YES,image);

                        });

      }];

     }

                                            }];
    [_sessionTask resume];
}

How to read xml file contents in jQuery and display in html elements?

Simply you can read XML file as dataType: "xml", it will retuen xml object already parsed. you can use it as jquery object and find anything or loop throw it…etc.

$(document).ready(function(){
   $.ajax({
    type: "GET" ,
    url: "sampleXML.xml" ,
    dataType: "xml" ,
    success: function(xml) {

    //var xmlDoc = $.parseXML( xml );   <------------------this line
    //if single item
    var person = $(xml).find('person').text();  

    //but if it's multible items then loop
    $(xml).find('person').each(function(){
     $("#temp").append('<li>' + $(this).text() + '</li>');  
    }); 
    }       
});
});

jQuery docs for parseXML

How to send email via Django?

For Django version 1.7, if above solutions dont work then try the following

in settings.py add

#For email
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_USE_TLS = True

EMAIL_HOST = 'smtp.gmail.com'

EMAIL_HOST_USER = '[email protected]'

#Must generate specific password for your app in [gmail settings][1]
EMAIL_HOST_PASSWORD = 'app_specific_password'

EMAIL_PORT = 587

#This did the trick
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

The last line did the trick for django 1.7

curl: (35) SSL connect error

If you are using curl versions curl-7.19.7-46.el6.x86_64 or older. Please provide an option as -k1 (small K1).

mySQL Error 1040: Too Many Connection

This error occurs, due to connection limit reaches the maximum limit, defined in the configuration file my.cnf.

In order to fix this error, login to MySQL as root user (Note: you can login as root, since, mysql will pre-allocate additional one connection for root user) and increase the max_connections variable by using the following command:

SET GLOBAL max_connections = 500;

This change will be there, until next server restart. In order to make this change permanent, you have to modify in your configuration file. You can do this by,

vi /etc/my.cnf

[mysqld]
max_connections = 500

This article has detailed step by step workaround to fix this error. Have a look at it, I hope it may help you. Thanks.

Using Case/Switch and GetType to determine the object

Depending on what you are doing in the switch statement, the correct answer is polymorphism. Just put a virtual function in the interface/base class and override for each node type.

JavaFX Application Icon

I tried this and it totally works. The code is:

stage.getIcons().add(
   new Image(
      <yourclassname>.class.getResourceAsStream( "icon.png" ))); 

icon.png is under the same folder as the source files.

how to hide keyboard after typing in EditText in android?

Just write down these two lines of code where enter option will work.

InputMethodManager inputManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);

Lowercase and Uppercase with jQuery

If it's just for display purposes, you can render the text as upper or lower case in pure CSS, without any Javascript using the text-transform property:

.myclass {
    text-transform: lowercase;
}

See https://developer.mozilla.org/en/CSS/text-transform for more info.

However, note that this doesn't actually change the value to lower case; it just displays it that way. This means that if you examine the contents of the element (ie using Javascript), it will still be in its original format.

How to select a div element in the code-behind page?

id + runat="server" leads to accessible at the server

How to set the height and the width of a textfield in Java?

package myguo;
import javax.swing.*;

public class MyGuo {

    JFrame f;
    JButton bt1 , bt2 ;
    JTextField t1,t2;
    JLabel l1,l2;

    MyGuo(){

        f=new JFrame("LOG IN FORM");
        f.setLocation(500,300);
        f.setSize(600,500);
        f.setLayout(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        l1=new JLabel("NAME");
        l1.setBounds(50,70,80,30);

        l2=new JLabel("PASSWORD");
        l2.setBounds(50,100,80,30);

        t1=new JTextField();
        t1.setBounds(140, 70, 200,30);

         t2=new JTextField();
        t2.setBounds(140, 110, 200,30);

        bt1 =new JButton("LOG IN");
        bt1.setBounds(150,150,80,30);

        bt2 =new JButton("CLEAR");
        bt2.setBounds(235,150,80,30);

         f.add(l1);
        f.add(l2);
         f.add(t1);
         f.add(t2);
         f.add(bt1);
         f.add(bt2);

    f.setVisible(true);

    }
    public static void main(String[] args) {
        MyGuo myGuo = new MyGuo();
}
}

How to check which PHP extensions have been enabled/disabled in Ubuntu Linux 12.04 LTS?

For information on php extensions etc, on site.

  1. Create a new file and name it info.php (or some other name.php)

  2. Write this code in it:

     <?php
       phpinfo ();
     ?>
    
  3. Save the file in the root (home)of the site

  4. Open the file in your browser. For example: example.com/info.php All the php information on your site will be displayed.

How to parse freeform street/postal address out of text, and into components

libpostal: an open-source library to parse addresses, training with data from OpenStreetMap, OpenAddresses and OpenCage.

https://github.com/openvenues/libpostal (more info about it)

Other tools/services:

How to replace multiple strings in a file using PowerShell

A third option, for a pipelined one-liner is to nest the -replaces:

PS> ("ABC" -replace "B","C") -replace "C","D"
ADD

And:

PS> ("ABC" -replace "C","D") -replace "B","C"
ACD

This preserves execution order, is easy to read, and fits neatly into a pipeline. I prefer to use parentheses for explicit control, self-documentation, etc. It works without them, but how far do you trust that?

-Replace is a Comparison Operator, which accepts an object and returns a presumably modified object. This is why you can stack or nest them as shown above.

Please see:

help about_operators

PHP header() redirect with POST variables

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

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

Android webview & localStorage

I've also had problem with data being lost after application is restarted. Adding this helped:

webView.getSettings().setDatabasePath("/data/data/" + webView.getContext().getPackageName() + "/databases/");

Making heatmap from pandas DataFrame

Useful sns.heatmap api is here. Check out the parameters, there are a good number of them. Example:

import seaborn as sns
%matplotlib inline

idx= ['aaa','bbb','ccc','ddd','eee']
cols = list('ABCD')
df = DataFrame(abs(np.random.randn(5,4)), index=idx, columns=cols)

# _r reverses the normal order of the color map 'RdYlGn'
sns.heatmap(df, cmap='RdYlGn_r', linewidths=0.5, annot=True)

enter image description here

A regular expression to exclude a word/string

This should do it:

^/\b([a-z0-9]+)\b(?<!ignoreme|ignoreme2|ignoreme3)

You can add as much ignored words as you like, here is a simple PHP implementation:

$ignoredWords = array('ignoreme', 'ignoreme2', 'ignoreme...');

preg_match('~^/\b([a-z0-9]+)\b(?<!' . implode('|', array_map('preg_quote', $ignoredWords)) . ')~i', $string);

How to output to the console in C++/Windows

For debugging in Visual Studio you can print to the debug console:

OutputDebugStringW(L"My output string.");

How to print out the method name and line number and conditionally disable NSLog?

building on top of above answers, here is what I plagiarized and came up with. Also added memory logging.

#import <mach/mach.h>

#ifdef DEBUG
#   define DebugLog(fmt, ...) NSLog((@"%s(%d) " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#   define DebugLog(...)
#endif


#define AlwaysLog(fmt, ...) NSLog((@"%s(%d) " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);


#ifdef DEBUG
#   define AlertLog(fmt, ...)  { \
    UIAlertView *alert = [[UIAlertView alloc] \
            initWithTitle : [NSString stringWithFormat:@"%s(Line: %d) ", __PRETTY_FUNCTION__, __LINE__]\
                  message : [NSString stringWithFormat : fmt, ##__VA_ARGS__]\
                 delegate : nil\
        cancelButtonTitle : @"Ok"\
        otherButtonTitles : nil];\
    [alert show];\
}
#else
#   define AlertLog(...)
#endif



#ifdef DEBUG
#   define DPFLog NSLog(@"%s(%d)", __PRETTY_FUNCTION__, __LINE__);//Debug Pretty Function Log
#else
#   define DPFLog
#endif


#ifdef DEBUG
#   define MemoryLog {\
    struct task_basic_info info;\
    mach_msg_type_number_t size = sizeof(info);\
    kern_return_t e = task_info(mach_task_self(),\
                                   TASK_BASIC_INFO,\
                                   (task_info_t)&info,\
                                   &size);\
    if(KERN_SUCCESS == e) {\
        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; \
        [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; \
        DebugLog(@"%@ bytes", [formatter stringFromNumber:[NSNumber numberWithInteger:info.resident_size]]);\
    } else {\
        DebugLog(@"Error with task_info(): %s", mach_error_string(e));\
    }\
}
#else
#   define MemoryLog
#endif

How to check if a file is a valid image file?

Update

I also implemented the following solution in my Python script here on GitHub.

I also verified that damaged files (jpg) frequently are not 'broken' images i.e, a damaged picture file sometimes remains a legit picture file, the original image is lost or altered but you are still able to load it with no errors. But, file truncation cause always errors.

End Update

You can use Python Pillow(PIL) module, with most image formats, to check if a file is a valid and intact image file.

In the case you aim at detecting also broken images, @Nadia Alramli correctly suggests the im.verify() method, but this does not detect all the possible image defects, e.g., im.verify does not detect truncated images (that most viewers often load with a greyed area).

Pillow is able to detect these type of defects too, but you have to apply image manipulation or image decode/recode in or to trigger the check. Finally I suggest to use this code:

try:
  im = Image.load(filename)
  im.verify() #I perform also verify, don't know if he sees other types o defects
  im.close() #reload is necessary in my case
  im = Image.load(filename) 
  im.transpose(PIL.Image.FLIP_LEFT_RIGHT)
  im.close()
except: 
  #manage excetions here

In case of image defects this code will raise an exception. Please consider that im.verify is about 100 times faster than performing the image manipulation (and I think that flip is one of the cheaper transformations). With this code you are going to verify a set of images at about 10 MBytes/sec with standard Pillow or 40 MBytes/sec with Pillow-SIMD module (modern 2.5Ghz x86_64 CPU).

For the other formats psd,xcf,.. you can use Imagemagick wrapper Wand, the code is as follows:

im = wand.image.Image(filename=filename)
temp = im.flip;
im.close()

But, from my experiments Wand does not detect truncated images, I think it loads lacking parts as greyed area without prompting.

I red that Imagemagick has an external command identify that could make the job, but I have not found a way to invoke that function programmatically and I have not tested this route.

I suggest to always perform a preliminary check, check the filesize to not be zero (or very small), is a very cheap idea:

statfile = os.stat(filename)
filesize = statfile.st_size
if filesize == 0:
  #manage here the 'faulty image' case

Checking version of angular-cli that's installed?

ng version or ng --version or ng v OR ng -v

You can use this 4 commands to check the which version of angular-cli installed in your machine.

Excel Formula to SUMIF date falls in particular month

=SUMPRODUCT( (MONTH($A$2:$A$6)=1) * ($B$2:$B$6) )

Explanation:

  • (MONTH($A$2:$A$6)=1) creates an array of 1 and 0, it's 1 when the month is january, thus in your example the returned array would be [1, 1, 1, 0, 0]

  • SUMPRODUCT first multiplies each value of the array created in the above step with values of the array ($B$2:$B$6), then it sums them. Hence in your example it does this: (1 * 430) + (1 * 96) + (1 * 440) + (0 * 72.10) + (0 * 72.30)

This works also in OpenOffice and Google Spreadsheets

Java ArrayList - how can I tell if two lists are equal, order not mattering?

Probably the easiest way for any list would be:

listA.containsAll(listB) && listB.containsAll(listA)

Disabling and enabling a html input button

This will surely work .

To Disable a button

$('#btn_id').button('disable');

To Enable a button

$('#btn_id').button('enable');

jQuery selector for inputs with square brackets in the name attribute

You can use backslash to quote "funny" characters in your jQuery selectors:

$('#input\\[23\\]')

For attribute values, you can use quotes:

$('input[name="weirdName[23]"]')

Now, I'm a little confused by your example; what exactly does your HTML look like? Where does the string "inputName" show up, in particular?

edit fixed bogosity; thanks @Dancrumb

Purpose of a constructor in Java?

I thought a constructor might work like a database in which only it defines variables and methods to control them

Then I saw objects that use variables and methods not defined in its constructor. So the discussion that makes the most sense to me is the one that tests variables values for validity, but the class can create variables and methods that are not defined in the constructor - less like a database and more like an over pressure valve on a steam locomotive. It doesn't control the wheels,etc.

Far less of a definition than I thought.

$lookup on ObjectId's in an array

Starting with MongoDB v3.4 (released in 2016), the $lookup aggregation pipeline stage can also work directly with an array. There is no need for $unwind any more.

This was tracked in SERVER-22881.

Eclipse projects not showing up after placing project files in workspace/projects

I just wish to add one important detail to the answers above. And it is that even if you import the projects from your chosen root directory they may not appear in bold so you won't be able to select them. The reason for this may be that the metadata of the projects is corrupted. If you do encounter this problem then the easiest and quickest way to fix it is to rid yourself of the workspace-folder and create a new one and copy+paste your projects (do it before you erase the old workspace) folders to this new workspace. Then, in your new worskapce, import the projects as the previous posts have explained.

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists

You may try the following if your database does not have any data OR you have another away to restore that data. You will need to know the Ubuntu server root password but not the mysql root password.

It is highly probably that many of us have installed "mysql_secure_installation" as this is a best practice. Navigate to bin directory where mysql_secure_installation exist. It can be found in the /bin directory on Ubuntu systems. By rerunning the installer, you will be prompted about whether to change root database password.

Find all files in a folder

You can try with Directory.GetFiles and fix your pattern

 string[] files = Directory.GetFiles(@"c:\", "*.txt");

 foreach (string file in files)
 {
    File.Copy(file, "....");
 }

 Or Move

 foreach (string file in files)
 {
    File.Move(file, "....");
 }     

http://msdn.microsoft.com/en-us/library/wz42302f

Add placeholder text inside UITextView in Swift?

I believe this is a very clean solution. It adds a dummy text view underneath the actual text view and shows or hides it depending on the text in the actual text view:

import Foundation
import UIKit

class TextViewWithPlaceholder: UITextView {

    private var placeholderTextView: UITextView = UITextView()

    var placeholder: String? {
        didSet {
            placeholderTextView.text = placeholder
        }
    }

    override var text: String! {
        didSet {
            placeholderTextView.isHidden = text.isEmpty == false
        }
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    private func commonInit() {
        applyCommonTextViewAttributes(to: self)
        configureMainTextView()
        addPlaceholderTextView()
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(textDidChange),
                                               name: UITextView.textDidChangeNotification,
                                               object: nil)
    }

    func addPlaceholderTextView() {
        applyCommonTextViewAttributes(to: placeholderTextView)
        configurePlaceholderTextView()
        insertSubview(placeholderTextView, at: 0)
    }

    private func applyCommonTextViewAttributes(to textView: UITextView) {
        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.textContainer.lineFragmentPadding = 0
        textView.textContainerInset = UIEdgeInsets(top: 10,
                                                   left: 10,
                                                   bottom: 10,
                                                   right: 10)
    }

    private func configureMainTextView() {
        // Do any configuration of the actual text view here
    }

    private func configurePlaceholderTextView() {
        placeholderTextView.text = placeholder
        placeholderTextView.font = font
        placeholderTextView.textColor = UIColor.lightGray
        placeholderTextView.frame = bounds
        placeholderTextView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        placeholderTextView.frame = bounds
    }

    @objc func textDidChange() {
        placeholderTextView.isHidden = !text.isEmpty
    }

}

Thread-safe List<T> property

Basically if you want to enumerate safely, you need to use lock.

Please refer to MSDN on this. http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx

Here is part of MSDN that you might be interested:

Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

A List can support multiple readers concurrently, as long as the collection is not modified. Enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with one or more write accesses, the only way to ensure thread safety is to lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

How can I check if given int exists in array?

int index = std::distance(std::begin(myArray), std::find(begin(myArray), end(std::myArray), VALUE));

Returns an invalid index (length of the array) if not found.

github: server certificate verification failed

Try to connect to repositroy with url: http://github.com/<user>/<project>.git (http except https)

In your case you should clone like this:

git clone http://github.com/<user>/<project>.git

Twitter Bootstrap tabs not working: when I click on them nothing happens

Had a problem with Bootstrap tabs recently following their online guidelines, but there's currently an error in their markup example data-tabs="tabs" is missing on <ul> element. Without it using data-toggle on links doesn't work.

Deep-Learning Nan loss reasons

The reason for nan, inf or -inf often comes from the fact that division by 0.0 in TensorFlow doesn't result in a division by zero exception. It could result in a nan, inf or -inf "value". In your training data you might have 0.0 and thus in your loss function it could happen that you perform a division by 0.0.

a = tf.constant([2., 0., -2.])
b = tf.constant([0., 0., 0.])
c = tf.constant([1., 1., 1.])
print((a / b) + c)

Output is the following tensor:

tf.Tensor([ inf  nan -inf], shape=(3,), dtype=float32)

Adding a small eplison (e.g., 1e-5) often does the trick. Additionally, since TensorFlow 2 the opteration tf.math.division_no_nan is defined.

Python os.path.join on Windows

To be pedantic, it's probably not good to hardcode either / or \ as the path separator. Maybe this would be best?

mypath = os.path.join('c:%s' % os.sep, 'sourcedir')

or

mypath = os.path.join('c:' + os.sep, 'sourcedir')

Get user location by IP address

I was able to achieve this in ASP.NET MVC using the client IP address and freegeoip.net API. freegeoip.net is free and does not require any license.

Below is the sample code I used.

String UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(UserIP))
{
    UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
string url = "http://freegeoip.net/json/" + UserIP.ToString();
WebClient client = new WebClient();
string jsonstring = client.DownloadString(url);
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
System.Web.HttpContext.Current.Session["UserCountryCode"] = dynObj.country_code;

You can go through this post for more details.Hope it helps!

Rename a file using Java

In short:

Files.move(source, source.resolveSibling("newname"));

More detail:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

The following is copied directly from http://docs.oracle.com/javase/7/docs/api/index.html:

Suppose we want to rename a file to "newname", keeping the file in the same directory:

Path source = Paths.get("path/here");
Files.move(source, source.resolveSibling("newname"));

Alternatively, suppose we want to move a file to new directory, keeping the same file name, and replacing any existing file of that name in the directory:

Path source = Paths.get("from/path");
Path newdir = Paths.get("to/path");
Files.move(source, newdir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING);

Get: TypeError: 'dict_values' object does not support indexing when using python 3.2.3

A simpler version of your code would be:

dict(zip(names, d.values()))

If you want to keep the same structure, you can change it to:

vlst = list(d.values())
{names[i]: vlst[i] for i in range(len(names))}

(You can just as easily put list(d.values()) inside the comprehension instead of vlst; it's just wasteful to do so since it would be re-generating the list every time).

How to create streams from string in Node.Js?

Heres a tidy solution in TypeScript:

import { Readable } from 'stream'

class ReadableString extends Readable {
    private sent = false

    constructor(
        private str: string
    ) {
        super();
    }

    _read() {
        if (!this.sent) {
            this.push(Buffer.from(this.str));
            this.sent = true
        }
        else {
            this.push(null)
        }
    }
}

const stringStream = new ReadableString('string to be streamed...')

SQLException : String or binary data would be truncated

  1. Get the query that is causing the problems (you can also use SQL Profiler if you dont have the source)
  2. Remove all WHERE clauses and other unimportant parts until you are basically just left with the SELECT and FROM parts
  3. Add WHERE 0 = 1 (this will select only table structure)
  4. Add INTO [MyTempTable] just before the FROM clause

You should end up with something like

SELECT
 Col1, Col2, ..., [ColN]
INTO [MyTempTable]
FROM
  [Tables etc.]
WHERE 0 = 1

This will create a table called MyTempTable in your DB that you can compare to your target table structure i.e. you can compare the columns on both tables to see where they differ. It is a bit of a workaround but it is the quickest method I have found.

how do I set height of container DIV to 100% of window height?

html {
  min-height: 100%;
}

body {
  min-height: 100vh;
}

The html height (%) will take care of the height of the documents that's height is more than a 100% of the screen view while the body view height (vh) will take care of the document's height that is less than the height of the screen view.

Escaping single quote in PHP when inserting into MySQL

I had the same problem and I solved it like this:

$text = str_replace("'", "\'", $YourContent);

There is probably a better way to do this, but it worked for me and it should work for you too.

How to style a JSON block in Github Wiki?

```javascript
{ "some": "json" }
```

I tried using json but didn't like the way it looked. javascript looks a bit more pleasing to my eye.

Pip freeze vs. pip list

To answer the second part of this question, the two packages shown in pip list but not pip freeze are setuptools (which is easy_install) and pip itself.

It looks like pip freeze just doesn't list packages that pip itself depends on. You may use the --all flag to show also those packages.

From the documentation:

--all

Do not skip these packages in the output: pip, setuptools, distribute, wheel

How to add jQuery to an HTML page?

Inside of your <head></head> tags add...

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $('input[type=radio]').change(function() {

    $('input[type=radio]').each(function(index) {
        $(this).closest('tr').removeClass('selected');
    });

        $(this).closest('tr').addClass('selected');
    });
});
</script>

EDIT: The placement inside of <head></head> is not the only option...this could just as easily be placed RIGHT before the closing </body> tag. I generally try and place my JavaScript inside of head for placement reasons, but it can in some cases slow down page rendering so some will recommend the latter approach (before closing body).

Undefined reference to pow( ) in C, despite including math.h

You need to link with the math library:

gcc -o sphere sphere.c -lm

The error you are seeing: error: ld returned 1 exit status is from the linker ld (part of gcc that combines the object files) because it is unable to find where the function pow is defined.

Including math.h brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a. You need to link your program with this library so that the calls to functions like pow() are resolved.

Submitting HTML form using Jquery AJAX

If you add:

jquery.form.min.js

You can simply do this:

<script>
$('#myform').ajaxForm(function(response) {
  alert(response);
});

// this will register the AJAX for <form id="myform" action="some_url">
// and when you submit the form using <button type="submit"> or $('myform').submit(), then it will send your request and alert response
</script>

NOTE:

You could use simple $('FORM').serialize() as suggested in post above, but that will not work for FILE INPUTS... ajaxForm() will.

Create a unique number with javascript time

I use

Math.floor(new Date().valueOf() * Math.random())

So if by any chance the code is fired at the same time there is also a teeny chance that the random numbers will be the same.

Python socket receive - incoming packets always have a different size

You can alternatively use recv(x_bytes, socket.MSG_WAITALL), which seems to work only on Unix, and will return exactly x_bytes.

iOS Detection of Screenshot?

As of iOS 7 the other answers are no longer true. Apple has made it so touchesCancelled:withEvent: is no longer called when the user takes a screenshot.

This would effectively break Snapchat entirely, so a couple betas in a new solution was added. Now, the solution is as simple as using NSNotificationCenter to add an observer to UIApplicationUserDidTakeScreenshotNotification.

Here's an example:

Objective C

NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationUserDidTakeScreenshotNotification
                                                  object:nil
                                                   queue:mainQueue
                                              usingBlock:^(NSNotification *note) {
                                                 // executes after screenshot
                                              }];

Swift

NotificationCenter.default.addObserver(
    forName: UIApplication.userDidTakeScreenshotNotification,
    object: nil,
    queue: .main) { notification in
        //executes after screenshot
}

How to emit an event from parent to child?

Within the parent, you can reference the child using @ViewChild. When needed (i.e. when the event would be fired), you can just execute a method in the child from the parent using the @ViewChild reference.

Angular: Cannot Get /

I had the same problem with an Angular 9.

In my case, I changed the angular.json file from

"aot": true

To

"aot": false

It works for me.

JavaScript variable number of arguments to function

As mentioned already, you can use the arguments object to retrieve a variable number of function parameters.

If you want to call another function with the same arguments, use apply. You can even add or remove arguments by converting arguments to an array. For example, this function inserts some text before logging to console:

log() {
    let args = Array.prototype.slice.call(arguments);
    args = ['MyObjectName', this.id_].concat(args);
    console.log.apply(console, args);
}

openssl s_client -cert: Proving a client certificate was sent to the server

I know this is an old question but it does not yet appear to have an answer. I've duplicated this situation, but I'm writing the server app, so I've been able to establish what happens on the server side as well. The client sends the certificate when the server asks for it and if it has a reference to a real certificate in the s_client command line. My server application is set up to ask for a client certificate and to fail if one is not presented. Here is the command line I issue:

Yourhostname here -vvvvvvvvvv s_client -connect <hostname>:443 -cert client.pem -key cckey.pem -CAfile rootcert.pem -cipher ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH -tls1 -state

When I leave out the "-cert client.pem" part of the command the handshake fails on the server side and the s_client command fails with an error reported. I still get the report "No client certificate CA names sent" but I think that has been answered here above.

The short answer then is that the server determines whether a certificate will be sent by the client under normal operating conditions (s_client is not normal) and the failure is due to the server not recognizing the CA in the certificate presented. I'm not familiar with many situations in which two-way authentication is done although it is required for my project.

You are clearly sending a certificate. The server is clearly rejecting it.

The missing information here is the exact manner in which the certs were created and the way in which the provider loaded the cert, but that is probably all wrapped up by now.

Counter exit code 139 when running, but gdb make it through

this error is also caused by null pointer reference. if you are using a pointer who is not initialized then it causes this error.

to check either a pointer is initialized or not you can try something like

Class *pointer = new Class();
if(pointer!=nullptr){
    pointer->myFunction();
}

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

Introduction

This can have a lot of causes which are broken down in following sections:

  • Put servlet class in a package
  • Set servlet URL in url-pattern
  • @WebServlet works only on Servlet 3.0 or newer
  • javax.servlet.* doesn't work anymore in Servlet 5.0 or newer
  • Make sure compiled *.class file is present in built WAR
  • Test the servlet individually without any JSP/HTML page
  • Use domain-relative URL to reference servlet from HTML
  • Use straight quotes in HTML attributes

Put servlet class in a package

First of all, put the servlet class in a Java package. You should always put publicly reuseable Java classes in a package, otherwise they are invisible to classes which are in a package, such as the server itself. This way you eliminiate potential environment-specific problems. Packageless servlets work only in specific Tomcat+JDK combinations and this should never be relied upon.

In case of a "plain" IDE project, the class needs to be placed in its package structure inside "Java Resources" folder and thus not "WebContent", this is for web files such as JSP. Below is an example of the folder structure of a default Eclipse Dynamic Web Project as seen in Navigator view:

EclipseProjectName
 |-- src
 |    `-- com
 |         `-- example
 |              `-- YourServlet.java
 |-- WebContent
 |    |-- WEB-INF
 |    |    `-- web.xml
 |    `-- jsps
 |         `-- page.jsp
 :

In case of a Maven project, the class needs to be placed in its package structure inside main/java and thus not main/resources, this is for non-class files and absolutely also not main/webapp, this is for web files. Below is an example of the folder structure of a default Maven webapp project as seen in Eclipse's Navigator view:

MavenProjectName
 |-- src
 |    `-- main
 |         |-- java
 |         |    `-- com
 |         |         `-- example
 |         |              `-- YourServlet.java
 |         |-- resources
 |         `-- webapp
 |              |-- WEB-INF
 |              |    `-- web.xml
 |              `-- jsps
 |                   `-- page.jsp
 :

Note that the /jsps subfolder is not strictly necessary. You can even do without it and put the JSP file directly in webcontent/webapp root, but I'm just taking over this from your question.

Set servlet URL in url-pattern

The servlet URL is specified as the "URL pattern" of the servlet mapping. It's absolutely not per definition the classname/filename of the servlet class. The URL pattern is to be specified as value of @WebServlet annotation.

package com.example; // Use a package!

@WebServlet("/servlet") // This is the URL of the servlet.
public class YourServlet extends HttpServlet { // Must be public and extend HttpServlet.
    // ...
}

In case you want to support path parameters like /servlet/foo/bar, then use an URL pattern of /servlet/* instead. See also Servlet and path parameters like /xyz/{value}/test, how to map in web.xml?

@WebServlet works only on Servlet 3.0 or newer

In order to use @WebServlet, you only need to make sure that your web.xml file, if any (it's optional since Servlet 3.0), is declared conform Servlet 3.0+ version and thus not conform e.g. 2.5 version or lower. Below is a Servlet 4.0 compatible one (which matches Tomcat 9+, WildFly 11+, Payara 5+, etc).

<?xml version="1.0" encoding="UTF-8"?>
<web-app
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    version="4.0"
>
    <!-- Config here. -->
</web-app>

Or, in case you're not on Servlet 3.0+ yet (e.g. Tomcat 6 or older), then remove the @WebServlet annotation.

package com.example;

public class YourServlet extends HttpServlet {
    // ...
}

And register the servlet instead in web.xml like this:

<servlet>
    <servlet-name>yourServlet</servlet-name>
    <servlet-class>com.example.YourServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>yourServlet</servlet-name>
    <url-pattern>/servlet</url-pattern>  <!-- This is the URL of the servlet. -->
</servlet-mapping>

Note thus that you should not use both ways. Use either annotation based configuarion or XML based configuration. When you have both, then XML based configuration will override annotation based configuration.

javax.servlet.* doesn't work anymore in Servlet 5.0 or newer

Since Jakarta EE 9 / Servlet 5.0 (Tomcat 10, TomEE 9, WildFly 22 Preview, GlassFish 6, Payara 6, Liberty 22, etc), the javax.* package has been renamed to jakarta.* package.

In other words, please make absolutely sure that you don't randomly put JAR files of a different server in your WAR project such as tomcat-servlet-api-9.x.x.jar merely in order to get the javax.* package to compile. This will only cause trouble. Remove it altogether and edit the imports of your servlet class from

import javax.servlet.*;
import javax.servlet.http.*;

to

import jakarta.servlet.*;
import jakarta.servlet.http.*;

In case you're using Maven, you can find examples of proper pom.xml declarations for Tomcat 10+, Tomcat 9-, JEE 9+ and JEE 8- in this answer: Tomcat 9 casting servlets to javax.servlet.Servlet instead of jakarta.servlet.http.HttpServlet

Make sure compiled *.class file is present in built WAR

In case you're using a build tool such as Eclipse and/or Maven, then you need to make absolutely sure that the compiled servlet class file resides in its package structure in /WEB-INF/classes folder of the produced WAR file. In case of package com.example; public class YourServlet, it must be located in /WEB-INF/classes/com/example/YourServlet.class. Otherwise you will face in case of @WebServlet also a 404 error, or in case of <servlet> a HTTP 500 error like below:

HTTP Status 500

Error instantiating servlet class com.example.YourServlet

And find in the server log a java.lang.ClassNotFoundException: com.example.YourServlet, followed by a java.lang.NoClassDefFoundError: com.example.YourServlet, in turn followed by javax.servlet.ServletException: Error instantiating servlet class com.example.YourServlet.

An easy way to verify if the servlet is correctly compiled and placed in classpath is to let the build tool produce a WAR file (e.g. rightclick project, Export > WAR file in Eclipse) and then inspect its contents with a ZIP tool. If the servlet class is missing in /WEB-INF/classes, or if the export causes an error, then the project is badly configured or some IDE/project configuration defaults have been mistakenly reverted (e.g. Project > Build Automatically has been disabled in Eclipse).

You also need to make sure that the project icon has no red cross indicating a build error. You can find the exact error in Problems view (Window > Show View > Other...). Usually the error message is fine Googlable. In case you have no clue, best is to restart from scratch and do not touch any IDE/project configuration defaults. In case you're using Eclipse, you can find instructions in How do I import the javax.servlet API in my Eclipse project?

Test the servlet individually without any JSP/HTML page

Provided that the server runs on localhost:8080, and that the WAR is successfully deployed on a context path of /contextname (which defaults to the IDE project name, case sensitive!), and the servlet hasn't failed its initialization (read server logs for any deploy/servlet success/fail messages and the actual context path and servlet mapping), then a servlet with URL pattern of /servlet is available at http://localhost:8080/contextname/servlet.

You can just enter it straight in browser's address bar to test it invidivually. If its doGet() is properly overriden and implemented, then you will see its output in browser. Or if you don't have any doGet() or if it incorrectly calls super.doGet(), then a "HTTP 405: HTTP method GET is not supported by this URL" error will be shown (which is still better than a 404 as a 405 is evidence that the servlet itself is actually found).

Overriding service() is a bad practice, unless you're reinventing a MVC framework — which is very unlikely if you're just starting out with servlets and are clueless as to the problem described in the current question ;) See also Design Patterns web based applications.

Regardless, if the servlet already returns 404 when tested invidivually, then it's entirely pointless to try with a HTML form instead. Logically, it's therefore also entirely pointless to include any HTML form in questions about 404 errors from a servlet.

Use domain-relative URL to reference servlet from HTML

Once you've verified that the servlet works fine when invoked individually, then you can advance to HTML. As to your concrete problem with the HTML form, the <form action> value needs to be a valid URL. The same applies to <a href>. You need to understand how absolute/relative URLs work. You know, an URL is a web address as you can enter/see in the webbrowser's address bar. If you're specifying a relative URL as form action, i.e. without the http:// scheme, then it becomes relative to the current URL as you see in your webbrowser's address bar. It's thus absolutely not relative to the JSP/HTML file location in server's WAR folder structure as many starters seem to think.

So, assuming that the JSP page with the HTML form is opened by http://localhost:8080/contextname/jsps/page.jsp, and you need to submit to a servlet located in http://localhost:8080/contextname/servlet, here are several cases (note that you can safely substitute <form action> with <a href> here):

  • Form action submits to an URL with a leading slash.

      <form action="/servlet">
    

    The leading slash / makes the URL relative to the domain, thus the form will submit to

      http://localhost:8080/servlet
    

    But this will likely result in a 404 as it's in the wrong context.


  • Form action submits to an URL without a leading slash.

      <form action="servlet">
    

    This makes the URL relative to the current folder of the current URL, thus the form will submit to

      http://localhost:8080/contextname/jsps/servlet
    

    But this will likely result in a 404 as it's in the wrong folder.


  • Form action submits to an URL which goes one folder up.

      <form action="../servlet">
    

    This will go one folder up (exactly like as in local disk file system paths!), thus the form will submit to

      http://localhost:8080/contextname/servlet
    

    This one must work!


  • The canonical approach, however, is to make the URL domain-relative so that you don't need to fix the URLs once again when you happen to move the JSP files around into another folder.

      <form action="${pageContext.request.contextPath}/servlet">
    

    This will generate

      <form action="/contextname/servlet">
    

    Which will thus always submit to the right URL.


Use straight quotes in HTML attributes

You need to make absolutely sure you're using straight quotes in HTML attributes like action="..." or action='...' and thus not curly quotes like action=”...” or action=’...’. Curly quotes are not supported in HTML and they will simply become part of the value. Watch out when copy-pasting code snippets from blogs! Some blog engines, notably Wordpress, are known to by default use so-called "smart quotes" which thus also corrupts the quotes in code snippets this way. On the other hand, instead of copy-pasting code, try simply typing over the code yourself. Additional advantage of actually getting the code through your brain and fingers is that it will make you to remember and understand the code much better in long term and also make you a better developer.

See also:

Other cases of HTTP Status 404 error:

The type or namespace name 'Objects' does not exist in the namespace 'System.Data'

You need to add a reference to the .NET assembly System.Data.Linq

C++ - struct vs. class

Ok, POD means plain old data. That usually refers to structs without any methods because these types are then used to structure multiple data that belong together.

As for structs not having methods: I have seen more than once that a struct had methods, and I don't feel that this would be unnatural.

How to get current class name including package name in Java?

Use this.getClass().getCanonicalName() to get the full class name.

Note that a package / class name ("a.b.C") is different from the path of the .class files (a/b/C.class), and that using the package name / class name to derive a path is typically bad practice. Sets of class files / packages can be in multiple different class paths, which can be directories or jar files.

Set default time in bootstrap-datetimepicker

use this after initialisation

$('.form_datetime').datetimepicker('update', new Date());

Illegal Character when trying to compile java code

Even I was facing this issue as am using notepad++ to code. It is very convenient to type the code in notepad++. However after compiling I get an error " error: illegal character: '\u00bb'". Solution : Start writing the code in older version of notepad(which will be there by default in your PC) and save it. Later the modifications can be done using notepad++. It works!!!

Cannot assign requested address using ServerSocket.socketBind

java.net.BindException: Cannot assign requested address

According to BindException documentation, it basically:

Signals that an error occurred while attempting to bind a socket to a local address and port. Typically, the port is in use, or the requested local address could not be assigned.

So try the following command:

sudo lsof -i:8983

to double check if any application is using the same port and kill it.

If that's not the case, make sure that your IP address to which you're trying to bind is correct (it's correctly assigned to your network interface).

Restrict SQL Server Login access to only one database

I think this is what we like to do very much.

--Step 1: (create a new user)
create LOGIN hello WITH PASSWORD='foo', CHECK_POLICY = OFF;


-- Step 2:(deny view to any database)
USE master;
GO
DENY VIEW ANY DATABASE TO hello; 


 -- step 3 (then authorized the user for that specific database , you have to use the  master by doing use master as below)
USE master;
GO
ALTER AUTHORIZATION ON DATABASE::yourDB TO hello;
GO

If you already created a user and assigned to that database before by doing

USE [yourDB] 
CREATE USER hello FOR LOGIN hello WITH DEFAULT_SCHEMA=[dbo] 
GO

then kindly delete it by doing below and follow the steps

   USE yourDB;
   GO
   DROP USER newlogin;
   GO

For more information please follow the links:

Hiding databases for a login on Microsoft Sql Server 2008R2 and above

DataColumn Name from DataRow (not DataTable)

You can make it easier in your code (if you're doing this a lot anyway) by using an extension on the DataRow object, like:

static class Extensions
{
    public static string GetColumn(this DataRow Row, int Ordinal)
    {
        return Row.Table.Columns[Ordinal].ColumnName;
    }
}

Then call it using:

string MyColumnName = MyRow.GetColumn(5);

How can I convert tabs to spaces in every file of a directory?

Try the command line tool expand.

expand -i -t 4 input | sponge output

where

  • -i is used to expand only leading tabs on each line;
  • -t 4 means that each tab will be converted to 4 whitespace chars (8 by default).
  • sponge is from the moreutils package, and avoids clearing the input file.

Finally, you can use gexpand on OSX, after installing coreutils with Homebrew (brew install coreutils).

Delete from a table based on date

or an ORACLE version:

delete
  from table_name
 where trunc(table_name.date) > to_date('01/01/2009','mm/dd/yyyy') 

Is there a way to make a DIV unselectable?

Wouldn't a simple background image for the textarea suffice?

How to check if an element is off-screen

  • Get the distance from the top of the given element
  • Add the height of the same given element. This will tell you the total number from the top of the screen to the end of the given element.
  • Then all you have to do is subtract that from total document height

    jQuery(function () {
        var documentHeight = jQuery(document).height();
        var element = jQuery('#you-element');
        var distanceFromBottom = documentHeight - (element.position().top + element.outerHeight(true));
        alert(distanceFromBottom)
    });
    

Add two numbers and display result in textbox with Javascript

<script>
function myFunction() {
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var x = y + z;
document.getElementById("result").innerHTML = x;
}
</script>
<p>
<label>Enter First Number : </label><br>
<input type="number" id="txt1" name="text1"><br/>
<label>Enter Second Number : </label><br>
<input type="number" id="txt2" name="text2">
</p>
<p>
<button onclick="myFunction()">Calculate</button>
</p>
<br/>
<p id="result"></p>

What is the best way to convert an array to a hash in Ruby

Appending to the answer but using anonymous arrays and annotating:

Hash[*("a,b,c,d".split(',').zip([1,2,3,4]).flatten)]

Taking that answer apart, starting from the inside:

  • "a,b,c,d" is actually a string.
  • split on commas into an array.
  • zip that together with the following array.
  • [1,2,3,4] is an actual array.

The intermediate result is:

[[a,1],[b,2],[c,3],[d,4]]

flatten then transforms that to:

["a",1,"b",2,"c",3,"d",4]

and then:

*["a",1,"b",2,"c",3,"d",4] unrolls that into "a",1,"b",2,"c",3,"d",4

which we can use as the arguments to the Hash[] method:

Hash[*("a,b,c,d".split(',').zip([1,2,3,4]).flatten)]

which yields:

{"a"=>1, "b"=>2, "c"=>3, "d"=>4}

File Permissions and CHMOD: How to set 777 in PHP upon file creation?

You just need to manually set the desired permissions with chmod():

private function writeFileContent($file, $content){
    $fp = fopen($file, 'w');
    fwrite($fp, $content);
    fclose($fp);

    // Set perms with chmod()
    chmod($file, 0777);
    return true;
}

How to print something to the console in Xcode?

How to print:

NSLog(@"Something To Print");

Or

NSString * someString = @"Something To Print";
NSLog(@"%@", someString);

For other types of variables, use:

NSLog(@"%@", someObject);
NSLog(@"%i", someInt);
NSLog(@"%f", someFloat);
/// etc...

Can you show it in phone?

Not by default, but you could set up a display to show you.

Update for Swift

print("Print this string")
print("Print this \(variable)")
print("Print this ", variable)
print(variable)

Download a file with Android, and showing the progress in a ProgressDialog

I am adding another answer for other solution I am using now because Android Query is so big and unmaintained to stay healthy. So i moved to this https://github.com/amitshekhariitbhu/Fast-Android-Networking.

    AndroidNetworking.download(url,dirPath,fileName).build()
      .setDownloadProgressListener(new DownloadProgressListener() {
        public void onProgress(long bytesDownloaded, long totalBytes) {
            bar.setMax((int) totalBytes);
            bar.setProgress((int) bytesDownloaded);
        }
    }).startDownload(new DownloadListener() {
        public void onDownloadComplete() {
            ...
        }

        public void onError(ANError error) {
            ...
        }
    });

How to retrieve GET parameters from JavaScript

You should use URL and URLSearchParams native functions:

_x000D_
_x000D_
let url = new URL("https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8&q=mdn%20query%20string")_x000D_
let params = new URLSearchParams(url.search);_x000D_
let sourceid = params.get('sourceid') // 'chrome-instant'_x000D_
let q = params.get('q') // 'mdn query string'_x000D_
let ie = params.has('ie') // true_x000D_
params.append('ping','pong')_x000D_
_x000D_
console.log(sourceid)_x000D_
console.log(q)_x000D_
console.log(ie)_x000D_
console.log(params.toString())_x000D_
console.log(params.get("ping"))
_x000D_
_x000D_
_x000D_

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams https://polyfill.io/v2/docs/features/

How to search for a string inside an array of strings

It's faster to avoid using regular expressions, if you're just trying to find the first substring match within an array of string values. You can add your own array searching function:

Code:

Array.prototype.findFirstSubstring = function(s) {
            for(var i = 0; i < this.length;i++)
            {
                if(this[i].indexOf(s) !== -1)
                    return i;
            }
            return -1;
        };

Usage:

i.findFirstSubstring('height');

Returns:

-1 if not found or the array index of the first substring occurrence if it is found (in your case would be 2)

Catching KeyboardInterrupt in Python during program shutdown

You could ignore SIGINTs after shutdown starts by calling signal.signal(signal.SIGINT, signal.SIG_IGN) before you start your cleanup code.

How to convert a Java String to an ASCII byte array?

Using the getBytes method, giving it the appropriate Charset (or Charset name).

Example:

String s = "Hello, there.";
byte[] b = s.getBytes(StandardCharsets.US_ASCII);

(Before Java 7: byte[] b = s.getBytes("US-ASCII");)

Jmeter - Run .jmx file through command line and get the summary report in a excel

JMeter can be launched in non-GUI mode as follows:

jmeter -n -t /path/to/your/test.jmx -l /path/to/results/file.jtl

You can set what would you like to see in result jtl file via playing with JMeter Properties.

See jmeter.properties file under /bin folder of your JMeter installation and look for those starting with

jmeter.save.saveservice.

Defaults are listed below:

#jmeter.save.saveservice.output_format=csv
#jmeter.save.saveservice.assertion_results_failure_message=false
#jmeter.save.saveservice.assertion_results=none
#jmeter.save.saveservice.data_type=true
#jmeter.save.saveservice.label=true
#jmeter.save.saveservice.response_code=true
#jmeter.save.saveservice.response_data=false
#jmeter.save.saveservice.response_data.on_error=false
#jmeter.save.saveservice.response_message=true
#jmeter.save.saveservice.successful=true
#jmeter.save.saveservice.thread_name=true
#jmeter.save.saveservice.time=true
#jmeter.save.saveservice.subresults=true
#jmeter.save.saveservice.assertions=true
#jmeter.save.saveservice.latency=true
#jmeter.save.saveservice.samplerData=false
#jmeter.save.saveservice.responseHeaders=false
#jmeter.save.saveservice.requestHeaders=false
#jmeter.save.saveservice.encoding=false
#jmeter.save.saveservice.bytes=true
#jmeter.save.saveservice.url=false
#jmeter.save.saveservice.filename=false
#jmeter.save.saveservice.hostname=false
#jmeter.save.saveservice.thread_counts=false
#jmeter.save.saveservice.sample_count=false
#jmeter.save.saveservice.idle_time=false
#jmeter.save.saveservice.timestamp_format=ms
#jmeter.save.saveservice.timestamp_format=yyyy/MM/dd HH:mm:ss.SSS
#jmeter.save.saveservice.default_delimiter=,
#jmeter.save.saveservice.default_delimiter=\t
#jmeter.save.saveservice.print_field_names=false
#jmeter.save.saveservice.xml_pi=<?xml-stylesheet type="text/xsl" href="../extras/jmeter-results-detail-report_21.xsl"?>
#jmeter.save.saveservice.base_prefix=~/
#jmeter.save.saveservice.autoflush=false

Uncomment the one you are interested in and set it's value to change the default. Another option is override property in user.properties file or provide it as a command-line argument using -J key as follows:

jmeter -Jjmeter.save.saveservice.print_field_names=true -n /path/to/your/test.jmx -l /path/to/results/file.jtl

See Apache JMeter Properties Customization Guide for more details on what can be done using JMeter Properties.

Replace specific characters within strings

With a regular expression and the function gsub():

group <- c("12357e", "12575e", "197e18", "e18947")
group
[1] "12357e" "12575e" "197e18" "e18947"

gsub("e", "", group)
[1] "12357" "12575" "19718" "18947"

What gsub does here is to replace each occurrence of "e" with an empty string "".


See ?regexp or gsub for more help.

How to select an element with 2 classes

You can chain class selectors without a space between them:

.a.b {
     color: #666;
}

Note that, if it matters to you, IE6 treats .a.b as .b, so in that browser both div.a.b and div.b will have gray text. See this answer for a comparison between proper browsers and IE6.

ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

It looks like that's an "unhandled exception", meaning the cmdlet itself hasn't been coded to recognize and handle that exception. It blew up without ever getting to run it's internal error handling, so the -ErrorAction setting on the cmdlet never came into play.

Way to get number of digits in an int?

Curious, I tried to benchmark it ...

import org.junit.Test;
import static org.junit.Assert.*;


public class TestStack1306727 {

    @Test
    public void bench(){
        int number=1000;
        int a= String.valueOf(number).length();
        int b= 1 + (int)Math.floor(Math.log10(number));

        assertEquals(a,b);
        int i=0;
        int s=0;
        long startTime = System.currentTimeMillis();
        for(i=0, s=0; i< 100000000; i++){
            a= String.valueOf(number).length();
            s+=a;
        }
        long stopTime = System.currentTimeMillis();
        long runTime = stopTime - startTime;
        System.out.println("Run time 1: " + runTime);
        System.out.println("s: "+s);
        startTime = System.currentTimeMillis();
        for(i=0,s=0; i< 100000000; i++){
            b= number==0?1:(1 + (int)Math.floor(Math.log10(Math.abs(number))));
            s+=b;
        }
        stopTime = System.currentTimeMillis();
        runTime = stopTime - startTime;
        System.out.println("Run time 2: " + runTime);
        System.out.println("s: "+s);
        assertEquals(a,b);


    }
}

the results are :

Run time 1: 6765
s: 400000000
Run time 2: 6000
s: 400000000

Now I am left to wonder if my benchmark actually means something but I do get consistent results (variations within a ms) over multiple runs of the benchmark itself ... :) It looks like it's useless to try and optimize this...


edit: following ptomli's comment, I replaced 'number' by 'i' in the code above and got the following results over 5 runs of the bench :

Run time 1: 11500
s: 788888890
Run time 2: 8547
s: 788888890

Run time 1: 11485
s: 788888890
Run time 2: 8547
s: 788888890

Run time 1: 11469
s: 788888890
Run time 2: 8547
s: 788888890

Run time 1: 11500
s: 788888890
Run time 2: 8547
s: 788888890

Run time 1: 11484
s: 788888890
Run time 2: 8547
s: 788888890

Is the 'as' keyword required in Oracle to define an alias?

My conclusion is that(Tested on 12c):

  • AS is always optional, either with or without ""; AS makes no difference (column alias only, you can not use AS preceding table alias)
  • However, with or without "" does make difference because "" lets lower case possible for an alias

thus :

SELECT {T / t} FROM (SELECT 1 AS T FROM DUAL); -- Correct
SELECT "tEST" FROM (SELECT 1 AS "tEST" FROM DUAL); -- Correct
SELECT {"TEST" / tEST} FROM (SELECT 1 AS "tEST" FROM DUAL ); -- Incorrect

SELECT test_value AS "doggy" FROM test ORDER BY "doggy"; --Correct
SELECT test_value AS "doggy" FROM test WHERE "doggy" IS NOT NULL; --You can not do this, column alias not supported in WHERE & HAVING
SELECT * FROM test "doggy" WHERE "doggy".test_value IS NOT NULL; -- Do not use AS preceding table alias

So, the reason why USING AS AND "" causes problem is NOT AS

Note: "" double quotes are required if alias contains space OR if it contains lower-case characters and MUST show-up in Result set as lower-case chars. In all other scenarios its OPTIONAL and can be ignored.

Remove everything after a certain character

If you also want to keep "?" and just remove everything after that particular character, you can do:

var str = "/Controller/Action?id=11112&value=4444",
    stripped = str.substring(0, str.indexOf('?') + '?'.length);

// output: /Controller/Action?

How to use http.client in Node.js if there is basic authorization

var http = require("http");
var url = "http://api.example.com/api/v1/?param1=1&param2=2";

var options = {
    host: "http://api.example.com",
    port: 80,
    method: "GET",
    path: url,//I don't know for some reason i have to use full url as a path
    auth: username + ':' + password
};

http.get(options, function(rs) {
    var result = "";
    rs.on('data', function(data) {
        result += data;
    });
    rs.on('end', function() {
        console.log(result);
    });
});

socket.error:[errno 99] cannot assign requested address and namespace in python

This error will also appear if you try to connect to an exposed port from within a Docker container, when nothing is actively serving the port.

On a host where nothing is listening/bound to that port you'd get a No connection could be made because the target machine actively refused it error instead when making a request to a local URL that is not served, eg: localhost:5000. However, if you start a container that binds to the port, but there is no server running inside of it actually serving the port, any requests to that port on localhost will result in:

  • [Errno 99] Cannot assign requested address (if called from within the container), or
  • [Errno 0] Error (if called from outside of the container).

You can reproduce this error and the behaviour described above as follows:

Start a dummy container (note: this will pull the python image if not found locally):

docker run --name serv1 -p 5000:5000 -dit python

Then for [Errno 0] Error enter a Python console on host, while for [Errno 99] Cannot assign requested address access a Python console on the container by calling:

docker exec -it -u 0 serv1 python

And then in either case call:

import urllib.request
urllib.request.urlopen('https://localhost:5000')

I concluded with treating either of these errors as equivalent to No connection could be made because the target machine actively refused it rather than trying to fix their cause - although please advise if that's a bad idea.


I've spent over a day figuring this one out, given that all resources and answers I could find on the [Errno 99] Cannot assign requested address point in the direction of binding to an occupied port, connecting to an invalid IP, sysctl conflicts, docker network issues, TIME_WAIT being incorrect, and many more things. Therefore I wanted to leave this answer here, despite not being a direct answer to the question at hand, given that it can be a common cause for the error described in this question.

Make header and footer files to be included in multiple html pages

You can accomplish this with jquery.

Place this code in index.html

<html>
<head>
<title></title>
<script
    src="https://code.jquery.com/jquery-3.3.1.js"
    integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
    crossorigin="anonymous">
</script>
<script> 
$(function(){
  $("#header").load("header.html"); 
  $("#footer").load("footer.html"); 
});
</script> 
</head>
<body>
<div id="header"></div>
<!--Remaining section-->
<div id="footer"></div>
</body>
</html>

and put this code in header.html and footer.html, at the same location as index.html

<a href="http://www.google.com">click here for google</a>

Now, when you visit index.html, you should be able to click the link tags.

HTML5 video won't play in Chrome only

Have you tried by setting the MIME type of your .m4v to "video/m4v" or "video/x-m4v" ?

Browsers might use the canPlayType method internally to check if a <source> is candidate to playback.

In Chrome, I have these results:

document.createElement("video").canPlayType("video/mp4"); // "maybe"
document.createElement("video").canPlayType("video/m4v"); // ""
document.createElement("video").canPlayType("video/x-m4v"); // "maybe"

How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"

Since there's no mention of how to compile a .c file together with a bunch of .o files, and this comment asks for it:

where's the main.c in this answer? :/ if file1.c is the main, how do you link it with other already compiled .o files? – Tom Brito Oct 12 '14 at 19:45

$ gcc main.c lib_obj1.o lib_obj2.o lib_objN.o -o x0rbin

Here, main.c is the C file with the main() function and the object files (*.o) are precompiled. GCC knows how to handle these together, and invokes the linker accordingly and results in a final executable, which in our case is x0rbin.

You will be able to use functions not defined in the main.c but using an extern reference to functions defined in the object files (*.o).

You can also link with .obj or other extensions if the object files have the correct format (such as COFF).

Reload a DIV without reloading the whole page

Your code works, but the fadeIn doesn't, because it's already visible. I think the effect you want to achieve is: fadeOutloadfadeIn:

var auto_refresh = setInterval(function () {
    $('.View').fadeOut('slow', function() {
        $(this).load('/echo/json/', function() {
            $(this).fadeIn('slow');
        });
    });
}, 15000); // refresh every 15000 milliseconds

Try it here: http://jsfiddle.net/kelunik/3qfNn/1/

Additional notice: As Khanh TO mentioned, you may need to get rid of the browser's internal cache. You can do so using $.ajax and $.ajaxSetup ({ cache: false }); or the random-hack, he mentioned.

How to terminate script execution when debugging in Google Chrome?

One way you can do it is pause the script, look at what code follows where you are currently stopped, e.g.:

var something = somethingElse.blah;

In the console, do the following:

delete somethingElse;

Then play the script: it will cause a fatal error when it tries to access somethingElse, and the script will die. Voila, you've terminated the script.

EDIT: Originally, I deleted a variable. That's not good enough. You have to delete a function or an object of which JavaScript attempts to access a property.

Writing to CSV with Python adds blank lines

import csv

hello = [['Me','You'],['293', '219'],['13','15']]
length = len(hello[0])

with open('test1.csv', 'wb') as testfile:
    csv_writer = csv.writer(testfile)
    for y in range(length):
        csv_writer.writerow([x[y] for x in hello])

will produce an output like this

Me You
293 219
13 15

Hope this helps

C# "as" cast vs classic cast

In some cases, it's easily to deal with a null than an exception. In particular, the coalescing operator is handy:

SomeClass someObject = (obj as SomeClass) ?? new SomeClass();

It also simplifies code where you are (not using polymorphism, and) branching based on the type of an object:

ClassA a;
ClassB b;
if ((a = obj as ClassA) != null)
{
    // use a
}
else if ((b = obj as ClassB) != null)
{
    // use b
}

As specified on the MSDN page, the as operator is equivalent to:

expression is type ? (type)expression : (type)null

which avoids the exception completely in favour of a faster type test, but also limits its use to types that support null (reference types and Nullable<T>).

Check if a value exists in pandas dataframe index

Code below does not print boolean, but allows for dataframe subsetting by index... I understand this is likely not the most efficient way to solve the problem, but I (1) like the way this reads and (2) you can easily subset where df1 index exists in df2:

df3 = df1[df1.index.isin(df2.index)]

or where df1 index does not exist in df2...

df3 = df1[~df1.index.isin(df2.index)]

How to find the maximum value in an array?

Have a max int and set it to the first value in the array. Then in a for loop iterate through the whole array and see if the max int is larger than the int at the current index.

int max = array.get(0);

for (int i = 1; i < array.length; i++) {
    if (array.get(i) > max) {
      max = array.get(i);
    }
}

Linux bash: Multiple variable assignment

I wanted to assign the values to an array. So, extending Michael Krelin's approach, I did:

read a[{1..3}] <<< $(echo 2 4 6); echo "${a[1]}|${a[2]}|${a[3]}"

which yields:

2|4|6 

as expected.

Create a simple Login page using eclipse and mysql

You Can simply Use One Jsp Page To accomplish the task.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
   <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <%
        String username=request.getParameter("user_name");
        String password=request.getParameter("password");
        String role=request.getParameter("role");
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
            Statement st=con.createStatement();
            String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
            ResultSet rs=st.executeQuery(query);
            while(rs.next())
            {
                session.setAttribute( "user_name",rs.getString(2));
                session.setMaxInactiveInterval(3000);
                response.sendRedirect("homepage.jsp");
            }
            %>



        <%}
        catch(Exception e)
        {
            out.println(e);
        }
    %>

</body>

I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.

Using jquery to get all checked checkboxes with a certain class name

$('input.yourClass:checkbox:checked').each(function () {
    var sThisVal = $(this).val();
});

This would get all checkboxes of the class name "yourClass". I like this example since it uses the jQuery selector checked instead of doing a conditional check. Personally I would also use an array to store the value, then use them as needed, like:

var arr = [];
$('input.yourClass:checkbox:checked').each(function () {
    arr.push($(this).val());
});

How do you calculate log base 2 in Java for integers?

let's add:

int[] fastLogs;

private void populateFastLogs(int length) {
    fastLogs = new int[length + 1];
    int counter = 0;
    int log = 0;
    int num = 1;
    fastLogs[0] = 0;
    for (int i = 1; i < fastLogs.length; i++) {
        counter++;
        fastLogs[i] = log;
        if (counter == num) {
            log++;
            num *= 2;
            counter = 0;
        }
    }
}

Source: https://github.com/pochuan/cs166/blob/master/ps1/rmq/SparseTableRMQ.java

Contains case insensitive

There are a couple of approaches here.

If you want to perform a case-insensitive check for just this instance, do something like the following.

if (referrer.toLowerCase().indexOf("Ral".toLowerCase()) == -1) {
    ...

Alternatively, if you're performing this check regularly, you can add a new indexOf()-like method to String, but make it case insensitive.

String.prototype.indexOfInsensitive = function (s, b) {
    return this.toLowerCase().indexOf(s.toLowerCase(), b);
}

// Then invoke it
if (referrer.indexOfInsensitive("Ral") == -1) { ...

How to use Git Revert

git revert makes a new commit

git revert simply creates a new commit that is the opposite of an existing commit.

It leaves the files in the same state as if the commit that has been reverted never existed. For example, consider the following simple example:

$ cd /tmp/example
$ git init
Initialized empty Git repository in /tmp/example/.git/
$ echo "Initial text" > README.md
$ git add README.md
$ git commit -m "initial commit"
[master (root-commit) 3f7522e] initial commit
 1 file changed, 1 insertion(+)
 create mode 100644 README.md
$ echo "bad update" > README.md 
$ git commit -am "bad update"
[master a1b9870] bad update
 1 file changed, 1 insertion(+), 1 deletion(-)

In this example the commit history has two commits and the last one is a mistake. Using git revert:

$ git revert HEAD
[master 1db4eeb] Revert "bad update"
 1 file changed, 1 insertion(+), 1 deletion(-)

There will be 3 commits in the log:

$ git log --oneline
1db4eeb Revert "bad update"
a1b9870 bad update
3f7522e initial commit

So there is a consistent history of what has happened, yet the files are as if the bad update never occured:

cat README.md 
Initial text

It doesn't matter where in the history the commit to be reverted is (in the above example, the last commit is reverted - any commit can be reverted).

Closing questions

do you have to do something else after?

A git revert is just another commit, so e.g. push to the remote so that other users can pull/fetch/merge the changes and you're done.

Do you have to commit the changes revert made or does revert directly commit to the repo?

git revert is a commit - there are no extra steps assuming reverting a single commit is what you wanted to do.

Obviously you'll need to push again and probably announce to the team.

Indeed - if the remote is in an unstable state - communicating to the rest of the team that they need to pull to get the fix (the reverting commit) would be the right thing to do :).

Is Google Play Store supported in avd emulators?

Yes, you can enable/use Play Store on Android Emulator(AVD): Before that you have to set up some prerequisites:

  1. Start Android SDK Manager and select Google Play Intel x86 Atom System Image (Recomended: because it will work comparatively faster) of your required android version (For Example: Android 7.1.1 or API 25)

[Note: Please keep all other thing as it is, if you are going to install it for first time] Or Install as the image below: enter image description here

  1. After download is complete Goto Tools->Manage AVDs...->Create from your Android SDK Manager

  2. enter image description here

Check you have provided following option correctly. Not sure about internal and SD card storage. You can choose different. And Target must be your downloaded android version

  1. Also check Google Play Intel Atom (x86) in CPU/ABI is provided

  2. Click OK

  3. Then Start your Android Emulator. There you will see the Android Play Store. See --- enter image description here

Get resultset from oracle stored procedure

CREATE OR REPLACE PROCEDURE SP_Invoices(p_nameClient IN CHAR)
AS
BEGIN       
    FOR c_invoice IN 
    (
       SELECT CodeInvoice, NameClient FROM Invoice
       WHERE NameClient = p_nameClient
    )
    LOOP
        dbms_output.put_line('Code Invoice: ' || c_invoice.CodeInvoice);
        dbms_output.put_line('Name Client : ' ||  c_invoice.NameClient );
    END LOOP;
END;

Executing in SQL Developer:

BEGIN
    SP_Invoices('Perico de los palotes');
END;
-- Or:
EXEC SP_Invoices('Perico de los palotes');

Output:

> Code Invoice: 1 
> Name Client : Perico de los palotes
> Code Invoice: 2 
> Name Client : Perico de los palotes

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

java_home environment variable should point to the location of the proper version of java installation directory, so that tomcat starts with the right version. for example it you built the project with java 1.7 , then make sure that JAVA_HOME environment variable points to the jdk 1.7 installation directory in your machine.

I had same problem , when i deploy the war in tomcat and run, the link throws the error. But pointing the variable - JAVA_HOME to jdk 1.7 resolved the issue, as my war file was built in java 1.7 environment.

How can I remove Nan from list Python/NumPy

import numpy as np

mylist = [3, 4, 5, np.nan]
l = [x for x in mylist if ~np.isnan(x)]

This should remove all NaN. Of course, I assume that it is not a string here but actual NaN (np.nan).

How to write inline if statement for print?

hmmm, you can do it with a list comprehension. This would only make sense if you had a real range.. but it does do the job:

print([a for i in range(0,1) if b])

or using just those two variables:

print([a for a in range(a,a+1) if b])

Rails - controller action name to string

I just did the same. I did it in helper controller, my code is:

def get_controller_name
  controller_name    
end


def get_action_name
  action_name   
end

These methods will return current contoller and action name. Hope it helps

Set 4 Space Indent in Emacs in Text Mode

Do not confuse variable tab-width with variable tab-stop-list. The former is used for the display of literal TAB characters. The latter controls what characters are inserted when you press the TAB character in certain modes.

-- GNU Emacs Manual

(customize-variable (quote tab-stop-list))

or add tab-stop-list entry to custom-set-variables in .emacs file:

(custom-set-variables
  ;; custom-set-variables was added by Custom.
  ;; If you edit it by hand, you could mess it up, so be careful.
  ;; Your init file should contain only one such instance.
  ;; If there is more than one, they won't work right.
 '(tab-stop-list (quote (4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80 84 88 92 96 100 104 108 112 116 120))))

Another way to edit the tab behavior is with with M-x edit-tab-stops.

See the GNU Emacs Manual on Tab Stops for more information on edit-tab-stops.

How to declare an array of strings in C++?

Problems - no way to get the number of strings automatically (that i know of).

There is a bog-standard way of doing this, which lots of people (including MS) define macros like arraysize for:

#define arraysize(ar)  (sizeof(ar) / sizeof(ar[0]))

Run "mvn clean install" in Eclipse

You can create external command Run -> External Tools -> External Tools Configuration...

It will be available under Run -> External Tools and can be run using shortcuts.

How to force a hover state with jQuery?

Also, you could try triggering a mouseover.

$("#btn").click(function() {
   $("#link").trigger("mouseover");
});

Not sure if this will work for your specific scenario, but I've had success triggering mouseover instead of hover for various cases.

Editor does not contain a main type

If it is maven project please check the java file is created under src/main/java

If you are not getting please change the JRE path and create the java files in above folder structure

What's the difference between a Future and a Promise?

For client code, Promise is for observing or attaching callback when a result is available, whereas Future is to wait for result and then continue. Theoretically anything which is possible to do with futures what can done with promises, but due to the style difference, the resultant API for promises in different languages make chaining easier.

How to remove all white spaces from a given text file

Much simpler to my opinion:

sed -r 's/\s+//g' filename

How to obtain the last index of a list?

I guess you want

last_index = len(list1) - 1 

which would store 3 in last_index.

Execute method on startup in Spring

For a file StartupHousekeeper.java located in package com.app.startup,

Do this in StartupHousekeeper.java:

@Component
public class StartupHousekeeper {

  @EventListener(ContextRefreshedEvent.class)
  public void keepHouse() {
    System.out.println("This prints at startup.");
  }
}

And do this in myDispatcher-servlet.java:

<?xml version="1.0" encoding="UTF-8"?>
<beans>

    <mvc:annotation-driven />
    <context:component-scan base-package="com.app.startup" />

</beans>

commands not found on zsh

For me just restarting my terminal seemed to fix the issue.

Getting first value from map in C++

begin() returns the first pair, (precisely, an iterator to the first pair, and you can access the key/value as ->first and ->second of that iterator)

Deleting a file in VBA

Here's a tip: are you re-using the file name, or planning to do something that requires the deletion immediately?

No?

You can get VBA to fire the command DEL "C:\TEMP\scratchpad.txt" /F from the command prompt asynchronously using VBA.Shell:

Shell "DEL " & chr(34) & strPath & chr(34) & " /F ", vbHide

Note the double-quotes (ASCII character 34) around the filename: I'm assuming that you've got a network path, or a long file name containing spaces.

If it's a big file, or it's on a slow network connection, fire-and-forget is the way to go. Of course, you never get to see if this worked or not; but you resume your VBA immediately, and there are times when this is better than waiting for the network.

Difference between | and || or & and && for comparison

in C (and other languages probably) a single | or & is a bitwise comparison.
The double || or && is a logical comparison.
Edit: Be sure to read Mehrdad's comment below regarding "without short-circuiting"

In practice, since true is often equivalent to 1 and false is often equivalent to 0, the bitwise comparisons can sometimes be valid and return exactly the same result.

There was once a mission critical software component I ran a static code analyzer on and it pointed out that a bitwise comparison was being used where a logical comparison should have been. Since it was written in C and due to the arrangement of logical comparisons, the software worked just fine with either. Example:

if ( (altitide > 10000) & (knots > 100) )
...

Add text to textarea - Jquery

That should work. Better if you pass a function to val:

$('#replyBox').val(function(i, text) {
    return text + quote;
});

This way you avoid searching the element and calling val twice.

Browser Caching of CSS files

That depends on what headers you are sending along with your CSS files. Check your server configuration as you are probably not sending them manually. Do a google search for "http caching" to learn about different caching options you can set. You can force the browser to download a fresh copy of the file everytime it loads it for instance, or you can cache the file for one week...

Rails 3.1 and Image Assets

http://railscasts.com/episodes/279-understanding-the-asset-pipeline

This railscast (Rails Tutorial video on asset pipeline) helps a lot to explain the paths in assets pipeline as well. I found it pretty useful, and actually watched it a few times.

The solution I chose is @Lee McAlilly's above, but this railscast helped me to understand why it works. Hope it helps!

How do I get the function name inside a function in PHP?

The accurate way is to use the __FUNCTION__ predefined magic constant.

Example:

class Test {
    function MethodA(){
        echo __FUNCTION__;
    }
}

Result: MethodA.

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

It does not natively, but you certainly can add this functionality

<script type="text/javascript">

String.prototype.regexIndexOf = function( pattern, startIndex )
{
    startIndex = startIndex || 0;
    var searchResult = this.substr( startIndex ).search( pattern );
    return ( -1 === searchResult ) ? -1 : searchResult + startIndex;
}

String.prototype.regexLastIndexOf = function( pattern, startIndex )
{
    startIndex = startIndex === undefined ? this.length : startIndex;
    var searchResult = this.substr( 0, startIndex ).reverse().regexIndexOf( pattern, 0 );
    return ( -1 === searchResult ) ? -1 : this.length - ++searchResult;
}

String.prototype.reverse = function()
{
    return this.split('').reverse().join('');
}

// Indexes 0123456789
var str = 'caabbccdda';

alert( [
        str.regexIndexOf( /[cd]/, 4 )
    ,   str.regexLastIndexOf( /[cd]/, 4 )
    ,   str.regexIndexOf( /[yz]/, 4 )
    ,   str.regexLastIndexOf( /[yz]/, 4 )
    ,   str.lastIndexOf( 'd', 4 )
    ,   str.regexLastIndexOf( /d/, 4 )
    ,   str.lastIndexOf( 'd' )
    ,   str.regexLastIndexOf( /d/ )
    ]
);

</script>

I didn't fully test these methods, but they seem to work so far.

php/mySQL on XAMPP: password for phpMyAdmin and mysql_connect different?

You need to change the password directly in the database because at mysql the users and their profiles are saved in the database.

So there are several ways. At phpMyAdmin you simple go to user admin, choose root and change the password.

Where does linux store my syslog?

Default log location (rhel) are

General messages:

/var/log/messages

Authentication messages:

/var/log/secure

Mail events:

/var/log/maillog

Check your /etc/syslog.conf or /etc/syslog-ng.conf (it depends on which of syslog facility you have installed)

Example:

$ cat /etc/syslog.conf
# Log anything (except mail) of level info or higher.
# Don't log private authentication messages!
*.info;mail.none;authpriv.none         /var/log/messages

# The authpriv file has restricted access.
authpriv.*                             /var/log/secure

# Log all the mail messages in one place.
mail.*                                 /var/log/maillog

#For a start, use this simplified approach.
*.*                                     /var/log/messages

Java switch statement: Constant expression required, but it IS constant

I recommend you to use enums :)

Check this out:

public enum Foo 
{
    BAR("bar"),
    BAZ("baz"),
    BAM("bam");

    private final String description;

    private Foo(String description)
    {
        this.description = description;
    }

    public String getDescription()
    {
        return description;
    }
}

Then you can use it like this:

System.out.println(Foo.BAR.getDescription());

What is the C# Using block and why should I use it?

using (B a = new B())
{
   DoSomethingWith(a);
}

is equivalent to

B a = new B();
try
{
  DoSomethingWith(a);
}
finally
{
   ((IDisposable)a).Dispose();
}

Sorting rows in a data table

Did you try using the Select(filterExpression, sortOrder) method on DataTable? See here for an example. Note this method will not sort the data table in place, if that is what you are looking for, but it will return a sorted array of rows without using a data view.

How to calculate sum of a formula field in crystal Reports?

You Can simply Right Click Formula Fields- > new Give it a name like TotalCount then Right this code:

if(isnull(sum(count({YOURCOLUMN})))) then
0
else
(sum(count({YOURCOLUMN})))

and Save then Drag and drop TotalCount this field in header/footer. After you open the "count" bracket you can drop your column there from the above section.See the example in the Pictureenter image description here

Detecting an undefined object property

I use if (this.variable) to test if it is defined. A simple if (variable), recommended in a previous answer, fails for me.

It turns out that it works only when a variable is a field of some object, obj.someField to check if it is defined in the dictionary. But we can use this or window as the dictionary object since any variable is a field in the current window, as I understand it. Therefore here is a test:

_x000D_
_x000D_
if (this.abc) 
    alert("defined"); 
else 
    alert("undefined");

abc = "abc";
if (this.abc) 
    alert("defined"); 
else 
    alert("undefined");
_x000D_
_x000D_
_x000D_

It first detects that variable abc is undefined and it is defined after initialization.

SQL Server ON DELETE Trigger

INSERTED and DELETED are virtual tables. They need to be used in a FROM clause.

CREATE TRIGGER sampleTrigger
    ON database1.dbo.table1
    FOR DELETE
AS
    IF EXISTS (SELECT foo
               FROM database2.dbo.table2
               WHERE id IN (SELECT deleted.id FROM deleted)
               AND bar = 4)

AngularJS HTTP post to PHP and undefined

In the API I am developing I have a base controller and inside its __construct() method I have the following:

if(isset($_SERVER["CONTENT_TYPE"]) && strpos($_SERVER["CONTENT_TYPE"], "application/json") !== false) {
    $_POST = array_merge($_POST, (array) json_decode(trim(file_get_contents('php://input')), true));
}

This allows me to simply reference the json data as $_POST["var"] when needed. Works great.

That way if an authenticated user connects with a library such a jQuery that sends post data with a default of Content-Type: application/x-www-form-urlencoded or Content-Type: application/json the API will respond without error and will make the API a little more developer friendly.

Hope this helps.

Automatically resize images with browser size using CSS

This may be too simplistic of an answer (I am still new here), but what I have done in the past to remedy this situation is figured out the percentage of the screen I would like the image to take up. For example, there is one webpage I am working on where the logo must take up 30% of the screen size to look best. I played around and finally tried this code and it has worked for me thus far:

img {
width:30%;
height:auto;
}

That being said, this will change all of your images to be 30% of the screen size at all times. To get around this issue, simply make this a class and apply it to the image that you desire to be at 30% directly. Here is an example of the code I wrote to accomplish this on the aforementioned site:

the CSS portion:

.logo {
position:absolute;
right:25%;
top:0px;
width:30%;
height:auto;
}

the HTML portion:

<img src="logo_001_002.png" class="logo">

Alternatively, you could place ever image you hope to automatically resize into a div of its own and use the class tag option on each div (creating now class tags whenever needed), but I feel like that would cause a lot of extra work eventually. But, if the site calls for it: the site calls for it.

Hopefully this helps. Have a great day!

How to state in requirements.txt a direct github source

requirements.txt allows the following ways of specifying a dependency on a package in a git repository as of pip 7.0:1

[-e] git+git://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+https://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+ssh://git.myproject.org/SomeProject#egg=SomeProject
-e [email protected]:SomeProject#egg=SomeProject (deprecated as of Jan 2020)

For Github that means you can do (notice the omitted -e):

git+git://github.com/mozilla/elasticutils.git#egg=elasticutils

Why the extra answer?
I got somewhat confused by the -e flag in the other answers so here's my clarification:

The -e or --editable flag means that the package is installed in <venv path>/src/SomeProject and thus not in the deeply buried <venv path>/lib/pythonX.X/site-packages/SomeProject it would otherwise be placed in.2

Documentation

JPA: how do I persist a String into a database field, type MYSQL Text

With @Lob I always end up with a LONGTEXTin MySQL.

To get TEXT I declare it that way (JPA 2.0):

@Column(columnDefinition = "TEXT")
private String text

Find this better, because I can directly choose which Text-Type the column will have in database.

For columnDefinition it is also good to read this.

EDIT: Please pay attention to Adam Siemions comment and check the database engine you are using, before applying columnDefinition = "TEXT".

Java 8 stream reverse order

How about reversing the Collection backing the stream prior?

import java.util.Collections;
import java.util.List;

public void reverseTest(List<Integer> sampleCollection) {
    Collections.reverse(sampleCollection); // remember this reverses the elements in the list, so if you want the original input collection to remain untouched clone it first.

    sampleCollection.stream().forEach(item -> {
      // you op here
    });
}

Set element focus in angular way

I prefered to use an expression. This lets me do stuff like focus on a button when a field is valid, reaches a certain length, and of course after load.

<button type="button" moo-focus-expression="form.phone.$valid">
<button type="submit" moo-focus-expression="smsconfirm.length == 6">
<input type="text" moo-focus-expression="true">

On a complex form this also reduces need to create additional scope variables for the purposes of focusing.

See https://stackoverflow.com/a/29963695/937997

Why is there no tuple comprehension in Python?

Raymond Hettinger (one of the Python core developers) had this to say about tuples in a recent tweet:

#python tip: Generally, lists are for looping; tuples for structs. Lists are homogeneous; tuples heterogeneous. Lists for variable length.

This (to me) supports the idea that if the items in a sequence are related enough to be generated by a, well, generator, then it should be a list. Although a tuple is iterable and seems like simply a immutable list, it's really the Python equivalent of a C struct:

struct {
    int a;
    char b;
    float c;
} foo;

struct foo x = { 3, 'g', 5.9 };

becomes in Python

x = (3, 'g', 5.9)

What Are The Best Width Ranges for Media Queries

best bet is targeting features not devices unless you have to, bootstrap do well and you can extend on their breakpoints, for instance targeting pixel density and larger screens above 1920

Javascript - get array of dates between 2 dates

I have been using @Mohammed Safeer solution for a while and I made a few improvements. Using formated dates is a bad practice while working in your controllers. moment().format() should be used only for display purposes in views. Also remember that moment().clone() ensures separation from input parameters, meaning that the input dates are not altered. I strongly encourage you to use moment.js when working with dates.

Usage:

  • Provide moment.js dates as values for startDate, endDate parameters
  • interval parameter is optional and defaults to 'days'. Use intervals suported by .add() method (moment.js). More details here
  • total parameter is useful when specifying intervals in minutes. It defaults to 1.

Invoke:

var startDate = moment(),
    endDate = moment().add(1, 'days');

getDatesRangeArray(startDate, endDate, 'minutes', 30);

Function:

var getDatesRangeArray = function (startDate, endDate, interval, total) {
    var config = {
            interval: interval || 'days',
            total: total || 1
        },
        dateArray = [],
        currentDate = startDate.clone();

    while (currentDate < endDate) {
        dateArray.push(currentDate);
        currentDate = currentDate.clone().add(config.total, config.interval);
    }

    return dateArray;
};

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

How to display hexadecimal numbers in C?

Try:

printf("%04x",a);
  • 0 - Left-pads the number with zeroes (0) instead of spaces, where padding is specified.
  • 4 (width) - Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is right justified within this width by padding on the left with the pad character. By default this is a blank space, but the leading zero we used specifies a zero as the pad char. The value is not truncated even if the result is larger.
  • x - Specifier for hexadecimal integer.

More here

Playing m3u8 Files with HTML Video Tag

In normally html5 video player will support mp4, WebM, 3gp and OGV format directly.

    <video controls>
      <source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
      <source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
      <source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
      <source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
    </video>

We can add an external HLS js script in web application.

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset=utf-8 />
    <title>Your title</title>
      
    
      <link href="https://unpkg.com/video.js/dist/video-js.css" rel="stylesheet">
      <script src="https://unpkg.com/video.js/dist/video.js"></script>
      <script src="https://unpkg.com/videojs-contrib-hls/dist/videojs-contrib-hls.js"></script>
       
    </head>
    <body>
      <video id="my_video_1" class="video-js vjs-fluid vjs-default-skin" controls preload="auto"
      data-setup='{}'>
        <source src="https://cdn3.wowza.com/1/ejBGVnFIOW9yNlZv/cithRSsv/hls/live/playlist.m3u8" type="application/x-mpegURL">
      </video>
      
    <script>
    var player = videojs('my_video_1');
    player.play();
    </script>
      
    </body>
    </html>

UTF-8 text is garbled when form is posted as multipart/form-data

You do not use UTF-8 to encode text data for HTML forms. The html standard defines two encodings, and the relevant part of that standard is here. The "old" encoding, than handles ascii, is application/x-www-form-urlencoded. The new one, that works properly, is multipart/form-data.

Specifically, the form declaration looks like this:

 <FORM action="http://server.com/cgi/handle"
       enctype="multipart/form-data"
       method="post">
   <P>
   What is your name? <INPUT type="text" name="submit-name"><BR>
   What files are you sending? <INPUT type="file" name="files"><BR>
   <INPUT type="submit" value="Send"> <INPUT type="reset">
 </FORM>

And I think that's all you have to worry about - the webserver should handle it. If you are writing something that directly reads the InputStream from the web client, then you will need to read RFC 2045 and RFC 2046.

How to Automatically Close Alerts using Twitter Bootstrap

I could not get it to work with alert.('close') either.

However I am using this and it works a treat! The alert will fade away after 5 seconds, and once gone, the content below it will slide up to its natural position.

window.setTimeout(function() {
    $(".alert-message").fadeTo(500, 0).slideUp(500, function(){
        $(this).remove(); 
    });
}, 5000);

Scheduling recurring task in Android

I am not sure but as per my knowledge I share my views. I always accept best answer if I am wrong .

Alarm Manager

The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive() returns, the Alarm Manager releases this wake lock. This means that the phone will in some cases sleep as soon as your onReceive() method completes. If your alarm receiver called Context.startService(), it is possible that the phone will sleep before the requested service is launched. To prevent this, your BroadcastReceiver and Service will need to implement a separate wake lock policy to ensure that the phone continues running until the service becomes available.

Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.

Timer

timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {

        synchronized public void run() {

            \\ here your todo;
            }

        }, TimeUnit.MINUTES.toMillis(1), TimeUnit.MINUTES.toMillis(1));

Timer has some drawbacks that are solved by ScheduledThreadPoolExecutor. So it's not the best choice

ScheduledThreadPoolExecutor.

You can use java.util.Timer or ScheduledThreadPoolExecutor (preferred) to schedule an action to occur at regular intervals on a background thread.

Here is a sample using the latter:

ScheduledExecutorService scheduler =
    Executors.newSingleThreadScheduledExecutor();

scheduler.scheduleAtFixedRate
      (new Runnable() {
         public void run() {
            // call service
         }
      }, 0, 10, TimeUnit.MINUTES);

So I preferred ScheduledExecutorService

But Also think about that if the updates will occur while your application is running, you can use a Timer, as suggested in other answers, or the newer ScheduledThreadPoolExecutor. If your application will update even when it is not running, you should go with the AlarmManager.

The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running.

Take note that if you plan on updating when your application is turned off, once every ten minutes is quite frequent, and thus possibly a bit too power consuming.

Run Executable from Powershell script with parameters

Try quoting the argument list:

Start-Process -FilePath "C:\Program Files\MSBuild\test.exe" -ArgumentList "/genmsi/f $MySourceDirectory\src\Deployment\Installations.xml"

You can also provide the argument list as an array (comma separated args) but using a string is usually easier.

How to cache data in a MVC application

HttpContext.Current.Cache.Insert("subjectlist", subjectlist);

How to validate an email address using a regular expression?

I never bother creating with my own regular expression, because chances are that someone else has already come up with a better version. I always use regexlib to find one to my liking.

How to drop rows from pandas data frame that contains a particular string in a particular column?

This will only work if you want to compare exact strings. It will not work in case you want to check if the column string contains any of the strings in the list.

The right way to compare with a list would be :

searchfor = ['john', 'doe']
df = df[~df.col.str.contains('|'.join(searchfor))]

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

How to scroll to the bottom of a UITableView on the iPhone before the view appears

Actually a "Swifter" way to do it in swift is :

var lastIndex = NSIndexPath(forRow: self.messages.count - 1, inSection: 0)
self.messageTableView.scrollToRowAtIndexPath(lastIndex, atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)

work Perfect for me.

ipynb import another ipynb file

The issue is that a notebooks is not a plain python file. The steps to import the .ipynb file are outlined in the following: Importing notebook

I am pasting the code, so if you need it...you can just do a quick copy and paste. Notice that at the end I have the import primes statement. You'll have to change that of course. The name of my file is primes.ipynb. From this point on you can use the content inside that file as you would do regularly.

Wish there was a simpler method, but this is straight from the docs.
Note: I am using jupyter not ipython.

import io, os, sys, types
from IPython import get_ipython
from nbformat import current
from IPython.core.interactiveshell import InteractiveShell


def find_notebook(fullname, path=None):
    """find a notebook, given its fully qualified name and an optional path

    This turns "foo.bar" into "foo/bar.ipynb"
    and tries turning "Foo_Bar" into "Foo Bar" if Foo_Bar
    does not exist.
    """
    name = fullname.rsplit('.', 1)[-1]
    if not path:
        path = ['']
    for d in path:
        nb_path = os.path.join(d, name + ".ipynb")
        if os.path.isfile(nb_path):
            return nb_path
        # let import Notebook_Name find "Notebook Name.ipynb"
        nb_path = nb_path.replace("_", " ")
        if os.path.isfile(nb_path):
            return nb_path


class NotebookLoader(object):
    """Module Loader for Jupyter Notebooks"""
    def __init__(self, path=None):
        self.shell = InteractiveShell.instance()
        self.path = path

    def load_module(self, fullname):
        """import a notebook as a module"""
        path = find_notebook(fullname, self.path)

        print ("importing Jupyter notebook from %s" % path)

        # load the notebook object
        with io.open(path, 'r', encoding='utf-8') as f:
            nb = current.read(f, 'json')


        # create the module and add it to sys.modules
        # if name in sys.modules:
        #    return sys.modules[name]
        mod = types.ModuleType(fullname)
        mod.__file__ = path
        mod.__loader__ = self
        mod.__dict__['get_ipython'] = get_ipython
        sys.modules[fullname] = mod

        # extra work to ensure that magics that would affect the user_ns
        # actually affect the notebook module's ns
        save_user_ns = self.shell.user_ns
        self.shell.user_ns = mod.__dict__

        try:
        for cell in nb.worksheets[0].cells:
            if cell.cell_type == 'code' and cell.language == 'python':
                # transform the input to executable Python
                code = self.shell.input_transformer_manager.transform_cell(cell.input)
                # run the code in themodule
                exec(code, mod.__dict__)
        finally:
            self.shell.user_ns = save_user_ns
        return mod


class NotebookFinder(object):
    """Module finder that locates Jupyter Notebooks"""
    def __init__(self):
        self.loaders = {}

    def find_module(self, fullname, path=None):
        nb_path = find_notebook(fullname, path)
        if not nb_path:
            return

        key = path
        if path:
            # lists aren't hashable
            key = os.path.sep.join(path)

        if key not in self.loaders:
            self.loaders[key] = NotebookLoader(path)
        return self.loaders[key]

sys.meta_path.append(NotebookFinder())

import primes

Is JavaScript's "new" keyword considered harmful?

Another case for new is what I call Pooh Coding. Winnie the Pooh follows his tummy. I say go with the language you are using, not against it.

Chances are that the maintainers of the language will optimize the language for the idioms they try to encourage. If they put a new keyword into the language they probably think it makes sense to be clear when creating a new instance.

Code written following the language's intentions will increase in efficiency with each release. And code avoiding the key constructs of the language will suffer with time.

EDIT: And this goes well beyond performance. I can't count the times I've heard (or said) "why the hell did they do that?" when finding strange looking code. It often turns out that at the time when the code was written there was some "good" reason for it. Following the Tao of the language is your best insurance for not having your code ridiculed some years from now.

How do I remove a substring from the end of a string in Python?

Because this is a very popular question i add another, now available, solution. With python 3.9 (https://docs.python.org/3.9/whatsnew/3.9.html) the function removesuffix() will be added (and removeprefix()) and this function is exactly what was questioned here.

url = 'abcdc.com'
print(url.removesuffix('.com'))

output:

'abcdc'

PEP 616 (https://www.python.org/dev/peps/pep-0616/) shows how it will behave (it is not the real implementation):

def removeprefix(self: str, prefix: str, /) -> str:
    if self.startswith(prefix):
        return self[len(prefix):]
    else:
        return self[:]

and what benefits it has against self-implemented solutions:

  1. Less fragile: The code will not depend on the user to count the length of a literal.

  2. More performant: The code does not require a call to the Python built-in len function nor to the more expensive str.replace() method.

  3. More descriptive: The methods give a higher-level API for code readability as opposed to the traditional method of string slicing.

Android Lint contentDescription warning

Resolved this warning by setting attribute android:contentDescription for my ImageView

android:contentDescription="@string/desc"

Android Lint support in ADT 16 throws this warning to ensure that image widgets provide a contentDescription.

This defines text that briefly describes content of the view. This property is used primarily for accessibility. Since some views do not have textual representation this attribute can be used for providing such.

Non-textual widgets like ImageViews and ImageButtons should use the contentDescription attribute to specify a textual description of the widget such that screen readers and other accessibility tools can adequately describe the user interface.

Removing certain characters from a string in R

This should work

gsub('\u009c','','\u009cYes yes for ever for ever the boys ')
"Yes yes for ever for ever the boys "

Here 009c is the hexadecimal number of unicode. You must always specify 4 hexadecimal digits. If you have many , one solution is to separate them by a pipe:

gsub('\u009c|\u00F0','','\u009cYes yes \u00F0for ever for ever the boys and the girls')

"Yes yes for ever for ever the boys and the girls"

Set a variable if undefined in JavaScript

I needed to "set a variable if undefined" in several places. I created a function using @Alnitak answer. Hopefully it helps someone.

function setDefaultVal(value, defaultValue){
   return (value === undefined) ? defaultValue : value;
}  

Usage:

hasPoints = setDefaultVal(this.hasPoints, true);

How to add data via $.ajax ( serialize() + extra data ) like this

You can do it like this:

postData[postData.length] = { name: "variable_name", value: variable_value };

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

Another possible cause of similar issue could be wrong processorArchitecture in the cx_freeze manifest, trying to load x86 common controls dll in x64 process - should be fixed by this patch:

https://bitbucket.org/anthony_tuininga/cx_freeze/pull-request/71/changed-x86-in-windows-manifest-to/diff