Programs & Examples On #Scala java interop

How to add new activity to existing project in Android Studio?

I think natually do it is straightforward, whether Intellij IDEA or Android Studio, I always click new Java class menu, and then typing the class name, press Enter to create. after that, I manually typing "extends Activity" in the class file, and then import the class by shortcut key. finally, I also manually override the onCreate() method and invoke the setContentView() method.

Python: How exactly can you take a string, split it, reverse it and join it back together again?

I was asked to do so without using any inbuilt function. So I wrote three functions for these tasks. Here is the code-

def string_to_list(string):
'''function takes actual string and put each word of string in a list'''
list_ = []
x = 0 #Here x tracks the starting of word while y look after the end of word.
for y in range(len(string)):
    if string[y]==" ":
        list_.append(string[x:y])
        x = y+1
    elif y==len(string)-1:
        list_.append(string[x:y+1])
return list_

def list_to_reverse(list_):
'''Function takes the list of words and reverses that list'''
reversed_list = []
for element in list_[::-1]:
    reversed_list.append(element)
return reversed_list

def list_to_string(list_):
'''This function takes the list and put all the elements of the list to a string with 
space as a separator'''
final_string = str()
for element in list_:
    final_string += str(element) + " "
return final_string

#Output
text = "I love India"
list_ = string_to_list(text)
reverse_list = list_to_reverse(list_)
final_string = list_to_string(reverse_list)
print("Input is - {}; Output is - {}".format(text, final_string))
#op= Input is - I love India; Output is - India love I 

Please remember, This is one of a simpler solution. This can be optimized so try that. Thank you!

How to avoid pressing Enter with getchar() for reading a single character only?

I've had this problem/question come up in an assignment that I'm currently working on. It also depends on which input you are grabbing from. I am using

/dev/tty

to get input while the program is running, so that needs to be the filestream associated with the command.

On the ubuntu machine I have to test/target, it required more than just

system( "stty -raw" );

or

system( "stty -icanon" );

I had to add the --file flag, as well as path to the command, like so:

system( "/bin/stty --file=/dev/tty -icanon" );

Everything is copacetic now.

Concatenate in jQuery Selector

There is nothing wrong with syntax of

$('#part' + number).html(text);

jQuery accepts a String (usually a CSS Selector) or a DOM Node as parameter to create a jQuery Object.

In your case you should pass a String to $() that is

$(<a string>)

Make sure you have access to the variables number and text.

To test do:

function(){
    alert(number + ":" + text);//or use console.log(number + ":" + text)
    $('#part' + number).html(text);
}); 

If you see you dont have access, pass them as parameters to the function, you have to include the uual parameters for $.get and pass the custom parameters after them.

Parallel.ForEach vs Task.Factory.StartNew

Parallel.ForEach will optimize(may not even start new threads) and block until the loop is finished, and Task.Factory will explicitly create a new task instance for each item, and return before they are finished (asynchronous tasks). Parallel.Foreach is much more efficient.

Online code beautifier and formatter

JsonLint is good for validating and formatting JSON.

Checking if a worksheet-based checkbox is checked

It seems that in VBA macro code for an ActiveX checkbox control you use

If (ActiveSheet.OLEObjects("CheckBox1").Object.Value = True)

and for a Form checkbox control you use

If (ActiveSheet.Shapes("CheckBox1").OLEFormat.Object.Value = 1)

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

The docs give a pretty good explanation of the difference between apply() and commit():

Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself. As SharedPreferences instances are singletons within a process, it's safe to replace any instance of commit() with apply() if you were already ignoring the return value.

JavaScript string and number conversion

These questions come up all the time due to JavaScript's typing system. People think they are getting a number when they're getting the string of a number.

Here are some things you might see that take advantage of the way JavaScript deals with strings and numbers. Personally, I wish JavaScript had used some symbol other than + for string concatenation.

Step (1) Concatenate "1", "2", "3" into "123"

result = "1" + "2" + "3";

Step (2) Convert "123" into 123

result = +"123";

Step (3) Add 123 + 100 = 223

result = 123 + 100;

Step (4) Convert 223 into "223"

result = "" + 223;

If you know WHY these work, you're less likely to get into trouble with JavaScript expressions.

.mp4 file not playing in chrome

I too had the same issue. I changed the codec to H264-MPEG-4 AVC and the videos started working in HTML5/Chrome.

Option selected in converter: H264-MPEG-4 AVC, Codec visible in VLC player: H264-MPEG-4 AVC (part 10) (avc1)

Hope it helps...

React Hooks useState() with Object

I'm late to the party.. :)

@aseferov answer works very well when the intention is to re-enter the entire object structure. However, if the target/goal is to update a specific field value in an Object, I believe the approach below is better.

situation:

const [infoData, setInfoData] = useState({
    major: {
      name: "John Doe",
      age: "24",
      sex: "M",
    },

    minor:{
      id: 4,
      collegeRegion: "south",

    }

  });

Updating a specific record will require making a recall to the previous State prevState

Here:

setInfoData((prevState) => ({
      ...prevState,
      major: {
        ...prevState.major,
        name: "Tan Long",
      }
    }));

perhaps

setInfoData((prevState) => ({
      ...prevState,
      major: {
        ...prevState.major,
        name: "Tan Long",
      },
      minor: {
        ...prevState.minor,
        collegeRegion: "northEast"

    }));

I hope this helps anyone trying to solve a similar problem.

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

DataTable's Select method only supports simple filtering expressions like {field} = {value}. It does not support complex expressions, let alone SQL/Linq statements.

You can, however, use Linq extension methods to extract a collection of DataRows then create a new DataTable.

dt = dt.AsEnumerable()
       .GroupBy(r => new {Col1 = r["Col1"], Col2 = r["Col2"]})
       .Select(g => g.OrderBy(r => r["PK"]).First())
       .CopyToDataTable();

Correct way of getting Client's IP Addresses from http.Request

Here a completely working example

package main

import (  
    // Standard library packages
    "fmt"
    "strconv"
    "log"
    "net"
    "net/http"

    // Third party packages
    "github.com/julienschmidt/httprouter"
    "github.com/skratchdot/open-golang/open"
)



// https://blog.golang.org/context/userip/userip.go
func getIP(w http.ResponseWriter, req *http.Request, _ httprouter.Params){
    fmt.Fprintf(w, "<h1>static file server</h1><p><a href='./static'>folder</p></a>")

    ip, port, err := net.SplitHostPort(req.RemoteAddr)
    if err != nil {
        //return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)

        fmt.Fprintf(w, "userip: %q is not IP:port", req.RemoteAddr)
    }

    userIP := net.ParseIP(ip)
    if userIP == nil {
        //return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)
        fmt.Fprintf(w, "userip: %q is not IP:port", req.RemoteAddr)
        return
    }

    // This will only be defined when site is accessed via non-anonymous proxy
    // and takes precedence over RemoteAddr
    // Header.Get is case-insensitive
    forward := req.Header.Get("X-Forwarded-For")

    fmt.Fprintf(w, "<p>IP: %s</p>", ip)
    fmt.Fprintf(w, "<p>Port: %s</p>", port)
    fmt.Fprintf(w, "<p>Forwarded for: %s</p>", forward)
}


func main() {  
    myport := strconv.Itoa(10002);


    // Instantiate a new router
    r := httprouter.New()

    r.GET("/ip", getIP)

    // Add a handler on /test
    r.GET("/test", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
        // Simply write some test data for now
        fmt.Fprint(w, "Welcome!\n")
    })  


    l, err := net.Listen("tcp", "localhost:" + myport)
    if err != nil {
        log.Fatal(err)
    }
    // The browser can connect now because the listening socket is open.


    //err = open.Start("http://localhost:"+ myport + "/test")
    err = open.Start("http://localhost:"+ myport + "/ip")
    if err != nil {
         log.Println(err)
    }

    // Start the blocking server loop.
    log.Fatal(http.Serve(l, r)) 
}

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

Find Locked Table in SQL Server

You can use sp_lock (and sp_lock2), but in SQL Server 2005 onwards this is being deprecated in favour of querying sys.dm_tran_locks:

select  
    object_name(p.object_id) as TableName, 
    resource_type, resource_description
from
    sys.dm_tran_locks l
    join sys.partitions p on l.resource_associated_entity_id = p.hobt_id

How to run a program without an operating system?

I wrote a c++ program based on Win32 to write an assembly to the boot sector of a pen-drive. When the computer is booted from the pen-drive it executes the code successfully - have a look here C++ Program to write to the boot sector of a USB Pendrive

This program is a few lines that should be compiled on a compiler with windows compilation configured - such as a visual studio compiler - any available version.

Java: method to get position of a match in a String?

The family of methods that does this are:

Returns the index within this string of the first (or last) occurrence of the specified substring [searching forward (or backward) starting at the specified index].


String text = "0123hello9012hello8901hello7890";
String word = "hello";

System.out.println(text.indexOf(word)); // prints "4"
System.out.println(text.lastIndexOf(word)); // prints "22"

// find all occurrences forward
for (int i = -1; (i = text.indexOf(word, i + 1)) != -1; i++) {
    System.out.println(i);
} // prints "4", "13", "22"

// find all occurrences backward
for (int i = text.length(); (i = text.lastIndexOf(word, i - 1)) != -1; i++) {
    System.out.println(i);
} // prints "22", "13", "4"

C# : assign data to properties via constructor vs. instantiating

Object initializers are cool because they allow you to set up a class inline. The tradeoff is that your class cannot be immutable. Consider:

public class Album 
{
    // Note that we make the setter 'private'
    public string Name { get; private set; }
    public string Artist { get; private set; }
    public int Year { get; private set; }

    public Album(string name, string artist, int year)
    {
        this.Name = name;
        this.Artist = artist;
        this.Year = year;
    }
}

If the class is defined this way, it means that there isn't really an easy way to modify the contents of the class after it has been constructed. Immutability has benefits. When something is immutable, it is MUCH easier to determine that it's correct. After all, if it can't be modified after construction, then there is no way for it to ever be 'wrong' (once you've determined that it's structure is correct). When you create anonymous classes, such as:

new { 
    Name = "Some Name",
    Artist = "Some Artist",
    Year = 1994
};

the compiler will automatically create an immutable class (that is, anonymous classes cannot be modified after construction), because immutability is just that useful. Most C++/Java style guides often encourage making members const(C++) or final (Java) for just this reason. Bigger applications are just much easier to verify when there are fewer moving parts.

That all being said, there are situations when you want to be able quickly modify the structure of your class. Let's say I have a tool that I want to set up:

public void Configure(ConfigurationSetup setup);

and I have a class that has a number of members such as:

class ConfigurationSetup {
    public String Name { get; set; }
    public String Location { get; set; }
    public Int32 Size { get; set; }
    public DateTime Time { get; set; }

    // ... and some other configuration stuff... 
}

Using object initializer syntax is useful when I want to configure some combination of properties, but not neccesarily all of them at once. For example if I just want to configure the Name and Location, I can just do:

ConfigurationSetup setup = new ConfigurationSetup {
    Name = "Some Name",
    Location = "San Jose"
};

and this allows me to set up some combination without having to define a new constructor for every possibly permutation.

On the whole, I would argue that making your classes immutable will save you a great deal of development time in the long run, but having object initializer syntax makes setting up certain configuration permutations much easier.

Use formula in custom calculated field in Pivot Table

I'll post this comment as answer, as I'm confident enough that what I asked is not possible.

I) Couple of similar questions trying to do the same, without success:

II) This article: Excel Pivot Table Calculated Field for example lists many restrictions of Calculated Field:

  • For calculated fields, the individual amounts in the other fields are summed, and then the calculation is performed on the total amount.
  • Calculated field formulas cannot refer to the pivot table totals or subtotals
  • Calculated field formulas cannot refer to worksheet cells by address or by name.
  • Sum is the only function available for a calculated field.
  • Calculated fields are not available in an OLAP-based pivot table.

III) There is tiny limited possibility to use AVERAGE() and similar function for a range of cells, but that applies only if Pivot table doesn't have grouped cells, which allows listing the cells as items in new group (right to "Fileds" listbox in above screenshot) and then user can calculate AVERAGE(), referencing explicitly every item (cell), from Items listbox, as argument. Maybe it's better explained here: Calculate values in a PivotTable report
For my Pivot table it wasn't applicable because my range wasn't small enough, this option to be sane choice.

Exec : display stdout "live"

Don't use exec. Use spawn which is an EventEmmiter object. Then you can listen to stdout/stderr events (spawn.stdout.on('data',callback..)) as they happen.

From NodeJS documentation:

var spawn = require('child_process').spawn,
    ls    = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', function (data) {
  console.log('stdout: ' + data.toString());
});

ls.stderr.on('data', function (data) {
  console.log('stderr: ' + data.toString());
});

ls.on('exit', function (code) {
  console.log('child process exited with code ' + code.toString());
});

exec buffers the output and usually returns it when the command has finished executing.

What does (function($) {})(jQuery); mean?

Actually, this example helped me to understand what does (function($) {})(jQuery); mean.

Consider this:

// Clousure declaration (aka anonymous function)
var f = function(x) { return x*x; };
// And use of it
console.log( f(2) ); // Gives: 4

// An inline version (immediately invoked)
console.log( (function(x) { return x*x; })(2) ); // Gives: 4

And now consider this:

  • jQuery is a variable holding jQuery object.
  • $ is a variable name like any other (a, $b, a$b etc.) and it doesn't have any special meaning like in PHP.

Knowing that we can take another look at our example:

var $f = function($) { return $*$; };
var jQuery = 2;
console.log( $f(jQuery) ); // Gives: 4

// An inline version (immediately invoked)
console.log( (function($) { return $*$; })(jQuery) ); // Gives: 4

PHP header() redirect with POST variables

If you don't want to use sessions, the only thing you can do is POST to the same page. Which IMO is the best solution anyway.

// form.php

<?php

    if (!empty($_POST['submit'])) {
        // validate

        if ($allGood) {
            // put data into database or whatever needs to be done

            header('Location: nextpage.php');
            exit;
        }
    }

?>

<form action="form.php">
    <input name="foo" value="<?php if (!empty($_POST['foo'])) echo htmlentities($_POST['foo']); ?>">
    ...
</form>

This can be made more elegant, but you get the idea...

How do I make an editable DIV look like a text field?

In WebKit, you can do: -webkit-appearance: textarea;

jQuery change URL of form submit

Try using this:

$(".move_to").on("click", function(e){
    e.preventDefault();
    $('#contactsForm').attr('action', "/test1").submit();
});

Moving the order in which you use .preventDefault() might fix your issue. You also didn't use function(e) so e.preventDefault(); wasn't working.

Here it is working: http://jsfiddle.net/TfTwe/1/ - first of all, click the 'Check action attribute.' link. You'll get an alert saying undefined. Then click 'Set action attribute.' and click 'Check action attribute.' again. You'll see that the form's action attribute has been correctly set to /test1.

Error: 10 $digest() iterations reached. Aborting! with dynamic sortby predicate

I got this error in the context of angular tree control. In my case it was the tree options. I was returning treeOptions() from a function. It was always returning the same object. But Angular magically thinks that its a new object and then cause a digest cycle to kick off. Causing a recursion of digests. The solution was to bind the treeOptions to scope. And assign it just once.

How to enable PHP short tags?

This can be done by enabling short_open_tag in php.ini:

short_open_tag = on

If you don't have access to the php.ini you can try to enable them trough the .htaccess file but it's possible the hosting company disabled this if you are on shared hosting:

php_value short_open_tag 1

For the people thinking that short_open_tags are bad practice as of php 5.4 the <?= ... ?> shorttag will supported everywhere, regardless of the settings so there is no reason not to use them if you can control the settings on the server. Also said in this link: short_open_tag

Why are Python's 'private' methods not actually private?

The name scrambling is used to ensure that subclasses don't accidentally override the private methods and attributes of their superclasses. It's not designed to prevent deliberate access from outside.

For example:

>>> class Foo(object):
...     def __init__(self):
...         self.__baz = 42
...     def foo(self):
...         print self.__baz
...     
>>> class Bar(Foo):
...     def __init__(self):
...         super(Bar, self).__init__()
...         self.__baz = 21
...     def bar(self):
...         print self.__baz
...
>>> x = Bar()
>>> x.foo()
42
>>> x.bar()
21
>>> print x.__dict__
{'_Bar__baz': 21, '_Foo__baz': 42}

Of course, it breaks down if two different classes have the same name.

Wait .5 seconds before continuing code VB.net

This question is old but here is another answer because it is useful fo others:

thread.sleep is not a good method for waiting, because usually it freezes the software until finishing its time, this function is better:

   Imports VB = Microsoft.VisualBasic

   Public Sub wait(ByVal seconds As Single)
     Static start As Single
     start = VB.Timer()
     Do While VB.Timer() < start + seconds
       System.Windows.Forms.Application.DoEvents()
     Loop
   End Sub

The above function waits for a specific time without freezing the software, however increases the CPU usage.

This function not only doesn't freeze the software, but also doesn't increase the CPU usage:

   Private Sub wait(ByVal seconds As Integer)
     For i As Integer = 0 To seconds * 100
       System.Threading.Thread.Sleep(10)
       Application.DoEvents()
     Next
   End Sub

How to set DialogFragment's width and height?

When I need to make the DialogFragment a bit wider I'm setting minWidth:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minWidth="320dp"
    ... />

PHP - Notice: Undefined index:

How are you loading this page? Is it getting anything on POST to load? If it's not, then the $name = $_POST['Name']; assignation doesn't have any 'Name' on POST.

String formatting in Python 3

Here are the docs about the "new" format syntax. An example would be:

"({:d} goals, ${:d})".format(self.goals, self.penalties)

If both goals and penalties are integers (i.e. their default format is ok), it could be shortened to:

"({} goals, ${})".format(self.goals, self.penalties)

And since the parameters are fields of self, there's also a way of doing it using a single argument twice (as @Burhan Khalid noted in the comments):

"({0.goals} goals, ${0.penalties})".format(self)

Explaining:

  • {} means just the next positional argument, with default format;
  • {0} means the argument with index 0, with default format;
  • {:d} is the next positional argument, with decimal integer format;
  • {0:d} is the argument with index 0, with decimal integer format.

There are many others things you can do when selecting an argument (using named arguments instead of positional ones, accessing fields, etc) and many format options as well (padding the number, using thousands separators, showing sign or not, etc). Some other examples:

"({goals} goals, ${penalties})".format(goals=2, penalties=4)
"({goals} goals, ${penalties})".format(**self.__dict__)

"first goal: {0.goal_list[0]}".format(self)
"second goal: {.goal_list[1]}".format(self)

"conversion rate: {:.2f}".format(self.goals / self.shots) # '0.20'
"conversion rate: {:.2%}".format(self.goals / self.shots) # '20.45%'
"conversion rate: {:.0%}".format(self.goals / self.shots) # '20%'

"self: {!s}".format(self) # 'Player: Bob'
"self: {!r}".format(self) # '<__main__.Player instance at 0x00BF7260>'

"games: {:>3}".format(player1.games)  # 'games: 123'
"games: {:>3}".format(player2.games)  # 'games:   4'
"games: {:0>3}".format(player2.games) # 'games: 004'

Note: As others pointed out, the new format does not supersede the former, both are available both in Python 3 and the newer versions of Python 2 as well. Some may say it's a matter of preference, but IMHO the newer is much more expressive than the older, and should be used whenever writing new code (unless it's targeting older environments, of course).

Byte Array and Int conversion in Java

Instead of allocating space, et al, an approach using ByteBuffer from java.nio....

byte[] arr = { 0x01, 0x00, 0x00, 0x00, 0x48, 0x01};

// say we want to consider indices 1, 2, 3, 4 {0x00, 0x00, 0x00, 0x48};
ByteBuffer bf = ByteBuffer.wrap(arr, 1, 4); // big endian by default
int num = bf.getInt();    // 72

Now, to go the other way.

ByteBuffer newBuf = ByteBuffer.allocate(4);
newBuf.putInt(num);
byte[] bytes = newBuf.array();  // [0, 0, 0, 72] {0x48 = 72}

How to alter SQL in "Edit Top 200 Rows" in SSMS 2008

Ctrl+3 in SQL Server 2012. Might work in 2008 too

Error "library not found for" after putting application in AdMob

It is compile time error for a Static Library that is caused by Static Linker

ld: library not found for -l<Library_name>
  1. You can get the error Library not found for when you have not include a library path to the Library Search Paths

ld means Static Linker which can not find a location of the library. As a developer you should help the linker and point the Library Search Paths

```
Build Settings -> Search Paths -> Library Search Paths 
```
  1. Also you can get this error if you first time open a new project (.xcodeproj) with Cocoapods support, run pod update. To fix it just close this project and open created a workspace instead (.xcworkspace )

[Vocabulary]

window.print() not working in IE

This worked for me, it works in firefox, ie and chrome.

    var content = "This is a test Message";

    var contentHtml = [
        '<div><b>',
        'TestReport',
        '<button style="float:right; margin-right:10px;"',
        'id="printButton" onclick="printDocument()">Print</button></div>',
        content
    ].join('');

    var printWindow = window.open();

    printWindow.document.write('<!DOCTYPE HTML><html><head<title>Reports</title>',
        '<script>function printDocument() {',
        'window.focus();',
        'window.print();',
        'window.close();',
        '}',
        '</script>');

    printWindow.document.write("stylesheet link here");

    printWindow.document.write('</head><body>');
    printWindow.document.write(contentHtml);
    printWindow.document.write('</body>');
    printWindow.document.write('</html>');
    printWindow.document.close();

SQLAlchemy default DateTime

DateTime doesn't have a default key as an input. The default key should be an input to the Column function. Try this:

import datetime
from sqlalchemy import Column, Integer, DateTime
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Test(Base):
    __tablename__ = 'test'

    id = Column(Integer, primary_key=True)
    created_date = Column(DateTime, default=datetime.datetime.utcnow)

Alternative to file_get_contents?

Yes, if you have URL wrappers disabled you should use sockets or, even better, the cURL library.

If it's part of your site then refer to it with the file system path, not the web URL. /var/www/..., rather than http://domain.tld/....

Cannot find Dumpbin.exe

As for VS2017, I found it under C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.14.26428\bin\Hostx64\x64

Python to print out status bar and percentage

Easiest is still

import sys
total_records = 1000
for i in range (total_records):
    sys.stdout.write('\rUpdated record: ' + str(i) + ' of ' + str(total_records))
    sys.stdout.flush()

Key is to convert the integer type to string.

"NoClassDefFoundError: Could not initialize class" error

I recently ran into this error on Windows 10. It turned out that windows was looking for .dll files necessary for my project and couldn't find them because it looks for them in the system path, PATH, rather than the CLASSPATH or -Djava.library.path

Difference between RUN and CMD in a Dockerfile

There has been enough answers on RUN and CMD. I just want to add a few words on ENTRYPOINT. CMD arguments can be overwritten by command line arguments, while ENTRYPOINT arguments are always used.

This article is a good source of information.

Insert line break inside placeholder attribute of a textarea?

I liked the work of Jason Gennaro and Denis Golomazov, but I wanted something that would be more globally useful. I have modified the concept so that it can be added to any page without repercussion.

http://jsfiddle.net/pdXRx/297/

<h1>Demo: 5 different textarea placeholder behaviors from a single JS</h1>

<h2>Modified behaviors</h2>

<!-- To get simulated placeholder with New Lines behavior,
     add the placeholdernl attribute -->

<textarea placeholdernl>    (click me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<textarea placeholder='Address' placeholdernl>    (click me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<h2>Standard behaviors</h2>

<textarea placeholder='Address'>    (delete me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<textarea>    (delete me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<textarea placeholder='Address'></textarea>

The javascript is very simple

<script>
(function($){
var handleFocus = function(){
    var $this = $(this);
    if($this.val() === $this.attr('placeholdernl')){
        $this.attr('value', '');
        $this.css('color', '');
    }
};

var handleBlur = function(){
    var $this = $(this);
    if($this.val() == ''){
        $this.attr('value', $this.attr('placeholdernl'))
        $this.css('color', 'gray');
    }    
};

$('textarea[placeholdernl]').each(function(){
    var $this = $(this),
        value = $this.attr('value'),
        placeholder = $this.attr('placeholder');
    $this.attr('placeholdernl', value ? value : placeholder);
    $this.attr('value', '');
    $this.focus(handleFocus).blur(handleBlur).trigger('blur');
});
})(jQuery);
</script>

Android: Pass data(extras) to a fragment

Two things. First I don't think you are adding the data that you want to pass to the fragment correctly. What you need to pass to the fragment is a bundle, not an intent. For example if I wanted send an int value to a fragment I would create a bundle, put the int into that bundle, and then set that bundle as an argument to be used when the fragment was created.

Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

Second to retrieve that information you need to get the arguments sent to the fragment. You then extract the value based on the key you identified it with. For example in your fragment:

Bundle bundle = this.getArguments();
if (bundle != null) {
    int i = bundle.getInt(key, defaulValue);
}

What you are getting changes depending on what you put. Also the default value is usually null but does not need to be. It depends on if you set a default value for that argument.

Lastly I do not think you can do this in onCreateView. I think you must retrieve this data within your fragment's onActivityCreated method. My reasoning is as follows. onActivityCreated runs after the underlying activity has finished its own onCreate method. If you are placing the information you wish to retrieve within the bundle durring your activity's onCreate method, it will not exist during your fragment's onCreateView. Try using this in onActivityCreated and just update your ListView contents later.

How do I remove the "extended attributes" on a file in Mac OS X?

Another recursive approach:

# change directory to target folder:
cd /Volumes/path/to/folder

# find all things of type "f" (file), 
# then pipe "|" each result as an argument (xargs -0) 
# to the "xattr -c" command:
find . -type f -print0 | xargs -0 xattr -c

# Sometimes you may have to use a star * instead of the dot.
# The dot just means "here" (whereever your cd'd to
find * -type f -print0 | xargs -0 xattr -c

Setting an int to Infinity in C++

Integers are finite, so sadly you can't have set it to a true infinity. However you can set it to the max value of an int, this would mean that it would be greater or equal to any other int, ie:

a>=b

is always true.

You would do this by

#include <limits>

//your code here

int a = std::numeric_limits<int>::max();

//go off and lead a happy and productive life

This will normally be equal to 2,147,483,647

If you really need a true "infinite" value, you would have to use a double or a float. Then you can simply do this

float a = std::numeric_limits<float>::infinity();

Additional explanations of numeric limits can be found here

Happy Coding!

Note: As WTP mentioned, if it is absolutely necessary to have an int that is "infinite" you would have to write a wrapper class for an int and overload the comparison operators, though this is probably not necessary for most projects.

How to ignore SSL certificate errors in Apache HttpClient 4.0

If you are using Apache httpClient 4.5.x then try this:

public static void main(String... args)  {

    try (CloseableHttpClient httpclient = createAcceptSelfSignedCertificateClient()) {
        HttpGet httpget = new HttpGet("https://example.com");
        System.out.println("Executing request " + httpget.getRequestLine());

        httpclient.execute(httpget);
        System.out.println("----------------------------------------");
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | IOException e) {
        throw new RuntimeException(e);
    }
}

private static CloseableHttpClient createAcceptSelfSignedCertificateClient()
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {

    // use the TrustSelfSignedStrategy to allow Self Signed Certificates
    SSLContext sslContext = SSLContextBuilder
            .create()
            .loadTrustMaterial(new TrustSelfSignedStrategy())
            .build();

    // we can optionally disable hostname verification. 
    // if you don't want to further weaken the security, you don't have to include this.
    HostnameVerifier allowAllHosts = new NoopHostnameVerifier();

    // create an SSL Socket Factory to use the SSLContext with the trust self signed certificate strategy
    // and allow all hosts verifier.
    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, allowAllHosts);

    // finally create the HttpClient using HttpClient factory methods and assign the ssl socket factory
    return HttpClients
            .custom()
            .setSSLSocketFactory(connectionFactory)
            .build();
}

MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

Delete all documents from a collection in cmd:

cd C:\Program Files\MongoDB\Server\4.2\bin
mongo
use yourdb
db.yourcollection.remove( { } )

Java: Check if enum contains a given string?

With guava it's even simpler:

boolean isPartOfMyEnum(String myString){

return Lists.newArrayList(MyEnum.values().toString()).contains(myString);

}

Remove characters except digits from string using Python?

Use a generator expression:

>>> s = "foo200bar"
>>> new_s = "".join(i for i in s if i in "0123456789")

Get human readable version of file size?

Drawing from all the previous answers, here is my take on it. It's an object which will store the file size in bytes as an integer. But when you try to print the object, you automatically get a human readable version.

class Filesize(object):
    """
    Container for a size in bytes with a human readable representation
    Use it like this::

        >>> size = Filesize(123123123)
        >>> print size
        '117.4 MB'
    """

    chunk = 1024
    units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB']
    precisions = [0, 0, 1, 2, 2, 2]

    def __init__(self, size):
        self.size = size

    def __int__(self):
        return self.size

    def __str__(self):
        if self.size == 0: return '0 bytes'
        from math import log
        unit = self.units[min(int(log(self.size, self.chunk)), len(self.units) - 1)]
        return self.format(unit)

    def format(self, unit):
        if unit not in self.units: raise Exception("Not a valid file size unit: %s" % unit)
        if self.size == 1 and unit == 'bytes': return '1 byte'
        exponent = self.units.index(unit)
        quotient = float(self.size) / self.chunk**exponent
        precision = self.precisions[exponent]
        format_string = '{:.%sf} {}' % (precision)
        return format_string.format(quotient, unit)

Pass props in Link react-router

If you are just looking to replace the slugs in your routes, you can use generatePath that was introduced in react-router 4.3 (2018). As of today, it isn't included in the react-router-dom (web) documentation, but is in react-router (core). Issue#7679

// myRoutes.js
export const ROUTES = {
  userDetails: "/user/:id",
}


// MyRouter.jsx
import ROUTES from './routes'

<Route path={ROUTES.userDetails} ... />


// MyComponent.jsx
import { generatePath } from 'react-router-dom'
import ROUTES from './routes'

<Link to={generatePath(ROUTES.userDetails, { id: 1 })}>ClickyClick</Link>

It's the same concept that django.urls.reverse has had for a while.

Fixed positioned div within a relative parent div

here is a more generic solution, that don't depends on the Menu/Header height. its fully responsive, Pure CSS solution, Works great on IE8+, Firefox, Chrome, Safari, opera. supports Content scrolling without affecting the Menu/Header.

Test it with that Working Fiddle

The Html:

<div class="Container">
    <div class="First">
        <p>The First div height is not fixed</p>
        <p>This Layout has been tested on: IE10, IE9, IE8, FireFox, Chrome, Safari, using Pure CSS 2.1 only</p>
    </div>
    <div class="Second">
        <div class="Wrapper">
            <div class="Centered">
                <p>The Second div should always span the available Container space.</p>
                <p>This content is vertically Centered.</p>
            </div>
        </div>
    </div>
</div>

The CSS:

*
{
    margin: 0;
    padding: 0;
}

html, body, .Container
{
    height: 100%;
}

    .Container:before
    {
        content: '';
        height: 100%;
        float: left;
    }

.First
{
    /*for demonstration only*/
    background-color: #bf5b5b;
}

.Second
{
    position: relative;
    z-index: 1;
    /*for demonstration only*/
    background-color: #6ea364;
}

    .Second:after
    {
        content: '';
        clear: both;
        display: block;
    }

/*This part his relevant only for Vertically centering*/
.Wrapper
{
    position: absolute;
    width: 100%;
    height: 100%;
    overflow: auto;
}
    .Wrapper:before
    {
        content: '';
        display: inline-block;
        vertical-align: middle;
        height: 100%;
    }

.Centered
{
    display: inline-block;
    vertical-align: middle;
}

How can I measure the similarity between two images?

You can use Siamese Network to see if the two images are similar or dissimilar following this tutorial. This tutorial cluster the similar images whereas you can use L2 distance to measure the similarity of two images.

Annotation @Transactional. How to rollback?

You can throw an unchecked exception from the method which you wish to roll back. This will be detected by spring and your transaction will be marked as rollback only.

I'm assuming you're using Spring here. And I assume the annotations you refer to in your tests are the spring test based annotations.

The recommended way to indicate to the Spring Framework's transaction infrastructure that a transaction's work is to be rolled back is to throw an Exception from code that is currently executing in the context of a transaction.

and note that:

please note that the Spring Framework's transaction infrastructure code will, by default, only mark a transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException.

How can I insert multiple rows into oracle with a sequence value?

This works:

insert into TABLE_NAME (COL1,COL2)
select my_seq.nextval, a
from
(SELECT 'SOME VALUE' as a FROM DUAL
 UNION ALL
 SELECT 'ANOTHER VALUE' FROM DUAL)

Concatenate two NumPy arrays vertically

a = np.array([1,2,3])
b = np.array([4,5,6])
np.array((a,b))

works just as well as

np.array([[1,2,3], [4,5,6]])

Regardless of whether it is a list of lists or a list of 1d arrays, np.array tries to create a 2d array.

But it's also a good idea to understand how np.concatenate and its family of stack functions work. In this context concatenate needs a list of 2d arrays (or any anything that np.array will turn into a 2d array) as inputs.

np.vstack first loops though the inputs making sure they are at least 2d, then does concatenate. Functionally it's the same as expanding the dimensions of the arrays yourself.

np.stack is a new function that joins the arrays on a new dimension. Default behaves just like np.array.

Look at the code for these functions. If written in Python you can learn quite a bit. For vstack:

return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)

How do I get the last day of a month?

// Use any date you want, for the purpose of this example we use 1980-08-03.
var myDate = new DateTime(1980,8,3);
var lastDayOfMonth = new DateTime(myDate.Year, myDate.Month, DateTime.DaysInMonth(myDate.Year, myDate.Month));

Use URI builder in Android or create URL with variables

Best answer: https://stackoverflow.com/a/19168199/413127

Example for

 http://api.example.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7

Now with Kotlin

 val myUrl = Uri.Builder().apply {
        scheme("https")
        authority("www.myawesomesite.com")
        appendPath("turtles")
        appendPath("types")
        appendQueryParameter("type", "1")
        appendQueryParameter("sort", "relevance")
        fragment("section-name")
        build()            
    }.toString()

What is the difference between AF_INET and PF_INET in socket programming?

Beej's famous network programming guide gives a nice explanation:

In some documentation, you'll see mention of a mystical "PF_INET". This is a weird etherial beast that is rarely seen in nature, but I might as well clarify it a bit here. Once a long time ago, it was thought that maybe a address family (what the "AF" in "AF_INET" stands for) might support several protocols that were referenced by their protocol family (what the "PF" in "PF_INET" stands for).
That didn't happen. Oh well. So the correct thing to do is to use AF_INET in your struct sockaddr_in and PF_INET in your call to socket(). But practically speaking, you can use AF_INET everywhere. And, since that's what W. Richard Stevens does in his book, that's what I'll do here.

Set margins in a LinearLayout programmatically

Try this:

MarginLayoutParams params = (MarginLayoutParams) view.getLayoutParams();
params.width = 250;
params.leftMargin = 50;
params.topMargin = 50;

How to refresh page on back button click?

First of all insert field in your code:

<input id="reloadValue" type="hidden" name="reloadValue" value="" />

then run jQuery:

<script type="text/javascript">
   jQuery(document).ready(function()
    {
            var d = new Date();
            d = d.getTime();
            if (jQuery('#reloadValue').val().length === 0)
            {
                    jQuery('#reloadValue').val(d);
                    jQuery('body').show();
            }
            else
            {
                    jQuery('#reloadValue').val('');
                    location.reload();
            }
    });

Is generator.next() visible in Python 3?

g.next() has been renamed to g.__next__(). The reason for this is consistency: special methods like __init__() and __del__() all have double underscores (or "dunder" in the current vernacular), and .next() was one of the few exceptions to that rule. This was fixed in Python 3.0. [*]

But instead of calling g.__next__(), use next(g).

[*] There are other special attributes that have gotten this fix; func_name, is now __name__, etc.

CSS3 Transform Skew One Side

You try with the :before was pretty close, the only thing you had to change was actually using skew instead of the borders: http://jsfiddle.net/Hfkk7/1101/

Edit: Your border approach would work too, the only thing you did wrong was having the before element on top of your div, so the transparent border wasnt showing. If you would have position the pseudo element to the left of your div, everything would have worked too: http://jsfiddle.net/Hfkk7/1102/

Difference between Encapsulation and Abstraction

Encapsulation: Wrapping code and data together into a single unit. Class is an example of encapsulation, because it wraps the method and property.

Abstraction: Hiding internal details and showing functionality only. Abstraction focus on what the object does instead of how it does. It provides generalized view of classes.

int number = 5;
string aStringNumber = number.ToString(); 

Here, ToString() is abstraction. And how this mechanism number variable converted to string and initialize into aStringNumber is encapsulation.

Let us take a real world example of calculator. Encapsulation is the internal circuits, battery, etc., that combine to make it a calculator. Abstraction is the different buttons like on-off, clear and other buttons provided to operate it.

How to convert a Scikit-learn dataset to a Pandas dataset?

Took me 2 hours to figure this out

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris

iris = load_iris()
##iris.keys()


df= pd.DataFrame(data= np.c_[iris['data'], iris['target']],
                 columns= iris['feature_names'] + ['target'])

df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)

Get back the species for my pandas

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

Any easy way to use icons from resources?

  1. Add the icon to the project resources and rename to icon.

  2. Open the designer of the form you want to add the icon to.

  3. Append the InitializeComponent function.

  4. Add this line in the top:

    this.Icon = PROJECTNAME.Properties.Resources.icon;
    

    repeat step 4 for any forms in your project you want to update

bash shell nested for loop

The question does not contain a nested loop, just a single loop. But THIS nested version works, too:

# for i in c d; do for j in a b; do echo $i $j; done; done
c a
c b
d a
d b

Why does .json() return a promise?

This difference is due to the behavior of Promises more than fetch() specifically.

When a .then() callback returns an additional Promise, the next .then() callback in the chain is essentially bound to that Promise, receiving its resolve or reject fulfillment and value.

The 2nd snippet could also have been written as:

iterator.then(response =>
    response.json().then(post => document.write(post.title))
);

In both this form and yours, the value of post is provided by the Promise returned from response.json().


When you return a plain Object, though, .then() considers that a successful result and resolves itself immediately, similar to:

iterator.then(response =>
    Promise.resolve({
      data: response.json(),
      status: response.status
    })
    .then(post => document.write(post.data))
);

post in this case is simply the Object you created, which holds a Promise in its data property. The wait for that promise to be fulfilled is still incomplete.

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

PyPI packages not in the standard library:

  • virtualenv is a very popular tool that creates isolated Python environments for Python libraries. If you're not familiar with this tool, I highly recommend learning it, as it is a very useful tool, and I'll be making comparisons to it for the rest of this answer.

    It works by installing a bunch of files in a directory (eg: env/), and then modifying the PATH environment variable to prefix it with a custom bin directory (eg: env/bin/). An exact copy of the python or python3 binary is placed in this directory, but Python is programmed to look for libraries relative to its path first, in the environment directory. It's not part of Python's standard library, but is officially blessed by the PyPA (Python Packaging Authority). Once activated, you can install packages in the virtual environment using pip.

  • pyenv is used to isolate Python versions. For example, you may want to test your code against Python 2.7, 3.6, 3.7 and 3.8, so you'll need a way to switch between them. Once activated, it prefixes the PATH environment variable with ~/.pyenv/shims, where there are special files matching the Python commands (python, pip). These are not copies of the Python-shipped commands; they are special scripts that decide on the fly which version of Python to run based on the PYENV_VERSION environment variable, or the .python-version file, or the ~/.pyenv/version file. pyenv also makes the process of downloading and installing multiple Python versions easier, using the command pyenv install.

  • pyenv-virtualenv is a plugin for pyenv by the same author as pyenv, to allow you to use pyenv and virtualenv at the same time conveniently. However, if you're using Python 3.3 or later, pyenv-virtualenv will try to run python -m venv if it is available, instead of virtualenv. You can use virtualenv and pyenv together without pyenv-virtualenv, if you don't want the convenience features.

  • virtualenvwrapper is a set of extensions to virtualenv (see docs). It gives you commands like mkvirtualenv, lssitepackages, and especially workon for switching between different virtualenv directories. This tool is especially useful if you want multiple virtualenv directories.

  • pyenv-virtualenvwrapper is a plugin for pyenv by the same author as pyenv, to conveniently integrate virtualenvwrapper into pyenv.

  • pipenv aims to combine Pipfile, pip and virtualenv into one command on the command-line. The virtualenv directory typically gets placed in ~/.local/share/virtualenvs/XXX, with XXX being a hash of the path of the project directory. This is different from virtualenv, where the directory is typically in the current working directory. pipenv is meant to be used when developing Python applications (as opposed to libraries). There are alternatives to pipenv, such as poetry, which I won't list here since this question is only about the packages that are similarly named.

Standard library:

  • pyvenv is a script shipped with Python 3 but deprecated in Python 3.6 as it had problems (not to mention the confusing name). In Python 3.6+, the exact equivalent is python3 -m venv.

  • venv is a package shipped with Python 3, which you can run using python3 -m venv (although for some reason some distros separate it out into a separate distro package, such as python3-venv on Ubuntu/Debian). It serves the same purpose as virtualenv, but only has a subset of its features (see a comparison here). virtualenv continues to be more popular than venv, especially since the former supports both Python 2 and 3.

Recommendation for beginners:

This is my personal recommendation for beginners: start by learning virtualenv and pip, tools which work with both Python 2 and 3 and in a variety of situations, and pick up other tools once you start needing them.

How to set timeout for a line of c# code

I use something like this (you should add code to deal with the various fails):

    var response = RunTaskWithTimeout<ReturnType>(
        (Func<ReturnType>)delegate { return SomeMethod(someInput); }, 30);


    /// <summary>
    /// Generic method to run a task on a background thread with a specific timeout, if the task fails,
    /// notifies a user
    /// </summary>
    /// <typeparam name="T">Return type of function</typeparam>
    /// <param name="TaskAction">Function delegate for task to perform</param>
    /// <param name="TimeoutSeconds">Time to allow before task times out</param>
    /// <returns></returns>
    private T RunTaskWithTimeout<T>(Func<T> TaskAction, int TimeoutSeconds)
    {
        Task<T> backgroundTask;

        try
        {
            backgroundTask = Task.Factory.StartNew(TaskAction);
            backgroundTask.Wait(new TimeSpan(0, 0, TimeoutSeconds));
        }
        catch (AggregateException ex)
        {
            // task failed
            var failMessage = ex.Flatten().InnerException.Message);
            return default(T);
        }
        catch (Exception ex)
        {
            // task failed
            var failMessage = ex.Message;
            return default(T);
        }

        if (!backgroundTask.IsCompleted)
        {
            // task timed out
            return default(T);
        }

        // task succeeded
        return backgroundTask.Result;
    }

Concatenating string and integer in python

No string formatting:

>> print 'Foo',0
Foo 0

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

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

I always use this:

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

This is correct if your schema looks like this:

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

Which would result in:

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

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

How do I convert from int to Long in Java?

use

new Long(your_integer);

or

Long.valueOf(your_integer);

Play sound on button click android

public class MainActivity extends AppCompatActivity {

    public void clickMe (View view) {

        MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);
        mp.start();

    }

create a button with a method could be called when the button pressed (onCreate),

then create a variable for (MediaPlayer) class with the path of your file

MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);

finally run start method in that class

mp.start();

the file will run when the button pressed, hope this was helpful!

Scanner method to get a char

To get a char from a Scanner, you can use the findInLine method.

    Scanner sc = new Scanner("abc");
    char ch = sc.findInLine(".").charAt(0);
    System.out.println(ch); // prints "a"
    System.out.println(sc.next()); // prints "bc"

If you need a bunch of char from a Scanner, then it may be more convenient to (perhaps temporarily) change the delimiter to the empty string. This will make next() returns a length-1 string every time.

    Scanner sc = new Scanner("abc");
    sc.useDelimiter("");
    while (sc.hasNext()) {
        System.out.println(sc.next());
    } // prints "a", "b", "c"

What to return if Spring MVC controller method doesn't return value?

you can return void, then you have to mark the method with @ResponseStatus(value = HttpStatus.OK) you don't need @ResponseBody

@RequestMapping(value = "/updateSomeData" method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void updateDataThatDoesntRequireClientToBeNotified(...) {
    ...
}

Only get methods return a 200 status code implicity, all others you have do one of three things:

  • Return void and mark the method with @ResponseStatus(value = HttpStatus.OK)
  • Return An object and mark it with @ResponseBody
  • Return an HttpEntity instance

Can I exclude some concrete urls from <url-pattern> inside <filter-mapping>?

I have encounterd the same issue, but I find a anwser showing below.

web.xml

 <!-- set this param value for the filter-->
    <init-param>
            <param-name>freePages</param-name>
            <param-value>
            MainFrame.jsp;
            </param-value>
    </init-param>

filter.java

strFreePages = config.getInitParameter("freePages"); //get the exclue pattern from config file
isFreePage(strRequestPage)  //decide the exclude path

this way you don't have to harass the concrete Filter class.

Changing .gitconfig location on Windows

First check HOME setting, then change HOME and HOMEDRIVE to a existing dir.

c:\git>set HOME
HOME=U:\
HOMEDRIVE=U:
HOMEPATH=\

then change HOME and HOMEDRIVE by

set HOME=c:\tmp
set HOMEDRIVE=C:

Original purpose of <input type="hidden">?

In short, the original purpose was to make a field which will be submitted with form's submit. Sometimes, there were need to store some information in hidden field(for example, id of user) and submit it with form's submit.

From HTML September 22, 1995 specification

An INPUT element with `TYPE=HIDDEN' represents a hidden field.The user does not interact with this field; instead, the VALUE attribute specifies the value of the field. The NAME and VALUE attributes are required.

PHP Warning: Module already loaded in Unknown on line 0

I figured this out by printing the PHP configuration and searching by xml.ini. Notice in the following output how xml is loaded twice (first as 20-xml.ini and then as xml.ini):

$ php -i | grep xml
/etc/php.d/20-simplexml.ini,
/etc/php.d/20-xml.ini,
/etc/php.d/20-xmlwriter.ini,
/etc/php.d/30-xmlreader.ini,
/etc/php.d/xml.ini
xmlrpc_error_number => 0 => 0
xmlrpc_errors => Off => Off
libxml Version => 2.9.1
libxml
mbstring.http_output_conv_mimetypes => ^(text/|application/xhtml\+xml) => ^(text /|application/xhtml\+xml)
xml
libxml2 Version => 2.9.1
xmlreader
xmlwriter
libxslt compiled against libxml Version => 2.9.1

Where to place $PATH variable assertions in zsh?

I had similar problem (in bash terminal command was working correctly but zsh showed command not found error)

Solution:


just paste whatever you were earlier pasting in ~/.bashrc to:

~/.zshrc

Add / Change parameter of URL and redirect to the new URL

I had a similar situation where I wanted to replace a URL query parameter. However, I only had one param, and I could simply replace it:

window.location.search = '?filter=' + my_filter_value

The location.search property allows you to get or set the query portion of a URL.

How do I deal with corrupted Git object files?

You can use "find" for remove all files in the /objects directory with 0 in size with the command:

find .git/objects/ -size 0 -delete

Backup is recommended.

WHERE Clause to find all records in a specific month

One way would be to create a variable that represents the first of the month (ie 5/1/2009), either pass it into the proc or build it (concatenate month/1/year). Then use the DateDiff function.

WHERE DateDiff(m,@Date,DateField) = 0

This will return anything with a matching month and year.

How to pretty-print a numpy.array without scientific notation and with given precision?

FYI Numpy 1.15 (release date pending) will include a context manager for setting print options locally. This means that the following will work the same as the corresponding example in the accepted answer (by unutbu and Neil G) without having to write your own context manager. E.g., using their example:

x = np.random.random(10)
with np.printoptions(precision=3, suppress=True):
    print(x)
    # [ 0.073  0.461  0.689  0.754  0.624  0.901  0.049  0.582  0.557  0.348]

What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

ArrayIndexOutOfBoundsException means that you are trying to access an index of the array that does not exist or out of the bound of this array. Array indexes start from 0 and end at length - 1.

In your case

for(int i = 0; i<=name.length; i++) {
    System.out.print(name[i] +'\n'); // i goes from 0 to length, Not correct
}

ArrayIndexOutOfBoundsException happens when you are trying to access the name.length indexed element which does not exist (array index ends at length -1). just replacing <= with < would solve this problem.

for(int i = 0; i < name.length; i++) {
    System.out.print(name[i] +'\n');  // i goes from 0 to length - 1, Correct
}

Convert multidimensional array into single array

I have done this with OOP style

$res=[1=>[2,3,7,8,19],3=>[4,12],2=>[5,9],5=>6,7=>[10,13],10=>[11,18],8=>[14,20],12=>15,6=>[16,17]];
class MultiToSingle{
public $result=[];
public function __construct($array){
    if(!is_array($array)){
        echo "Give a array";
    }
    foreach($array as $key => $value){
        if(is_array($value)){
            for($i=0;$i<count($value);$i++){
                $this->result[]=$value[$i];
            }  
        }else{
            $this->result[]=$value;
        }
    }
}
}

$obj= new MultiToSingle($res);
$array=$obj->result;
print_r($array);

ORA-01652 Unable to extend temp segment by in tablespace

You don't need to create a new datafile; you can extend your existing tablespace data files.

Execute the following to determine the filename for the existing tablespace:

  SELECT * FROM DBA_DATA_FILES;

Then extend the size of the datafile as follows (replace the filename with the one from the previous query):

  ALTER DATABASE DATAFILE 'D:\ORACLEXE\ORADATA\XE\SYSTEM.DBF' RESIZE 2048M; 

an htop-like tool to display disk activity in linux

Use collectl which has extensive process I/O monitoring including monitoring threads.

Be warned that there are I/O counters for I/O being written to cache and I/O going to disk. collectl reports them separately. If you're not careful you can misinterpret the data. See http://collectl.sourceforge.net/Process.html

Of course, it shows a lot more than just process stats because you'd want one tool to provide everything rather than a bunch of different one that displays everything in different formats, right?

Reverse for '*' with arguments '()' and keyword arguments '{}' not found

You need single quotes around the view name

{% url 'viewname' %}

instead of

{% url viewname %}

Replace multiple strings at once

You could extend the String object with your own function that does what you need (useful if there's ever missing functionality):

String.prototype.replaceArray = function(find, replace) {
  var replaceString = this;
  for (var i = 0; i < find.length; i++) {
    replaceString = replaceString.replace(find[i], replace[i]);
  }
  return replaceString;
};

For global replace you could use regex:

String.prototype.replaceArray = function(find, replace) {
  var replaceString = this;
  var regex; 
  for (var i = 0; i < find.length; i++) {
    regex = new RegExp(find[i], "g");
    replaceString = replaceString.replace(regex, replace[i]);
  }
  return replaceString;
};

To use the function it'd be similar to your PHP example:

var textarea = $(this).val();
var find = ["<", ">", "\n"];
var replace = ["&lt;", "&gt;", "<br/>"];
textarea = textarea.replaceArray(find, replace);

How to put individual tags for a scatter plot

Perhaps use plt.annotate:

import numpy as np
import matplotlib.pyplot as plt

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]

plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
    cmap=plt.get_cmap('Spectral'))

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()

enter image description here

How might I find the largest number contained in a JavaScript array?

One for/of loop solution:

_x000D_
_x000D_
const numbers = [2, 4, 6, 8, 80, 56, 10];_x000D_
_x000D_
_x000D_
const findMax = (...numbers) => {_x000D_
  let currentMax = numbers[0]; // 2_x000D_
_x000D_
  for (const number of numbers) {_x000D_
    if (number > currentMax) {_x000D_
      console.log(number, currentMax);_x000D_
      currentMax = number;_x000D_
    }_x000D_
  }_x000D_
  console.log('Largest ', currentMax);_x000D_
  return currentMax;_x000D_
};_x000D_
_x000D_
findMax(...numbers);
_x000D_
_x000D_
_x000D_

Why does multiplication repeats the number several times?

It's the difference between strings and integers. See:

>>> "1" * 9
'111111111'

>>> 1 * 9
9

Creating a config file in PHP

Well - it would be sort of difficult to store your database configuration data in a database - don't ya think?

But really, this is a pretty heavily opinionated question because any style works really and it's all a matter of preference. Personally, I'd go for a configuration variable rather than constants - generally because I don't like things in the global space unless necessary. None of the functions in my codebase should be able to easily access my database password (except my database connection logic) - so I'd use it there and then likely destroy it.

Edit: to answer your comment - none of the parsing mechanisms would be the fastest (ini, json, etc) - but they're also not the parts of your application that you'd really need to focus on optimizing since the speed difference would be negligible on such small files.

How can I beautify JSON programmatically?

Programmatic formatting solution:

The JSON.stringify method supported by many modern browsers (including IE8) can output a beautified JSON string:

JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4);    // stringify with 4 spaces at each level
Demo: http://jsfiddle.net/AndyE/HZPVL/

This method is also included with json2.js, for supporting older browsers.

Manual formatting solution

If you don't need to do it programmatically, Try JSON Lint. Not only will it prettify your JSON, it will validate it at the same time.

Eclipse and Windows newlines

There is a handy bash utility - dos2unix - which is a DOS/MAC to UNIX text file format converter, that if not already installed on your distro, should be able to be easily installed via a package manager. dos2unix man page

Play sound file in a web-page in the background

<audio src="/music/good_enough.mp3">
<p>If you are reading this, it is because your browser does not support the audio element.     </p>
</audio>

and if you want the controls

<audio src="/music/good_enough.mp3" controls>
<p>If you are reading this, it is because your browser does not support the audio element.</p>
</audio>

and also using embed

<embed src="/music/good_enough.mp3" width="180" height="90" loop="false" autostart="false" hidden="true" />

Flutter - The method was called on null

The reason for this error occurs is that you are using the CryptoListPresenter _presenter without initializing.

I found that CryptoListPresenter _presenter would have to be initialized to fix because _presenter.loadCurrencies() is passing through a null variable at the time of instantiation;

there are two ways to initialize

  1. Can be initialized during an declaration, like this

    CryptoListPresenter _presenter = CryptoListPresenter();
    
  2. In the second, initializing(with assigning some value) it when initState is called, which the framework will call this method once for each state object.

    @override
    void initState() {
      _presenter = CryptoListPresenter(...);
    }
    

How can I get the current directory name in Javascript?

complete URL

If you want the complete URL e.g. http://website/basedirectory/workingdirectory/ use:

var location = window.location.href;
var directoryPath = location.substring(0, location.lastIndexOf("/")+1);

local path

If you want the local path without domain e.g. /basedirectory/workingdirectory/ use:

var location = window.location.pathname;
var directoryPath = location.substring(0, location.lastIndexOf("/")+1);

In case you don't need the slash at the end, remove the +1 after location.lastIndexOf("/")+1.

directory name

If you only want the current directory name, where the script is running in, e.g. workingdirectory use:

var location = window.location.pathname;
var path = location.substring(0, location.lastIndexOf("/"));
var directoryName = path.substring(path.lastIndexOf("/")+1);

Hibernate: failed to lazily initialize a collection of role, no session or session was closed

You're most likely closing the session inside of the RoleDao. If you close the session then try to access a field on an object that was lazy-loaded, you will get this exception. You should probably open and close the session/transaction in your test.

How do you post to an iframe?

This function creates a temporary form, then send data using jQuery :

function postToIframe(data,url,target){
    $('body').append('<form action="'+url+'" method="post" target="'+target+'" id="postToIframe"></form>');
    $.each(data,function(n,v){
        $('#postToIframe').append('<input type="hidden" name="'+n+'" value="'+v+'" />');
    });
    $('#postToIframe').submit().remove();
}

target is the 'name' attr of the target iFrame, and data is a JS object :

data={last_name:'Smith',first_name:'John'}

Easy way to test a URL for 404 in PHP?

If you are using PHP's curl bindings, you can check the error code using curl_getinfo as such:

$handle = curl_init($url);
curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);

/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode == 404) {
    /* Handle 404 here. */
}

curl_close($handle);

/* Handle $response here. */

Why do I get the "Unhandled exception type IOException"?

Try again with this code snippet:

import java.io.*;

class IO {
    public static void main(String[] args) {    
        try {
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));    
            String userInput;    
            while ((userInput = stdIn.readLine()) != null) {
                System.out.println(userInput);
            }
        } catch(IOException ie) {
            ie.printStackTrace();
        }   
    }
}

Using try-catch-finally is better than using throws. Finding errors and debugging are easier when you use try-catch-finally.

Reset Excel to default borders

In case anyone still needs the VBA way of doing this:

The properties, assuming you selected something, are:

With Selection
    .interior.pattern = xlNone
    .Borders(xl<side>).Linestyle = xlNone
End Selection

Where <side> can be for example DiagonalDown or EdgeTop, so

-> Selection.Borders(xlEdgeTop).Linestyle = xlNone

would reset the Top Edge.

Command-line Unix ASCII-based charting / plotting tool

Check the package plotext which allows to plot data directly on terminal using python3. It is very intuitive as its use is very similar to the matplotlib package.

Here is a basic example:

enter image description here

You can install it with the following command:

sudo -H pip install plotext

As for matplotlib, the main functions are scatter (for single points), plot (for points joined by lines) and show (to actually print the plot on terminal). It is easy to specify the plot dimensions, the point and line styles and whatever to show the axes, number ticks and final equations, which are used to convert the plotted coordinates to the original real values.

Here is the code to produce the plot shown above:

import plotext.plot as plx
import numpy as np

l=3000
x=np.arange(0, l)
y=np.sin(4*np.pi/l*np.array(x))*np.exp(-0.5*np.pi/l*x)

plx.scatter(x, y, rows = 17, cols = 70)
plx.show(clear = 0)

The option clear=True inside show is used to clear the terminal before plotting: this is useful, for example, when plotting a continuous flow of data. An example of plotting a continuous data flow is shown here: enter image description here

The package description provides more information how to customize the plot. The package has been tested on Ubuntu 16 where it works perfectly. Possible future developments (upon request) could involve extension to python2 and to other graphical interfaces (e.g. jupiter). Please let me know if you have any issues using it. Thanks.

I hope this answers your problem.

CSS table-cell equal width

This can be done by setting table-cell style to width: auto, and content empty. The columns are now equal-wide, but holding no content.

To insert content to the cell, add an div with css:

position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;

You also need to add position: relative to the cells.

Now you can put the actual content into the div talked above.

https://jsfiddle.net/vensdvvb/

Similarity String Comparison in Java

You can achieve this using the apache commons java library. Take a look at these two functions within it:
- getLevenshteinDistance
- getFuzzyDistance

Convert String XML fragment to Document Node in Java

You can use the document's import (or adopt) method to add XML fragments:

  /**
   * @param docBuilder
   *          the parser
   * @param parent
   *          node to add fragment to
   * @param fragment
   *          a well formed XML fragment
   */
  public static void appendXmlFragment(
      DocumentBuilder docBuilder, Node parent,
      String fragment) throws IOException, SAXException {
    Document doc = parent.getOwnerDocument();
    Node fragmentNode = docBuilder.parse(
        new InputSource(new StringReader(fragment)))
        .getDocumentElement();
    fragmentNode = doc.importNode(fragmentNode, true);
    parent.appendChild(fragmentNode);
  }

'namespace' but is used like a 'type'

If you're working on a big app and can't change any names, you can type a . to select the type you want from the namespace:

namespace Company.Core.Context{
  public partial class Context : Database Context {
    ...
  }
}
...

using Company.Core.Context;
someFunction(){
 var c = new Context.Context();
}

Python: What OS am I running on?

Check the available tests with module platform and print the answer out for your system:

import platform

print dir(platform)

for x in dir(platform):
    if x[0].isalnum():
        try:
            result = getattr(platform, x)()
            print "platform."+x+": "+result
        except TypeError:
            continue

Print specific part of webpage

Try this awesome ink-html library

import print from 'ink-html'
// const print = require('ink-html').default

// js
print(window.querySelector('#printable'))
// Vue.js
print(this.$refs.printable.$el)

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

You did not include jquery library. In jsfiddle its already there. Just include this line in your head section.

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

The proper syntax is (in example):

$query = mysql_query('SELECT * FROM beer ORDER BY quality');
while($row = mysql_fetch_assoc($query)) $results[] = $row;

How to execute cmd commands via Java

Every execution of exec spawns a new process with its own environment. So your second invocation is not connected to the first in any way. It will just change its own working directory and then exit (i.e. it's effectively a no-op).

If you want to compose requests, you'll need to do this within a single call to exec. Bash allows multiple commands to be specified on a single line if they're separated by semicolons; Windows CMD may allow the same, and if not there's always batch scripts.

As Piotr says, if this example is actually what you're trying to achieve, you can perform the same thing much more efficiently, effectively and platform-safely with the following:

String[] filenames = new java.io.File("C:/").list();

Apple Mach-O Linker Error when compiling for device

I was accidentally trying to compile for 64-bit simulator which was not agreeing with my CocoaPods

Replace Default Null Values Returned From Left Outer Join

That's as easy as

IsNull(FieldName, 0)

Or more completely:

SELECT iar.Description, 
  ISNULL(iai.Quantity,0) as Quantity, 
  ISNULL(iai.Quantity * rpl.RegularPrice,0) as 'Retail', 
  iar.Compliance 
FROM InventoryAdjustmentReason iar
LEFT OUTER JOIN InventoryAdjustmentItem iai  on (iar.Id = iai.InventoryAdjustmentReasonId)
LEFT OUTER JOIN Item i on (i.Id = iai.ItemId)
LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo)
WHERE iar.StoreUse = 'yes'

Remove scrollbar from iframe

This works in all browsers. jsfiddle here http://jsfiddle.net/zvhysct7/1/

<iframe src="http://buythecity.com"  scrolling="no" style=" width: 550px; height: 500px;  overflow: hidden;" ></iframe>

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

python3x or higher

  1. load file in byte stream:
     body = ''
        for lines in open('website/index.html','rb'):
            decodedLine = lines.decode('utf-8')
            body = body+decodedLine.strip()
        return body
  1. use global setting:
    import io
    import sys
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')

Name does not exist in the current context

I had this problem in my main project when I referenced a dll file.

The problem was that the main project that referenced the dll was targeting a lower framework version than that of the dll.

So I upped my target framework version (Right-click project -> Application -> Target framework) and the error disappeared.

pip not working in Python Installation in Windows 10

Make sure the path to scripts folder for the python version is added to the path environment/system variable in order to use pip command directly without the whole path to pip.exe which is inside the scripts folder.

The scripts folder would be inside the python folder for the version that you are using, which by default would be inside c drive or in c:/program files or c:/program files (x86).

Then use commands as mentioned below. You may have to run cmd as administrator to perform these tasks. You can do it by right clicking on cmd icon and selecting run as administrator.

python -m pip install packagename
python -m pip uninstall packagename
python -m pip install --upgrade packagename

In case you have more than one version of python. You may replace python with py -versionnumber for example py -2 for python 2 or you may replace it with the path to the corresponding python.exe file. For example "c:\python27\python".

Intel's HAXM equivalent for AMD on Windows OS

You will need to create a virtual device that runs on ARM. Virtual devices running on X86 require an Intel processor. AMD support as specified by Android is only available for Linux systems. If you want a better experience when creating your Virtual Device, use "Store a snapshot for faster startup" instead of the default "Use Host GPU".

How to use font-family lato?

Download it from here and extract LatoOFL.rar then go to TTF and open this font-face-generator click at Choose File choose font which you want to use and click at generate then download it and then go html file open it and you see the code like this

@font-face {
        font-family: "Lato Black";
        src: url('698242188-Lato-Bla.eot');
        src: url('698242188-Lato-Bla.eot?#iefix') format('embedded-opentype'),
        url('698242188-Lato-Bla.svg#Lato Black') format('svg'),
        url('698242188-Lato-Bla.woff') format('woff'),
        url('698242188-Lato-Bla.ttf') format('truetype');
        font-weight: normal;
        font-style: normal;
}
body{
    font-family: "Lato Black";
    direction: ltr;
}

change the src code and give the url where your this font directory placed, now you can use it at your website...

If you don't want to download it use this

<link type='text/css' href='http://fonts.googleapis.com/css?family=Lato:400,700' />

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

You have a view model to which your view is strongly typed => use strongly typed helpers:

<%= Html.DropDownListFor(
    x => x.SelectedAccountId, 
    new SelectList(Model.Accounts, "Value", "Text")
) %>

Also notice that I use a SelectList for the second argument.

And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:

public ActionResult AccountTransaction()
{
    var accounts = Services.AccountServices.GetAccounts(false);
    var viewModel = new AccountTransactionView
    {
        Accounts = accounts.Select(a => new SelectListItem
        {
            Text = a.Description,
            Value = a.AccountId.ToString()
        })
    };
    return View(viewModel);
}

C++ auto keyword. Why is it magic?

auto was a keyword that C++ "inherited" from C that had been there nearly forever, but virtually never used because there were only two possible conditions: either it wasn't allowed, or else it was assumed by default.

The use of auto to mean a deduced type was new with C++11.

At the same time, auto x = initializer deduces the type of x from the type of initializer the same way as template type deduction works for function templates. Consider a function template like this:

template<class T>
int whatever(T t) { 
    // point A
};

At point A, a type has been assigned to T based on the value passed for the parameter to whatever. When you do auto x = initializer;, the same type deduction is used to determine the type for x from the type of initializer that's used to initialize it.

This means that most of the type deduction mechanics a compiler needs to implement auto were already present and used for templates on any compiler that even sort of attempted to implement C++98/03. As such, adding support for auto was apparently fairly easy for essentially all the compiler teams--it was added quite quickly, and there seem to have been few bugs related to it either.

When this answer was originally written (in 2011, before the ink was dry on the C++ 11 standard) auto was already quite portable. Nowadays, it's thoroughly portable among all the mainstream compilers. The only obvious reasons to avoid it would be if you need to write code that's compatible with a C compiler, or you have a specific need to target some niche compiler that you know doesn't support it (e.g., a few people still write code for MS-DOS using compilers from Borland, Watcom, etc., that haven't seen significant upgrades in decades). If you're using a reasonably current version of any of the mainstream compilers, there's no reason to avoid it at all though.

Freemarker iterating over hashmap keys

If using a BeansWrapper with an exposure level of Expose.SAFE or Expose.ALL, then the standard Java approach of iterating the entry set can be employed:

For example, the following will work in Freemarker (since at least version 2.3.19):

<#list map.entrySet() as entry>  
  <input type="hidden" name="${entry.key}" value="${entry.value}" />
</#list>

In Struts2, for instance, an extension of the BeanWrapper is used with the exposure level defaulted to allow this manner of iteration.

How to push both key and value into an Array in Jquery

arr[title] = link;

You're not pushing into the array, you're setting the element with the key title to the value link. As such your array should be an object.

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

This could be solved without VBA by the following technique.

In this example I am counting all the threes (3) in the range A:A of the sheets Page M904, Page M905 and Page M906.

List all the sheet names in a single continuous range like in the following example. Here listed in the range D3:D5.

enter image description here

Then by having the lookup value in cell B2, the result can be found in cell B4 by using the following formula:

=SUMPRODUCT(COUNTIF(INDIRECT("'"&D3:D5&"'!A:A"), B2))

Kill a Process by Looking up the Port being used by it from a .BAT

Created a bat file with the below contents, it accepts the input for port number

@ECHO ON
set /p portid=Enter the Port to be killed: 
echo %portid%                                                                              
FOR /F "tokens=5" %%T IN ('netstat -a -n -o ^| findstr %portid% ') DO (
SET /A ProcessId=%%T) &GOTO SkipLine                                                   
:SkipLine                                                                              
echo ProcessId to kill = %ProcessId%
taskkill /f /pid %ProcessId%
PAUSE

Finally click "Enter" to exit.

What is the difference between x86 and x64

x86 is for a 32-bit OS, and x64 is for a 64-bit OS

Need to get current timestamp in Java

Joda-Time

Here is the same kind of code but using the third-party library Joda-Time 2.3.

In real life, I would specify a time zone, as relying on default zone is usually a bad practice. But omitted here for simplicity of example.

org.joda.time.DateTime now = new DateTime();
org.joda.time.format.DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy h:mm:ss a" );
String nowAsString = formatter.print( now );

System.out.println( "nowAsString: " + nowAsString );

When run…

nowAsString: 11/28/2013 11:28:15 PM

How to Detect Browser Window /Tab Close Event?

my solution is similar to the solution given by Server Themes. Do check it once:

localStorage.setItem("validNavigation", false);
$(document).on('keypress', function (e) {
    if (e.keyCode == 116) {
        localStorage.setItem("validNavigation", true);
    }
});

// Attach the event click for all links in the page
$(document).on("click", "a", function () {
    localStorage.setItem("validNavigation", true);
});

// Attach the event submit for all forms in the page
$(document).on("submit", "form", function () {
    localStorage.setItem("validNavigation", true);
});

// Attach the event click for all inputs in the page
$(document).bind("click", "input[type=submit]", function () {
    localStorage.setItem("validNavigation", true);
});

$(document).bind("click", "button[type=submit]", function () {
    localStorage.setItem("validNavigation", true);
});
window.onbeforeunload = function (event) {

    if (localStorage.getItem("validNavigation") === "false") {
        event.returnValue = "Write something clever here..";
        console.log("Test success!");
        localStorage.setItem("validNavigation", false);
    }
};

If you put the breakpoints correctly on the browser page, the if condition will be true only when the browser is about to be closed or the tab is about to be closed.

Check this link for reference: https://www.oodlestechnologies.com/blogs/Capture-Browser-Or-Tab-Close-Event-Jquery-Javascript/

How to change language settings in R

For me worked:

Sys.setlocale("LC_MESSAGES", "en_US.utf8")

Testing:

> Sys.setlocale("LC_MESSAGES", "en_US.utf8")
[1] "en_US.utf8"
> x[3]
Error: object 'x' not found

Also working to get english messages:

Sys.setlocale("LC_MESSAGES", "C")

To reset to german messages I used

Sys.setlocale("LC_MESSAGES", "de_DE.utf8")

Here is the start of my sessionInfo:

> sessionInfo()
R version 3.4.1 (2017-06-30)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.2 LTS

Merging two arrays in .NET

int [] SouceArray1 = new int[] {2,1,3};
int [] SourceArray2 = new int[] {4,5,6};
int [] targetArray = new int [SouceArray1.Length + SourceArray2.Length];
SouceArray1.CopyTo(targetArray,0);
SourceArray2.CopyTo(targetArray,SouceArray1.Length) ; 
foreach (int i in targetArray) Console.WriteLine(i + " ");  

Using the above code two Arrays can be easily merged.

Docker: Container keeps on restarting again on again

When docker kill CONTAINER_ID does not work and docker stop -t 1 CONTAINER_ID also does not work, you can try to delete the container:

docker container rm CONTAINER_ID

I had a similar issue today where containers were in a continuous restart loop.

The issue in my case was related to me being a poor engineer.

Anyway, I fixed the issue by deleting the container, fixing my code, and then rebuilding and running the container.

Hope that this helps anyone stuck with this issue in future

How to extract text from a PDF?

The best thing I can currently think of (within the list of "simple" tools) is Ghostscript (current version is v.8.71) and the PostScript utility program ps2ascii.ps. Ghostscript ships it in its lib subdirectory. Try this (on Windows):

gswin32c.exe ^
   -q ^
   -sFONTPATH=c:/windows/fonts ^
   -dNODISPLAY ^
   -dSAFER ^
   -dDELAYBIND ^
   -dWRITESYSTEMDICT ^
   -dCOMPLEX ^
   -f ps2ascii.ps ^
   -dFirstPage=3 ^
   -dLastPage=7 ^
   input.pdf ^
   -dQUIET ^
   -c quit

This command processes pages 3-7 of input.pdf. Read the comments in the ps2ascii.ps file itself to see what the "weird" numbers and additional infos mean (they indicate strings, positions, widths, colors, pictures, rectangles, fonts and page breaks...). To get a "simple" text output, replace the -dCOMPLEX part by -dSIMPLE.

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

Visual Studio 2017 - Git failed with a fatal error

I fixed this problem by uninstalling the 64-bit version and installing a 32-bit version of Git

Axios get access to response header fields

for django help

CORS_EXPOSE_HEADERS = [
        'your header'
    ]

Why are only a few video games written in Java?

Actually, it is very possible for managed code to do 3d games, the problem is the back engines. With .Net, for a brief period, there was a Managed DirectX wrapper to DirectX 9 by Microsoft. This was before the abstraction that is now XNA.

Being given total access to DirectX api's, .Net games work a treat. The best example I know of is www.entombed.co.uk, which is written in VB.Net.

Unfortunately, on the Java side, it is seriously lacking - mainly for the reason that DirectX isn't available for Java, and games programmers know and understand the DirectX api - why learn yet another api when you will be returning to DirectX?

Local dependency in package.json

Master project

Here is the package.json you will use for the master project:

"dependencies": {
    "express": "*",
    "somelocallib": "file:./somelocallib"
}

There, ./somelocallib is the reference to the library folder as relative to the master project package.json.

Reference: https://docs.npmjs.com/files/package.json#local-paths


Sub project

Handle your library dependencies.

In addition to running npm install, you will need to run (cd node_modules/somelocallib && npm install).

This is a known bug with NPM.

Reference: https://github.com/npm/npm/issues/1341 (seeking a more up-to-date reference)


Notes for Docker

Check in your master package.lock and your somelocallib/package.lock into your source code manager.

Then in your Dockerfile use:

FROM node:10
WORKDIR /app
# ...
COPY ./package.json ./package-lock.json ./
COPY somelocallib somelocallib
RUN npm ci
RUN (cd node_modules/zkp-utils/ && npm ci)
# ...

I use parenthesis in my (cd A && B) constructs to make the operation idempotent.

Why does the C++ STL not provide any "tree" containers?

This one looks promising and seems to be what you're looking for: http://tree.phi-sci.com/

What version of Python is on my Mac?

You could have multiple Python versions on your macOS.

You may check that by command, type or which command, like:

which -a python python2 python2.7 python3 python3.6

Or type python in Terminal and hit Tab few times for auto completion, which is equivalent to:

compgen -c python

By default python/pip commands points to the first binary found in PATH environment variable depending what's actually installed. So before installing Python packages with Homebrew, the default Python is installed in /usr/bin which is shipped with your macOS (e.g. Python 2.7.10 on High Sierra). Any versions found in /usr/local (such as /usr/local/bin) are provided by external packages.

It is generally advised, that when working with multiple versions, for Python 2 you may use python2/pip2 command, respectively for Python 3 you can use python3/pip3, but it depends on your configuration which commands are available.

It is also worth to mention, that since release of Homebrew 1.5.0+ (on 19 January 2018), the python formula has been upgraded to Python 3.x and a python@2 formula will be added for installing Python 2.7. Before, python formula was pointing to Python 2.

For instance, if you've installed different version via Homebrew, try the following command:

brew list python python3

or:

brew list | grep ^python

it'll show you all Python files installed with the package.

Alternatively you may use apropos or locate python command to locate more Python related files.

To check any environment variables related to Python, run:

env | grep ^PYTHON

To address your issues:

  • Error: No such keg: /usr/local/Cellar/python

    Means you don't have Python installed via Homebrew. However double check by specifying only one package at a time (like brew list python python2 python3).

  • The locate database (/var/db/locate.database) does not exist.

    Follow the advice and run:

    sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist
    

    After the database is rebuild, you can use locate command.

jQuery issue in Internet Explorer 8

Some people stumbling on this post might get this issue with jquery and IE8 because they're using >= jQuery v2. Use this code:

<!--[if lt IE 9]>
    <script src="jquery-1.9.0.js"></script>
<![endif]-->
<!--[if gte IE 9]><!-->
    <script src="jquery-2.0.0.js"></script>
<!--<![endif]-->

how to sort pandas dataframe from one column

This one worked for me:

df=df.sort_values(by=[2])

Whereas:

df=df.sort_values(by=['2']) 

is not working.

mysql.h file can't be found

You probably don't included the path to mysql headers, which can be found at /usr/include/mysql, on several unix systems I think. See this post, it may be helpfull.

By the way, related with the question of that guy above, about syntastic configuration. One can add the following to your ~/.vimrc:

let b:syntastic_c_cflags = '-I/usr/include/mysql'

and you can always check the wiki page of the developers on github. Enjoy!

How to stretch in width a WPF user control to its window?

The Canvas in WPF doesn't provide much automatic layout support. I try to steer clear of them for this reason (HorizontalAlignment and VerticalAlignment don't work as expected), but I got your code to work with these minor modifications (binding the Width and Height of the control to the canvas's ActualWidth/ActualHeight).

<Window x:Class="TCI.Indexer.UI.Operacao"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tci="clr-namespace:TCI.Indexer.UI.Controles"
Title=" " MinHeight="550" MinWidth="675" Loaded="Load" 
ResizeMode="NoResize" WindowStyle="None" WindowStartupLocation="CenterScreen" 
WindowState="Maximized" Focusable="True" x:Name="windowOperacao">

<Canvas x:Name="canv">
    <Grid>
        <tci:Status x:Name="ucStatus" Width="{Binding ElementName=canv
                                                    , Path=ActualWidth}" 
                                      Height="{Binding ElementName=canv
                                                    , Path=ActualHeight}"/> 
        <!-- the control which I want to stretch in width -->
    </Grid>
</Canvas>

The Canvas is the problem here. If you're not actually utilizing the features the canvas offers in terms of layout or Z-Order "squashing" (think of the flatten command in PhotoShop), I would consider using a control like a Grid instead so you don't end up having to learn the quirks of a control that works differently than you have come to expect with WPF.

How to Force New Google Spreadsheets to refresh and recalculate?

Quick, but manual


Updating NOW(), TODAY(), RAND(), or RANDBETWEEN() formulas

Press Backspace ? or Del on any empty cell to immediately trigger a recalculation of formulas depending on NOW(), TODAY(), RAND(), or RANDBETWEEN() (in all Sheets of the whole Spreadsheet, as usual).

(If no empty cell is at hand, you can delete a filled cell instead and then undo that with Ctrl+z.)

INDIRECT() formulas are unfortunately not updated like this by default.

Updating INDIRECT() formulas

You can update a (range of) cells of INDIRECT() formulas by pasting the range on itself:

  1. Select cell/ range
  2. Ctrl+C
  3. Ctrl+V

You can use Ctrl+A to select the whole current Sheet in step 1.. But for large Sheets then the other 2 operations can take several seconds each.
A trick to know when the process of copying a large range has finished: Copy some single cell before copying your range: The single cell losing its dotted border will be your notification of the large copy finishing.

C++ templates that accept only certain types

This typically is unwarranted in C++, as other answers here have noted. In C++ we tend to define generic types based on other constraints other than "inherits from this class". If you really wanted to do that, it's quite easy to do in C++11 and <type_traits>:

#include <type_traits>

template<typename T>
class observable_list {
    static_assert(std::is_base_of<list, T>::value, "T must inherit from list");
    // code here..
};

This breaks a lot of the concepts that people expect in C++ though. It's better to use tricks like defining your own traits. For example, maybe observable_list wants to accept any type of container that has the typedefs const_iterator and a begin and end member function that returns const_iterator. If you restrict this to classes that inherit from list then a user who has their own type that doesn't inherit from list but provides these member functions and typedefs would be unable to use your observable_list.

There are two solutions to this issue, one of them is to not constrain anything and rely on duck typing. A big con to this solution is that it involves a massive amount of errors that can be hard for users to grok. Another solution is to define traits to constrain the type provided to meet the interface requirements. The big con for this solution is that involves extra writing which can be seen as annoying. However, the positive side is that you will be able to write your own error messages a la static_assert.

For completeness, the solution to the example above is given:

#include <type_traits>

template<typename...>
struct void_ {
    using type = void;
};

template<typename... Args>
using Void = typename void_<Args...>::type;

template<typename T, typename = void>
struct has_const_iterator : std::false_type {};

template<typename T>
struct has_const_iterator<T, Void<typename T::const_iterator>> : std::true_type {};

struct has_begin_end_impl {
    template<typename T, typename Begin = decltype(std::declval<const T&>().begin()),
                         typename End   = decltype(std::declval<const T&>().end())>
    static std::true_type test(int);
    template<typename...>
    static std::false_type test(...);
};

template<typename T>
struct has_begin_end : decltype(has_begin_end_impl::test<T>(0)) {};

template<typename T>
class observable_list {
    static_assert(has_const_iterator<T>::value, "Must have a const_iterator typedef");
    static_assert(has_begin_end<T>::value, "Must have begin and end member functions");
    // code here...
};

There are a lot of concepts shown in the example above that showcase C++11's features. Some search terms for the curious are variadic templates, SFINAE, expression SFINAE, and type traits.

How do I test if a string is empty in Objective-C?

The first approach is valid, but doesn't work if your string has blank spaces (@" "). So you must clear this white spaces before testing it.

This code clear all the blank spaces on both sides of the string:

[stringObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ];

One good idea is create one macro, so you don't have to type this monster line:

#define allTrim( object ) [object stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ]

Now you can use:

NSString *emptyString = @"   ";

if ( [allTrim( emptyString ) length] == 0 ) NSLog(@"Is empty!");

Func delegate with no return type

Occasionally you will want to write a delegate for event handling, in which case you can take advantage of System.EvenHandler<T> which implicitly accepts an argument of type object in addition to the second parameter that should derive from EventArgs. EventHandlers will return void

I personally found this useful during testing for creating a one-off callback in a function body.

Disable Copy or Paste action for text box?

Check this fiddle.

 $('#email').bind("cut copy paste",function(e) {
     e.preventDefault();
 });

You need to bind what should be done on cut, copy and paste. You prevent default behavior of the action.

You can find a detailed explanation here.

FileNotFoundException while getting the InputStream object from HttpURLConnection

For anybody else stumbling over this, the same happened to me while trying to send a SOAP request header to a SOAP service. The issue was a wrong order in the code, I requested the input stream first before sending the XML body. In the code snipped below, the line InputStream in = conn.getInputStream(); came immediately after ByteArrayOutputStream out = new ByteArrayOutputStream(); which is the incorrect order of things.

ByteArrayOutputStream out = new ByteArrayOutputStream();
// send SOAP request as part of HTTP body 
byte[] data = request.getHttpBody().getBytes("UTF-8");
conn.getOutputStream().write(data); 

if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
  Log.d(TAG, "http response code is " + conn.getResponseCode());
  return null;
}

InputStream in = conn.getInputStream();

FileNotFound in this case was an unfortunate way to encode HTTP response code 400.

RegEx for validating an integer with a maximum length of 10 characters

0123456789 is not a valid integer (usually zeros will be stripped)

I think something like this regexp would be better to use:

^[1-9]([0-9]*)$

(does not support signed numbers)

What is an MDF file?

Just to make this absolutely clear for all:

A .MDF file is “typically” a SQL Server data file however it is important to note that it does NOT have to be.

This is because .MDF is nothing more than a recommended/preferred notation but the extension itself does not actually dictate the file type.

To illustrate this, if someone wanted to create their primary data file with an extension of .gbn they could go ahead and do so without issue.

To qualify the preferred naming conventions:

  • .mdf - Primary database data file.
  • .ndf - Other database data files i.e. non Primary.
  • .ldf - Log data file.

How to check heap usage of a running JVM from the command line?

For Java 8 you can use the following command line to get the heap space utilization in kB:

jstat -gc <PID> | tail -n 1 | awk '{split($0,a," "); sum=a[3]+a[4]+a[6]+a[8]; print sum}'

The command basically sums up:

  • S0U: Survivor space 0 utilization (kB).
  • S1U: Survivor space 1 utilization (kB).
  • EU: Eden space utilization (kB).
  • OU: Old space utilization (kB).

You may also want to include the metaspace and the compressed class space utilization. In this case you have to add a[10] and a[12] to the awk sum.

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

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

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

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

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

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

So in your case the correct syntax will be:

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

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


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

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

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


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

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

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

Reloading the page gives wrong GET request with AngularJS HTML5 mode

Your server side code is JAVA then Follow this below steps

step 1 : Download urlrewritefilter JAR Click Here and save to build path WEB-INF/lib

step 2 : Enable HTML5 Mode $locationProvider.html5Mode(true);

step 3 : set base URL <base href="/example.com/"/>

step 4 : copy and paste to your WEB.XML

 <filter>
     <filter-name>UrlRewriteFilter</filter-name>
 <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>UrlRewriteFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

step 5 : create file in WEN-INF/urlrewrite.xml

 <urlrewrite default-match-type="wildcard">


    <rule>
            <from>/</from>
            <to>/index.html</to>
        </rule>

    <!--Write every state dependent on your project url-->
    <rule>
            <from>/example</from>
            <to>/index.html</to>
        </rule>
    </urlrewrite>

Spring @PropertySource using YAML

Spring-boot has a helper for this, just add

@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)

at the top of your test classes or an abstract test superclass.

Edit: I wrote this answer five years ago. It doesn't work with recent versions of Spring Boot. This is what I do now (please translate the Kotlin to Java if necessary):

@TestPropertySource(locations=["classpath:application.yml"])
@ContextConfiguration(
        initializers=[ConfigFileApplicationContextInitializer::class]
)

is added to the top, then

    @Configuration
    open class TestConfig {

        @Bean
        open fun propertiesResolver(): PropertySourcesPlaceholderConfigurer {
            return PropertySourcesPlaceholderConfigurer()
        }
    }

to the context.

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

You have to add one jar : jackson-annotations-2.1.2.jar You can download it from here and add it to the class path If you are using the gradle then add the following dependency.

compile 'com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:2.5.2'

How to prevent line breaks in list items using CSS

Bootstrap 4 has a class named text-nowrap. It is just what you need.

Beautiful way to remove GET-variables with PHP?

Inspired by the comment of @MitMaro, I wrote a small benchmark to test the speed of solutions of @Gumbo, @Matt Bridges and @justin the proposal in the question:

function teststrtok($number_of_tests){
    for($i = 0; $i < $number_of_tests; $i++){
      $str = "http://www.example.com?test=test";
      $str = strtok($str,'?');
    }
}
function testexplode($number_of_tests){
    for($i = 0; $i < $number_of_tests; $i++){
      $str = "http://www.example.com?test=test";
      $str = explode('?', $str);
    }
}
function testregexp($number_of_tests){
    for($i = 0; $i < $number_of_tests; $i++){
      $str = "http://www.example.com?test=test";
      preg_replace('/\\?.*/', '', $str);
    }
}
function teststrpos($number_of_tests){
    for($i = 0; $i < $number_of_tests; $i++){
      $str = "http://www.example.com?test=test";
      $qPos = strpos($str, "?");
      $url_without_query_string = substr($str, 0, $qPos);
    }
}

$number_of_runs = 10;
for($runs = 0; $runs < $number_of_runs; $runs++){

  $number_of_tests = 40000;
  $functions = array("strtok", "explode", "regexp", "strpos");
  foreach($functions as $func){
    $starttime = microtime(true);
    call_user_func("test".$func, $number_of_tests);
    echo $func.": ". sprintf("%0.2f",microtime(true) - $starttime).";";
  }
  echo "<br />";
}
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;

Result: @justin's strtok is the fastest.

Note: tested on a local Debian Lenny system with Apache2 and PHP5.

How to create named and latest tag in Docker?

Here is my bash script

docker build -t ${IMAGE}:${VERSION} .
docker tag ${IMAGE}:${VERSION} ${IMAGE}:latest

You can then remove untagged images if you rebuilt the same version with

docker rmi $(docker images | grep "^<none>" | awk "{print $3}")

link

or

docker rmi $(docker images | grep "^<none>" | tr -s " " | cut -d' ' -f3 | tr '\n' ' ')

or

Clean up commands:

Docker 1.13 introduces clean-up commands. To remove all unused containers, images, networks and volumes:

docker system prune

or individually:

docker container prune
docker image prune
docker network prune
docker volume prune

How can I read input from the console using the Scanner class in Java?

There is a simple way to read from the console.

Please find the below code:

import java.util.Scanner;

    public class ScannerDemo {

        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);

            // Reading of Integer
            int number = sc.nextInt();

            // Reading of String
            String str = sc.next();
        }
    }

For a detailed understanding, please refer to the below documents.

Doc

Now let's talk about the detailed understanding of the Scanner class working:

public Scanner(InputStream source) {
    this(new InputStreamReader(source), WHITESPACE_PATTERN);
}

This is the constructor for creating the Scanner instance.

Here we are passing the InputStream reference which is nothing but a System.In. Here it opens the InputStream Pipe for console input.

public InputStreamReader(InputStream in) {
    super(in);
    try {
        sd = StreamDecoder.forInputStreamReader(in, this, (String)null); // ## Check lock object
    }
    catch (UnsupportedEncodingException e) {
        // The default encoding should always be available
        throw new Error(e);
    }
}

By passing the System.in this code will opens the socket for reading from console.

Count the number of occurrences of a string in a VARCHAR field?

This is the mysql function using the space technique (tested with mysql 5.0 + 5.5): CREATE FUNCTION count_str( haystack TEXT, needle VARCHAR(32)) RETURNS INTEGER DETERMINISTIC RETURN LENGTH(haystack) - LENGTH( REPLACE ( haystack, needle, space(char_length(needle)-1)) );

How to make Bitmap compress without change the bitmap size?

If you are using PNG format then it will not compress your image because PNG is a lossless format. use JPEG for compressing your image and use 0 instead of 100 in quality.

Quality Accepts 0 - 100

0 = MAX Compression (Least Quality which is suitable for Small images)

100 = Least Compression (MAX Quality which is suitable for Big images)

Can Android do peer-to-peer ad-hoc networking?

you can connect your android device to a known ad-hoc network.

edit /system/etc/wifi/tiwlan.ini

WiFiAdhoc = 1
dot11DesiredSSID = <your_network_ssid>
dot11DesiredBSSType = 0 

edit /data/misc/wifi/wpa_supplicant.conf

ctrl_interface=tiwlan0
update_config=1
eapol_version=1
ap_scan=2

if that is too simplistic, see these instructions.

"Sub or Function not defined" when trying to run a VBA script in Outlook

This probably does not answer your question, but I had the same question and it answered mine.

I changed Private Function to Public Function and it worked.

Open URL in same window and in same tab

   Just Try in button.

   <button onclick="location.reload();location.href='url_name'" 
   id="myButton" class="btn request-callback" >Explore More</button>

   Using href 

  <a href="#" class="know_how" onclick="location.reload();location.href='url_name'">Know More</a> 

How to quickly and conveniently create a one element arraylist

Yet another alternative is double brace initialization, e.g.

new ArrayList<String>() {{ add(s); }};

but it is inefficient and obscure. Therefore only suitable:

  • in code that doesn't mind memory leaks, such as most unit tests and other short-lived programs;
  • and if none of the other solutions apply, which I think implies you've scrolled all the way down here looking to populate a different type of container than the ArrayList in the question.

Tkinter understanding mainloop

I'm using an MVC / MVA design pattern, with multiple types of "views". One type is a "GuiView", which is a Tk window. I pass a view reference to my window object which does things like link buttons back to view functions (which the adapter / controller class also calls).

In order to do that, the view object constructor needed to be completed prior to creating the window object. After creating and displaying the window, I wanted to do some initial tasks with the view automatically. At first I tried doing them post mainloop(), but that didn't work because mainloop() blocked!

As such, I created the window object and used tk.update() to draw it. Then, I kicked off my initial tasks, and finally started the mainloop.

import Tkinter as tk

class Window(tk.Frame):
    def __init__(self, master=None, view=None ):
        tk.Frame.__init__( self, master )
        self.view_ = view       
        """ Setup window linking it to the view... """

class GuiView( MyViewSuperClass ):

    def open( self ):
        self.tkRoot_ = tk.Tk()
        self.window_ = Window( master=None, view=self )
        self.window_.pack()
        self.refresh()
        self.onOpen()
        self.tkRoot_.mainloop()         

    def onOpen( self ):        
        """ Do some initial tasks... """

    def refresh( self ):        
        self.tkRoot_.update()

Disable form autofill in Chrome without disabling autocomplete

Chrome password manager is looking for input elements with type="password" and fill in saved password. It also ignores autocomplete="off" property.

Here is fix for latest Chrome (Version 40.0.2181.0 canary):

<input name="password">

JS:

setTimeout(function() {
    var input = document.querySelector("input[name=password]");
    input.setAttribute("type", "password");
}, 0)

Chart.js v2 - hiding grid lines

Please refer to the official documentation:

https://www.chartjs.org/docs/latest/axes/styling.html#grid-line-configuration

Below code changes would hide the gridLines:

        gridLines: {
            display:false
        }

enter image description here

Change the background color of a row in a JTable

Resumee of Richard Fearn's answer , to make each second line gray:

jTable.setDefaultRenderer(Object.class, new DefaultTableCellRenderer()
{
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        c.setBackground(row % 2 == 0 ? Color.LIGHT_GRAY : Color.WHITE);
        return c;
    }
});

Check if a file exists with wildcard in shell script

Found a couple of neat solutions worth sharing. The first still suffers from "this will break if there's too many matches" problem:

pat="yourpattern*" matches=($pat) ; [[ "$matches" != "$pat" ]] && echo "found"

(Recall that if you use an array without the [ ] syntax, you get the first element of the array.)

If you have "shopt -s nullglob" in your script, you could simply do:

matches=(yourpattern*) ; [[ "$matches" ]] && echo "found"

Now, if it's possible to have a ton of files in a directory, you're pretty well much stuck with using find:

find /path/to/dir -maxdepth 1 -type f -name 'yourpattern*' | grep -q '.' && echo 'found'

How do I validate a date in this format (yyyy-mm-dd) using jquery?

You could also just use regular expressions to accomplish a slightly simpler job if this is enough for you (e.g. as seen in [1]).

They are build in into javascript so you can use them without any libraries.

function isValidDate(dateString) {
  var regEx = /^\d{4}-\d{2}-\d{2}$/;
  return dateString.match(regEx) != null;
}

would be a function to check if the given string is four numbers - two numbers - two numbers (almost yyyy-mm-dd). But you can do even more with more complex expressions, e.g. check [2].

isValidDate("23-03-2012") // false
isValidDate("1987-12-24") // true
isValidDate("22-03-1981") // false
isValidDate("0000-00-00") // true

How to set session attribute in java?

By default session object is available on jsp page(implicit object). It will not available in normal POJO java class. You can get the reference of HttpSession object on Servelt by using HttpServletRequest

HttpSession s=request.getSession()
s.setAttribute("name","value");

You can get session on an ActionSupport based Action POJO class as follows

 ActionContext ctx= ActionContext.getContext();
   Map m=ctx.getSession();
   m.put("name", value);

look at: http://ohmjavaclasses.blogspot.com/2011/12/access-session-in-action-class-struts2.html

WindowsError: [Error 126] The specified module could not be found

if you come across this error when you try running PyTorch related libraries you may have to consider installing PyTorch with CPU only version i.e. if you don't have Nvidia GPU in your system.

Pytorch with CUDA worked in Nvidia installed systems but not in others.

View HTTP headers in Google Chrome?

For me, as of Google Chrome Version 46.0.2490.71 m, the Headers info area is a little hidden. To access:

  1. While the browser is open, press F12 to access Web Developer tools

  2. When opened, click the "Network" option

  3. Initially, it is possible the page data is not present/up to date. Refresh the page if necessary

  4. Observe the page information appears in the listing. (Also, make sure "All" is selected next to the "Hide data URLs" checkbox)

see screenshot

How to use andWhere and orWhere in Doctrine?

One thing missing here: if you have a varying number of elements that you want to put together to something like

WHERE [...] AND (field LIKE '%abc%' OR field LIKE '%def%')

and dont want to assemble a DQL-String yourself, you can use the orX mentioned above like this:

$patterns = ['abc', 'def'];
$orStatements = $qb->expr()->orX();
foreach ($patterns as $pattern) {
    $orStatements->add(
        $qb->expr()->like('field', $qb->expr()->literal('%' . $pattern . '%'))
    );
}
$qb->andWhere($orStatements);

PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Or

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

How to set thousands separator in Java?

DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols();
formatSymbols.setDecimalSeparator('|');
formatSymbols.setGroupingSeparator(' ');

String strange = "#,##0.###";
DecimalFormat df = new DecimalFormat(strange, formatSymbols);
df.setGroupingSize(4);

String out = df.format(new BigDecimal(300000).doubleValue());

System.out.println(out);

How to get the size of the current screen in WPF?

I created a little wrapper around the Screen from System.Windows.Forms, currently everything works... Not sure about the "device independent pixels", though.

public class WpfScreen
{
    public static IEnumerable<WpfScreen> AllScreens()
    {
        foreach (Screen screen in System.Windows.Forms.Screen.AllScreens)
        {
            yield return new WpfScreen(screen);
        }
    }

    public static WpfScreen GetScreenFrom(Window window)
    {
        WindowInteropHelper windowInteropHelper = new WindowInteropHelper(window);
        Screen screen = System.Windows.Forms.Screen.FromHandle(windowInteropHelper.Handle);
        WpfScreen wpfScreen = new WpfScreen(screen);
        return wpfScreen;
    }

    public static WpfScreen GetScreenFrom(Point point)
    {
        int x = (int) Math.Round(point.X);
        int y = (int) Math.Round(point.Y);

        // are x,y device-independent-pixels ??
        System.Drawing.Point drawingPoint = new System.Drawing.Point(x, y);
        Screen screen = System.Windows.Forms.Screen.FromPoint(drawingPoint);
        WpfScreen wpfScreen = new WpfScreen(screen);

        return wpfScreen;
    }

    public static WpfScreen Primary
    {
        get { return new WpfScreen(System.Windows.Forms.Screen.PrimaryScreen); }
    }

    private readonly Screen screen;

    internal WpfScreen(System.Windows.Forms.Screen screen)
    {
        this.screen = screen;
    }

    public Rect DeviceBounds
    {
        get { return this.GetRect(this.screen.Bounds); }
    }

    public Rect WorkingArea
    {
        get { return this.GetRect(this.screen.WorkingArea); }
    }

    private Rect GetRect(Rectangle value)
    {
        // should x, y, width, height be device-independent-pixels ??
        return new Rect
                   {
                       X = value.X,
                       Y = value.Y,
                       Width = value.Width,
                       Height = value.Height
                   };
    }

    public bool IsPrimary
    {
        get { return this.screen.Primary; }
    }

    public string DeviceName
    {
        get { return this.screen.DeviceName; }
    }
}

ORA-00942: table or view does not exist (works when a separate sql, but does not work inside a oracle function)

A very simple solution is to add the database name with your table name like if your DB name is DBMS and table is info then it will be DBMS.info for any query.

If your query is

select * from STUDENTREC where ROLL_NO=1;

it might show an error but

select * from DBMS.STUDENTREC where ROLL_NO=1; 

it doesn't because now actually your table is found.

Cannot Resolve Collation Conflict

The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.

When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.

Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:

http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database

Update Collation of all fields in database on the fly

http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx

If you need to have different collation on two objects or can't change collations - you can still JOIN between them using COLLATE command, and choosing the collation you want for join.

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS 

or using default database collation:

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT

SQL Switch/Case in 'where' clause

Here you go.

SELECT
   column1, 
   column2
FROM
   viewWhatever
WHERE
CASE 
    WHEN @locationType = 'location' AND account_location = @locationID THEN 1
    WHEN @locationType = 'area' AND xxx_location_area = @locationID THEN 1
    WHEN @locationType = 'division' AND xxx_location_division = @locationID THEN 1
    ELSE 0
END = 1

Efficient way to determine number of digits in an integer

If faster is more efficient, this is a improvement on andrei alexandrescu's improvement. His version was already faster than the naive way (dividing by 10 at every digit). The version below is constant time and faster at least on x86-64 and ARM for all sizes, but occupies twice as much binary code, so it is not as cache-friendly.

Benchmarks for this version vs alexandrescu's version on my PR on facebook folly.

Works on unsigned, not signed.

inline uint32_t digits10(uint64_t v) {
  return  1
        + (std::uint32_t)(v>=10)
        + (std::uint32_t)(v>=100)
        + (std::uint32_t)(v>=1000)
        + (std::uint32_t)(v>=10000)
        + (std::uint32_t)(v>=100000)
        + (std::uint32_t)(v>=1000000)
        + (std::uint32_t)(v>=10000000)
        + (std::uint32_t)(v>=100000000)
        + (std::uint32_t)(v>=1000000000)
        + (std::uint32_t)(v>=10000000000ull)
        + (std::uint32_t)(v>=100000000000ull)
        + (std::uint32_t)(v>=1000000000000ull)
        + (std::uint32_t)(v>=10000000000000ull)
        + (std::uint32_t)(v>=100000000000000ull)
        + (std::uint32_t)(v>=1000000000000000ull)
        + (std::uint32_t)(v>=10000000000000000ull)
        + (std::uint32_t)(v>=100000000000000000ull)
        + (std::uint32_t)(v>=1000000000000000000ull)
        + (std::uint32_t)(v>=10000000000000000000ull);
}

Vertically centering Bootstrap modal window

_x000D_
_x000D_
.modal.in .modal-dialog {_x000D_
    position: relative;_x000D_
    top: 50%;_x000D_
    transform: translateY(-50%);_x000D_
}
_x000D_
_x000D_
_x000D_

What is the maximum possible length of a .NET string?

Since String.Length is an integer (that is an alias for Int32), its size is limited to Int32.MaxValue unicode characters. ;-)

80-characters / right margin line in Sublime Text 3

Yes, it is possible both in Sublime Text 2 and 3 (which you should really upgrade to if you haven't already). Select View ? Ruler ? 80 (there are several other options there as well). If you like to actually wrap your text at 80 columns, select View ? Word Wrap Column ? 80. Make sure that View ? Word Wrap is selected.

To make your selections permanent (the default for all opened files or views), open Preferences ? Settings—User and use any of the following rules:

{
    // set vertical rulers in specified columns.
    // Use "rulers": [80] for just one ruler
    // default value is []
    "rulers": [80, 100, 120],

    // turn on word wrap for source and text
    // default value is "auto", which means off for source and on for text
    "word_wrap": true,

    // set word wrapping at this column
    // default value is 0, meaning wrapping occurs at window width
    "wrap_width": 80
}

These settings can also be used in a .sublime-project file to set defaults on a per-project basis, or in a syntax-specific .sublime-settings file if you only want them to apply to files written in a certain language (Python.sublime-settings vs. JavaScript.sublime-settings, for example). Access these settings files by opening a file with the desired syntax, then selecting Preferences ? Settings—More ? Syntax Specific—User.

As always, if you have multiple entries in your settings file, separate them with commas , except for after the last one. The entire content should be enclosed in curly braces { }. Basically, make sure it's valid JSON.

If you'd like a key combo to automatically set the ruler at 80 for a particular view/file, or you are interested in learning how to set the value without using the mouse, please see my answer here.

Finally, as mentioned in another answer, you really should be using a monospace font in order for your code to line up correctly. Other types of fonts have variable-width letters, which means one 80-character line may not appear to be the same length as another 80-character line with different content, and your indentations will look all messed up. Sublime has monospace fonts set by default, but you can of course choose any one you want. Personally, I really like Liberation Mono. It has glyphs to support many different languages and Unicode characters, looks good at a variety of different sizes, and (most importantly for a programming font) clearly differentiates between 0 and O (digit zero and capital letter oh) and 1 and l (digit one and lowercase letter ell), which not all monospace fonts do, unfortunately. Version 2.0 and later of the font are licensed under the open-source SIL Open Font License 1.1 (here is the FAQ).

The endpoint reference (EPR) for the Operation not found is

Action is null means that no Action in given SOAP Message (Request XML). You must set Action before SOAP call:

java.net.URL endpoint = new URL("<URL>"); //sets URL

MimeHeaders headers = message.getMimeHeaders(); // getting MIME Header

headers.addHeader("SOAPAction", "<SOAP Action>"); //add Action To Header

SOAPMessage response = soapConnection.call(<SOAPMessage>, endpoint); //then Call

soapConnection.close(); // then Close the connection

Remove whitespaces inside a string in javascript

For space-character removal use

"hello world".replace(/\s/g, "");

for all white space use the suggestion by Rocket in the comments below!

Explicitly set column value to null SQL Developer

Use Shift+Del.

More info: Shift+Del combination key set a field to null when you filled a field by a value and you changed your decision and you want to make it null. It is useful and I amazed from the other answers that give strange solutions.

How can I check if char* variable points to empty string?

Give it a chance:

Try getting string via function gets(string) then check condition as if(string[0] == '\0')

How to debug an apache virtual host configuration?

I had a new VirtualHost configuration file that was not showing when using the apachectl -S command. After much head scratching I realised that my file did not have suffix ".conf". Once I renamed the file with that suffix my Vhost started showing and working!