Programs & Examples On #Link local

Unable to ping vmware guest from another vmware guest

  1. Check the firewall on all the windows system. If it's enabled, disable it.
  2. If you still are unable to ping, Open the virtual network editor and check if you are using the same VMnet adapter for both the VM's, this adapter should be present in the host machine's network adapters as well. Share a screenshot of what you are seeing in the virtual network editor.

DNS problem, nslookup works, ping doesn't

It's possible that the Windows internal resolver is adding '.local' to the domain name because there's no dots in it. nslookup wouldn't do that.

To verify this possiblity, install 'Wireshark' (previously aka Ethereal) on your client machine and observe any DNS request packets leaving it when you run the ping command.


OK, further investigation on my own XP machine at home reveals that for single label names (i.e. "foo", or "foo.") the system doesn't use DNS at all, and instead uses NBNS (NetBios Name Service).

Using a hint found at http://www.chicagotech.net/netforums/viewtopic.php?t=1476, I found that I was able to force DNS lookups for single label domains by putting a single entry reading "." in the "Append these DNS suffixes (in order)" in the "Advanced TCP/IP settings" dialog

Chosen Jquery Plugin - getting selected values

Like from any regular input/select/etc...:

$("form.my-form .chosen-select").val()

Change a HTML5 input's placeholder color with CSS

Use the new ::placeholder if you use autoprefixer.

Note that the .placeholder mixin from Bootstrap is deprecated in favor of this.

Example:

input::placeholder { color: black; }

When using autoprefixer the above will be converted to the correct code for all browsers.

What was the strangest coding standard rule that you were forced to follow?

You must use only five letter table names and the last two character is reserved for IO.

Use jQuery to change a second select list based on the first select list option

I wanted to make a version of this that uses $.getJSON() from a separate JSON file.

Demo: here

JavaScript:

$(document).ready(function () {
    "use strict";

    var selectData, $states;

    function updateSelects() {
        var cities = $.map(selectData[this.value], function (city) {
            return $("<option />").text(city);
        });
        $("#city_names").empty().append(cities);
    }

    $.getJSON("updateSelect.json", function (data) {
        var state;
        selectData = data;
        $states = $("#us_states").on("change", updateSelects);
        for (state in selectData) {
            $("<option />").text(state).appendTo($states);
        }
        $states.change();
    });
});

HTML:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
    <select id="us_states"></select>
    <select id="city_names"></select>
    <script type="text/javascript" src="updateSelect.js"></script>
</body>
</html>

JSON:

{
    "NE": [
        "Smallville",
        "Bigville"
    ],
    "CA": [
        "Sunnyvale",
        "Druryburg",
        "Vickslake"
    ],
    "MI": [
        "Lakeside",
        "Fireside",
        "Chatsville"
    ]
}

what is the use of $this->uri->segment(3) in codeigniter pagination

In your code $this->uri->segment(3) refers to the pagination offset which you use in your query. According to your $config['base_url'] = base_url().'index.php/papplicant/viewdeletedrecords/' ;, $this->uri->segment(3) i.e segment 3 refers to the offset. The first segment is the controller, second is the method, there after comes the parameters sent to the controllers as segments.

Printf long long int in C with GCC?

Try to update your compiler, I'm using GCC 4.7 on Windows 7 Starter x86 with MinGW and it compiles fine with the same options both in C99 and C11.

Fastest way to remove first char in a String

You could profile it, if you really cared. Write a loop of many iterations and see what happens. Chances are, however, that this is not the bottleneck in your application, and TrimStart seems the most semantically correct. Strive to write code readably before optimizing.

SyntaxError: missing ) after argument list

You had a unescaped " in the onclick handler, escape it with \"

$('#contentData').append("<div class='media'><div class='media-body'><h4 class='media-heading'>" + v.Name + "</h4><p>" + v.Description + "</p><a class='btn' href='" + type + "'  onclick=\"(canLaunch('" + v.LibraryItemId + " '))\">View &raquo;</a></div></div>")

Invalid syntax when using "print"?

That is because in Python 3, they have replaced the print statement with the print function.

The syntax is now more or less the same as before, but it requires parens:

From the "what's new in python 3" docs:

Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y)       # prints repr((x, y))
New: print((x, y))      # Not the same as print(x, y)!

How to change the sender's name or e-mail address in mutt?

One special case for this is if you have used a construction like the following in your ~/.muttrc:

# Reset From email to default
send-hook . "my_hdr From: Real Name <[email protected]>"

This send-hook will override either of these:

mutt -e "set [email protected]"
mutt -e "my_hdr From: Other Name <[email protected]>"

Your emails will still go out with the header:

From: Real Name <[email protected]>

In this case, the only command line solution I've found is actually overriding the send-hook itself:

mutt -e "send-hook . \"my_hdr From: Other Name <[email protected]>\""

Why is my Spring @Autowired field null?

Not entirely related to the question, but if the field injection is null, the constructor based injection will still work fine.

    private OrderingClient orderingClient;
    private Sales2Client sales2Client;
    private Settings2Client settings2Client;

    @Autowired
    public BrinkWebTool(OrderingClient orderingClient, Sales2Client sales2Client, Settings2Client settings2Client) {
        this.orderingClient = orderingClient;
        this.sales2Client = sales2Client;
        this.settings2Client = settings2Client;
    }

Matplotlib scatter plot legend

Here's an easier way of doing this (source: here):

import matplotlib.pyplot as plt
from numpy.random import rand


fig, ax = plt.subplots()
for color in ['red', 'green', 'blue']:
    n = 750
    x, y = rand(2, n)
    scale = 200.0 * rand(n)
    ax.scatter(x, y, c=color, s=scale, label=color,
               alpha=0.3, edgecolors='none')

ax.legend()
ax.grid(True)

plt.show()

And you'll get this:

enter image description here

Take a look at here for legend properties

Insert all values of a table into another table in SQL

 Dim ofd As New OpenFileDialog
                ofd.Filter = "*.mdb|*.MDB"
                ofd.FilterIndex = (2)
                ofd.FileName = "bd1.mdb"
                ofd.Title = "SELECCIONE LA BASE DE DATOS ORIGEN (bd1.mdb)"
                ofd.ShowDialog()
                Dim conexion1 = "Driver={Microsoft Access Driver (*.mdb)};DBQ=" + ofd.FileName
                Dim conn As New OdbcConnection()
                conn.ConnectionString = conexion1
                conn.Open()



            'EN ESTE CODIGO SOLO SE AGREGAN LOS DATOS'
            Dim ofd2 As New OpenFileDialog
            ofd2.Filter = "*.mdb|*.MDB"
            ofd2.FilterIndex = (2)
            ofd2.FileName = "bd1.mdb"
            ofd2.Title = "SELECCIONE LA BASE DE DATOS DESTINO (bd1.mdb)"
            ofd2.ShowDialog()
            Dim conexion2 = "Driver={Microsoft Access Driver (*.mdb)};DBQ=" + ofd2.FileName
            Dim conn2 As New OdbcConnection()
            conn2.ConnectionString = conexion2
            Dim cmd2 As New OdbcCommand
            Dim CADENA2 As String

            CADENA2 = "INSERT INTO EXISTENCIA IN '" + ofd2.FileName + "' SELECT * FROM EXISTENCIA IN '" + ofd.FileName + "'"


            cmd2.CommandText = CADENA2
            cmd2.Connection = conn2
            conn2.Open()
            Dim dA2 As New OdbcDataAdapter
            dA2.SelectCommand = cmd2
            Dim midataset2 As New DataSet
            dA2.Fill(midataset2, "EXISTENCIA")

How to add minutes to current time in swift

Swift 4:

// add 5 minutes to date

let date = startDate.addingTimeInterval(TimeInterval(5.0 * 60.0))

// subtract 5 minutes from date

let date = startDate.addingTimeInterval(TimeInterval(-5.0 * 60.0))

Swift 5.1:

// subtract 5 minutes from date
transportationFromDate.addTimeInterval(TimeInterval(-5.0 * 60.0))

Getting the PublicKeyToken of .Net assemblies

The simplest way for me is to use ILSpy.

When you drag & drop the assembly on its window and select the dropped assembly on the the left, you can see the public key token on the right side of the window.

(I also think that the newer versions will also display the public key of the signature, if you ever need that one... See here: https://github.com/icsharpcode/ILSpy/issues/610#issuecomment-111189234. Good stuff! ;))

Table cell widths - fixing width, wrapping/truncating long words

<style type="text/css">
td { word-wrap: break-word;max-width:50px; }            
</style>

ImportError: No module named PytQt5

This probably means that python doesn't know where PyQt5 is located. To check, go into the interactive terminal and type:

import sys
print sys.path

What you probably need to do is add the directory that contains the PyQt5 module to your PYTHONPATH environment variable. If you use bash, here's how:

Type the following into your shell, and add it to the end of the file ~/.bashrc

export PYTHONPATH=/path/to/PyQt5/directory:$PYTHONPATH

where /path/to/PyQt5/directory is the path to the folder where the PyQt5 library is located.

Warning: A non-numeric value encountered

Solve this error on WordPress

Warning: A non-numeric value encountered in C:\XAMPP\htdocs\aad-2\wp-includes\SimplePie\Parse\Date.php on line 694

Simple solution here!

  1. locate a file of wp-includes\SimplePie\Parse\Date.php
  2. find a line no. 694
  3. you show the code $second = round($match[6] + $match[7] / pow(10, strlen($match[7])));
  4. and change this 3.) to this line $second = round((int)$match[6] + (int)$match[7] / pow(10, strlen($match[7])));

Parsing boolean values with argparse

Quick and easy, but only for arguments 0 or 1:

parser.add_argument("mybool", default=True,type=lambda x: bool(int(x)))
myargs=parser.parse_args()
print(myargs.mybool)

The output will be "False" after calling from terminal:

python myscript.py 0

How to Select Every Row Where Column Value is NOT Distinct

Just for fun, here's another way:

;with counts as (
    select CustomerName, EmailAddress,
      count(*) over (partition by EmailAddress) as num
    from Customers
)
select CustomerName, EmailAddress
from counts
where num > 1

In Linux, how to tell how much memory processes are using?

Use ps to find the process id for the application, then use top -p1010 (substitute 1010 for the real process id). The RES column is the used physical memory and the VIRT column is the used virtual memory - including libraries and swapped memory.

More info can be found using "man top"

cannot load such file -- bundler/setup (LoadError)

You can try to run:

bundle exec rake rails:update:bin

As @Dinesh mentioned in Rails 5:

rails app:update:bin

Regular expression for validating names and surnames?

It's a very difficult problem to validate something like a name due to all the corner cases possible.

Corner Cases

Sanitize the inputs and let them enter whatever they want for a name, because deciding what is a valid name and what is not is probably way outside the scope of whatever you're doing; given the range of potential strange - and legal names is nearly infinite.

If they want to call themselves Tricyclopltz^2-Glockenschpiel, that's their problem, not yours.

How to fill DataTable with SQL Table

The SqlDataReader is a valid data source for the DataTable. As such, all you need to do its this:

public DataTable GetData()
{
    SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
    conn.Open();
    string query = "SELECT * FROM [EventOne]";
    SqlCommand cmd = new SqlCommand(query, conn);

    DataTable dt = new DataTable();
    dt.Load(cmd.ExecuteReader());
    conn.Close();
    return dt;
}

How to add trendline in python matplotlib dot (scatter) graphs?

as explained here

With help from numpy one can calculate for example a linear fitting.

# plot the data itself
pylab.plot(x,y,'o')

# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])

Android dex gives a BufferOverflowException when building

None of the other solutions here worked for me after upgrading to Android Studio 0.4.0 and Gradle 1.9.

I resolved the problem by downloading Build Tools 19.0.1 and updating the following line in my build.gradle files:

buildToolsVersion '19.0.0'

to

buildToolsVersion '19.0.1'

How can I execute Python scripts using Anaconda's version of Python?

You can try to change the default .py program via policy management. Go to windows, search for regedit, right click it. And then run as administrator. Then, you can search the key word "python.exe" And change your Python27 path to you Anaconda path.

How can I git stash a specific file?

I usually add to index changes I don't want to stash and then stash with --keep-index option.

git add app/controllers/cart_controller.php
git stash --keep-index
git reset

Last step is optional, but usually you want it. It removes changes from index.


Warning As noted in the comments, this puts everything into the stash, both staged and unstaged. The --keep-index just leaves the index alone after the stash is done. This can cause merge conflicts when you later pop the stash.

CSS last-child selector: select last-element of specific class, not last child inside of parent?

What about this solution?

div.commentList > article.comment:not(:last-child):last-of-type
{
    color:red; /*or whatever...*/
}

Python - Get path of root project structure

There are many answers here but I couldn't find something simple that covers all cases so allow me to suggest my solution too:

_x000D_
_x000D_
import pathlib_x000D_
import os_x000D_
_x000D_
def get_project_root():_x000D_
    """_x000D_
    There is no way in python to get project root. This function uses a trick._x000D_
    We know that the function that is currently running is in the project._x000D_
    We know that the root project path is in the list of PYTHONPATH_x000D_
    look for any path in PYTHONPATH list that is contained in this function's path_x000D_
    Lastly we filter and take the shortest path because we are looking for the root._x000D_
    :return: path to project root_x000D_
    """_x000D_
    apth = str(pathlib.Path().absolute())_x000D_
    ppth = os.environ['PYTHONPATH'].split(':')_x000D_
    matches = [x for x in ppth if x in apth]_x000D_
    project_root = min(matches, key=len)_x000D_
    return project_root
_x000D_
_x000D_
_x000D_

VSCode Change Default Terminal

I just type following keywords in the opened terminal;

  1. powershell
  2. bash
  3. cmd
  4. node
  5. python (or python3)

See details in the below image. (VSCode version 1.19.1 - windows 10 OS) enter image description here

It works on VS Code Mac as well. I tried it with VSCode (Version 1.20.1)

Automatically start a Windows Service on install

Here is a procedure and code using generated ProjectInstaller in Visual Studio:

  1. Create Windows Service project in Visual Studio
  2. Generate installers to the service
  3. Open ProjectInstaller in design editor (it should open automatically when installer is created) and set properties of generated serviceProcessInstaller1 (e.g. Account: LocalSystem) and serviceInstaller1 (e.g. StartType: Automatic)
  4. Open ProjectInstaller in code editor (press F7 in design editor) and add event handler to ServiceInstaller.AfterInstall - see the following code. It will start the service after its installation.

ProjectInstaller class:

using System.ServiceProcess;


[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
    public ProjectInstaller()
    {
        InitializeComponent(); //generated code including property settings from previous steps
        this.serviceInstaller1.AfterInstall += Autorun_AfterServiceInstall; //use your ServiceInstaller name if changed from serviceInstaller1
    }

    void Autorun_AfterServiceInstall(object sender, InstallEventArgs e)
    {
        ServiceInstaller serviceInstaller = (ServiceInstaller)sender;
        using (ServiceController sc = new ServiceController(serviceInstaller.ServiceName))
        {
            sc.Start();
        }
    }
}

Making the main scrollbar always visible

Setting height to 101% is my solution to the problem. You pages will no longer 'flick' when switching between ones that exceed the viewport height and ones that do not.

How do you return the column names of a table?

try this

select * from <tablename> where 1=2

...............................................

If conditions in a Makefile, inside a target

There are several problems here, so I'll start with my usual high-level advice: Start small and simple, add complexity a little at a time, test at every step, and never add to code that doesn't work. (I really ought to have that hotkeyed.)

You're mixing Make syntax and shell syntax in a way that is just dizzying. You should never have let it get this big without testing. Let's start from the outside and work inward.

UNAME := $(shell uname -m)

all:
    $(info Checking if custom header is needed)
    ifeq ($(UNAME), x86_64)
    ... do some things to build unistd_32.h
    endif

    @make -C $(KDIR) M=$(PWD) modules

So you want unistd_32.h built (maybe) before you invoke the second make, you can make it a prerequisite. And since you want that only in a certain case, you can put it in a conditional:

ifeq ($(UNAME), x86_64)
all: unistd_32.h
endif

all:
    @make -C $(KDIR) M=$(PWD) modules

unistd_32.h:
    ... do some things to build unistd_32.h

Now for building unistd_32.h:

F1_EXISTS=$(shell [ -e /usr/include/asm/unistd_32.h ] && echo 1 || echo 0 )
ifeq ($(F1_EXISTS), 1)
    $(info Copying custom header)
    $(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm/unistd_32.h > unistd_32.h)
else    
    F2_EXISTS=$(shell [[ -e /usr/include/asm-i386/unistd.h ]] && echo 1 || echo 0 )
    ifeq ($(F2_EXISTS), 1)
        $(info Copying custom header)
        $(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm-i386/unistd.h > unistd_32.h)
    else
        $(error asm/unistd_32.h and asm-386/unistd.h does not exist)
    endif
endif

You are trying to build unistd.h from unistd_32.h; the only trick is that unistd_32.h could be in either of two places. The simplest way to clean this up is to use a vpath directive:

vpath unistd.h /usr/include/asm /usr/include/asm-i386

unistd_32.h: unistd.h
    sed -e 's/__NR_/__NR32_/g' $< > $@

Stored procedure or function expects parameter which is not supplied

In my case, It was returning one output parameter and was not Returning any value.
So changed it to

param.Direction = ParameterDirection.Output;
command.ExecuteScalar();

and then it was throwing size error. so had to set the size as well

SqlParameter param = new SqlParameter("@Name",SqlDbType.NVarChar);
param.Size = 10;

Reportviewer tool missing in visual studio 2017 RC

Update: this answer works with both ,Visual Sudio 2017 and 2019

For me it worked by the following three steps:

  1. Updating Visual Studio to the latest build.
  2. Adding Report / Report Wizard to the Add/New Item menu by:
    • Going to Visual Studio menu Tools/Extensions and Updates
    • Choose Online from the left panel.
    • Search for Microsoft Rdlc Report Designer for Visual Studio
    • Download and install it.
  3. Adding Report viewer control by:

    • Going to NuGet Package Manager.

    • Installing Microsoft.ReportingServices.ReportViewerControl.Winforms

    • Go to the folder that contains Microsoft.ReportViewer.WinForms.dll: %USERPROFILE%\.nuget\packages\microsoft.reportingservices.reportviewercontrol.winforms\140.1000.523\lib\net40
    • Drag the Microsoft.ReportViewer.WinForms.dll file and drop it at Visual Studio Toolbox Window.

For WebForms applications:

  1. The same.
  2. The same.
  3. Adding Report viewer control by:

    • Going to NuGet Package Manager.

    • Installing Microsoft.ReportingServices.ReportViewerControl.WebForms

    • Go to the folder that contains Microsoft.ReportViewer.WebForms.dll file: %USERPROFILE%\.nuget\packages\microsoft.reportingservices.reportviewercontrol.webforms\140.1000.523\lib\net40
    • Drag the Microsoft.ReportViewer.WebForms.dll file and drop it at Visual Studio Toolbox Window.

That's all!

Disable Chrome strict MIME type checking

In my case, I turned off X-Content-Type-Options on nginx then works fine. But make sure this declines your security level a little. Would be a temporally fix.

# Not work
add_header X-Content-Type-Options nosniff;
# OK (comment out)
#add_header X-Content-Type-Options nosniff;

It'll be the same for apache.

<IfModule mod_headers.c>
  #Header set X-Content-Type-Options nosniff
</IfModule>

Is it possible to use a div as content for Twitter's Popover

here is an another example

<a   data-container = "body" data-toggle = "popover" data-placement = "left" 
    data-content = "&lt;img src='<?php echo baseImgUrl . $row1[2] ?>' width='250' height='100' &gt;&lt;div&gt;&lt;h3&gt; <?php echo $row1['1'] ?>&lt/h3&gt; &lt;p&gt; &lt;span&gt;<?php echo $countsss ?>videos &lt;/span&gt;
&lt;span&gt;<?php echo $countsss1 ?> followers&lt;/span&gt;
&lt;/p&gt;&lt;/div&gt;
<?php echo $row1['4'] ?>   &lt;hr&gt;&lt;div&gt;
&lt;span&gt; &lt;button type='button' class='btn btn-default pull-left green'&gt;Follow  &lt;/button&gt;  &lt;/span&gt; &lt;span&gt; &lt;button type='button' class='btn btn-default pull-left green'&gt; Go to channel page&lt;/button&gt;   &lt;/span&gt;&lt;span&gt; &lt;button type='button' class='btn btn-default pull-left green'&gt;Close  &lt;/button&gt;  &lt;/span&gt;

 &lt;/div&gt;">

<?php echo $row1['1'] ?>
  </a>

How to convert an integer to a string in any base?

def dec_to_radix(input, to_radix=2, power=None):
    if not isinstance(input, int):
        raise TypeError('Not an integer!')
    elif power is None:
        power = 1

    if input == 0:
        return 0
    else:
        remainder = input % to_radix**power
        digit = str(int(remainder/to_radix**(power-1)))
        return int(str(dec_to_radix(input-remainder, to_radix, power+1)) + digit)

def radix_to_dec(input, from_radix):
    if not isinstance(input, int):
        raise TypeError('Not an integer!')
    return sum(int(digit)*(from_radix**power) for power, digit in enumerate(str(input)[::-1]))

def radix_to_radix(input, from_radix=10, to_radix=2, power=None):
    dec = radix_to_dec(input, from_radix)
    return dec_to_radix(dec, to_radix, power)

How to set default value for HTML select?

Note: this is JQuery. See Sébastien answer for Javascript

$(function() {
    var temp="a"; 
    $("#MySelect").val(temp);
});

<select name="MySelect" id="MySelect">
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>
</select>

How to assign pointer address manually in C programming language?

let's say you want a pointer to point at the address 0x28ff4402, the usual way is

uint32_t *ptr;
ptr = (uint32_t*) 0x28ff4402 //type-casting the address value to uint32_t pointer
*ptr |= (1<<13) | (1<<10); //access the address how ever you want

So the short way is to use a MACRO,

#define ptr *(uint32_t *) (0x28ff4402)

How can I perform a reverse string search in Excel without using VBA?

=RIGHT(A1,LEN(A1)-FIND("`*`",SUBSTITUTE(A1," ","`*`",LEN(A1)-LEN(SUBSTITUTE(A1," ",""))))) 

Push items into mongo array via mongoose

Assuming, var friend = { firstName: 'Harry', lastName: 'Potter' };

There are two options you have:

Update the model in-memory, and save (plain javascript array.push):

person.friends.push(friend);
person.save(done);

or

PersonModel.update(
    { _id: person._id }, 
    { $push: { friends: friend } },
    done
);

I always try and go for the first option when possible, because it'll respect more of the benefits that mongoose gives you (hooks, validation, etc.).

However, if you are doing lots of concurrent writes, you will hit race conditions where you'll end up with nasty version errors to stop you from replacing the entire model each time and losing the previous friend you added. So only go to the former when it's absolutely necessary.

Is there are way to make a child DIV's width wider than the parent DIV using CSS?

Use absolute positioning

.child-div {
    position:absolute;
    left:0;
    right:0;
}

Converting Dictionary to List?

dict.items()

Does the trick.

How to remove an HTML element using Javascript?

Your JavaScript is correct. Your button has type="submit" which is causing the page to refresh.

How do I run Selenium in Xvfb?

open a terminal and run this command xhost +. This commands needs to be run every time you restart your machine. If everything works fine may be you can add this to startup commands

Also make sure in your /etc/environment file there is a line

export DISPLAY=:0.0 

And then, run your tests to see if your issue is resolved.

All please note the comment from sardathrion below before using this.

How to get local server host and port in Spring Boot?

One solution mentioned in a reply by @M. Deinum is one that I've used in a number of Akka apps:

object Localhost {

  /**
   * @return String for the local hostname
   */
  def hostname(): String = InetAddress.getLocalHost.getHostName

  /**
   * @return String for the host IP address
   */
  def ip(): String = InetAddress.getLocalHost.getHostAddress

}

I've used this method when building a callback URL for Oozie REST so that Oozie could callback to my REST service and it's worked like a charm

Adding link a href to an element using css

No. Its not possible to add link through css. But you can use jquery

$('.case').each(function() {
  var link = $(this).html();
  $(this).contents().wrap('<a href="example.com/script.php?id="></a>');
});

Here the demo: http://jsfiddle.net/r5uWX/1/

Loop through each row of a range in Excel

Just stumbled upon this and thought I would suggest my solution. I typically like to use the built in functionality of assigning a range to an multi-dim array (I guess it's also the JS Programmer in me).

I frequently write code like this:

Sub arrayBuilder()

myarray = Range("A1:D4")

'unlike most VBA Arrays, this array doesn't need to be declared and will be automatically dimensioned

For i = 1 To UBound(myarray)

    For j = 1 To UBound(myarray, 2)

    Debug.Print (myarray(i, j))

    Next j

Next i

End Sub

Assigning ranges to variables is a very powerful way to manipulate data in VBA.

How to split a string and assign it to variables

The IPv6 addresses for fields like RemoteAddr from http.Request are formatted as "[::1]:53343"

So net.SplitHostPort works great:

package main

    import (
        "fmt"
        "net"
    )

    func main() {
        host1, port, err := net.SplitHostPort("127.0.0.1:5432")
        fmt.Println(host1, port, err)

        host2, port, err := net.SplitHostPort("[::1]:2345")
        fmt.Println(host2, port, err)

        host3, port, err := net.SplitHostPort("localhost:1234")
        fmt.Println(host3, port, err)
    }

Output is:

127.0.0.1 5432 <nil>
::1 2345 <nil>
localhost 1234 <nil>

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

For the second part of your question, see the array page of the manual, which states (quoting) :

Array assignment always involves value copying. Use the reference operator to copy an array by reference.

And the given example :

<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
             // $arr1 is still array(2, 3)

$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>


For the first part, the best way to be sure is to try ;-)

Consider this example of code :

function my_func($a) {
    $a[] = 30;
}

$arr = array(10, 20);
my_func($arr);
var_dump($arr);

It'll give this output :

array
  0 => int 10
  1 => int 20

Which indicates the function has not modified the "outside" array that was passed as a parameter : it's passed as a copy, and not a reference.

If you want it passed by reference, you'll have to modify the function, this way :

function my_func(& $a) {
    $a[] = 30;
}

And the output will become :

array
  0 => int 10
  1 => int 20
  2 => int 30

As, this time, the array has been passed "by reference".


Don't hesitate to read the References Explained section of the manual : it should answer some of your questions ;-)

Sort array by firstname (alphabetically) in Javascript

Inspired from this answer,

users.sort((a,b) => (a.firstname  - b.firstname));

How can I use JQuery to post JSON data?

The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.

_x000D_
_x000D_
var Data = {_x000D_
"name":"jonsa",_x000D_
"e-mail":"[email protected]",_x000D_
"phone":1223456789_x000D_
};_x000D_
_x000D_
_x000D_
$.ajax({_x000D_
    type: 'POST',_x000D_
    url: '/form/',_x000D_
    data: Data,_x000D_
    success: function(data) { alert('data: ' + data); },_x000D_
    contentType: "application/json",_x000D_
    dataType: 'json'_x000D_
});
_x000D_
_x000D_
_x000D_

What is the best way to ensure only one instance of a Bash script is running?

I had the same problem, and came up with a template that uses lockfile, a pid file that holds the process id number, and a kill -0 $(cat $pid_file) check to make aborted scripts not stop the next run. This creates a foobar-$USERID folder in /tmp where the lockfile and pid file lives.

You can still call the script and do other things, as long as you keep those actions in alertRunningPS.

#!/bin/bash

user_id_num=$(id -u)
pid_file="/tmp/foobar-$user_id_num/foobar-$user_id_num.pid"
lock_file="/tmp/foobar-$user_id_num/running.lock"
ps_id=$$

function alertRunningPS () {
    local PID=$(cat "$pid_file" 2> /dev/null)
    echo "Lockfile present. ps id file: $PID"
    echo "Checking if process is actually running or something left over from crash..."
    if kill -0 $PID 2> /dev/null; then
        echo "Already running, exiting"
        exit 1
    else
        echo "Not running, removing lock and continuing"
        rm -f "$lock_file"
        lockfile -r 0 "$lock_file"
    fi
}

echo "Hello, checking some stuff before locking stuff"

# Lock further operations to one process
mkdir -p /tmp/foobar-$user_id_num
lockfile -r 0 "$lock_file" || alertRunningPS

# Do stuff here
echo -n $ps_id > "$pid_file"
echo "Running stuff in ONE ps"

sleep 30s

rm -f "$lock_file"
rm -f "$pid_file"
exit 0

How to get current date in 'YYYY-MM-DD' format in ASP.NET?

<%: DateTime.Today.ToShortDateString() %>

Deep copy, shallow copy, clone

Unfortunately, "shallow copy", "deep copy" and "clone" are all rather ill-defined terms.


In the Java context, we first need to make a distinction between "copying a value" and "copying an object".

int a = 1;
int b = a;     // copying a value
int[] s = new int[]{42};
int[] t = s;   // copying a value (the object reference for the array above)

StringBuffer sb = new StringBuffer("Hi mom");
               // copying an object.
StringBuffer sb2 = new StringBuffer(sb);

In short, an assignment of a reference to a variable whose type is a reference type is "copying a value" where the value is the object reference. To copy an object, something needs to use new, either explicitly or under the hood.


Now for "shallow" versus "deep" copying of objects. Shallow copying generally means copying only one level of an object, while deep copying generally means copying more than one level. The problem is in deciding what we mean by a level. Consider this:

public class Example {
    public int foo;
    public int[] bar;
    public Example() { };
    public Example(int foo, int[] bar) { this.foo = foo; this.bar = bar; };
}

Example eg1 = new Example(1, new int[]{1, 2});
Example eg2 = ... 

The normal interpretation is that a "shallow" copy of eg1 would be a new Example object whose foo equals 1 and whose bar field refers to the same array as in the original; e.g.

Example eg2 = new Example(eg1.foo, eg1.bar);

The normal interpretation of a "deep" copy of eg1 would be a new Example object whose foo equals 1 and whose bar field refers to a copy of the original array; e.g.

Example eg2 = new Example(eg1.foo, Arrays.copy(eg1.bar));

(People coming from a C / C++ background might say that a reference assignment produces a shallow copy. However, that's not what we normally mean by shallow copying in the Java context ...)

Two more questions / areas of uncertainty exist:

  • How deep is deep? Does it stop at two levels? Three levels? Does it mean the whole graph of connected objects?

  • What about encapsulated data types; e.g. a String? A String is actually not just one object. In fact, it is an "object" with some scalar fields, and a reference to an array of characters. However, the array of characters is completely hidden by the API. So, when we talk about copying a String, does it make sense to call it a "shallow" copy or a "deep" copy? Or should we just call it a copy?


Finally, clone. Clone is a method that exists on all classes (and arrays) that is generally thought to produce a copy of the target object. However:

  • The specification of this method deliberately does not say whether this is a shallow or deep copy (assuming that is a meaningful distinction).

  • In fact, the specification does not even specifically state that clone produces a new object.

Here's what the javadoc says:

"Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression x.clone() != x will be true, and that the expression x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements. While it is typically the case that x.clone().equals(x) will be true, this is not an absolute requirement."

Note, that this is saying that at one extreme the clone might be the target object, and at the other extreme the clone might not equal the original. And this assumes that clone is even supported.

In short, clone potentially means something different for every Java class.


Some people argue (as @supercat does in comments) that the Java clone() method is broken. But I think the correct conclusion is that the concept of clone is broken in the context of OO. AFAIK, it is impossible to develop a unified model of cloning that is consistent and usable across all object types.

Multi-key dictionary in c#?

I've also used tuples as jason in his answer does. However, I suggest you simply define a tuple as a struct:

public struct Tuple<T1, T2> {
    public readonly T1 Item1;
    public readonly T2 Item2;
    public Tuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2;} 
}

public static class Tuple { // for type-inference goodness.
    public static Tuple<T1,T2> Create<T1,T2>(T1 item1, T2 item2) { 
        return new Tuple<T1,T2>(item1, item2); 
    }
}

You get immutability, .GetHashcode and .Equals for free, which (while you're waiting for C# 4.0) is nice 'n simple...

One warning however: the default GetHashcode implementation (sometimes) only considers the first field so make sure to make the first field the most discriminating or implement GetHashcode yourself (e.g. using FieldwiseHasher.Hash(this) from ValueUtils), otherwise you'll likely run into scalability issues.

Also, you get to avoid nulls which tend to complicate matters (and if you really want nulls, you just make your Tuple<> nullable). Slightly offtopic, am I the only one annoyed at the framework-level lack of support for non-null references? I work on large project, and occasionally a null creeps in somewhere it really shouldn't -- and hey presto, you get a nullreference exception -- but with a stack trace that points you to the reference's first usage, not the actually faulty code.

Of course, .NET 4.0 is pretty old by now; most of us can just use .NET 4.0's tuple.

Edit: to workaround the poor GetHashCode implementation that .NET provides for structs I've written ValueUtils, which also allows you to use real names for your multi-field keys; that means you might write something like:

sealed class MyValueObject : ValueObject<MyValueObject> {
    public DayOfWeek day;
    public string NamedPart;
    //properties work fine too
}

...which hopefully makes it easier to have human-readable names for data with value semantics, at least until some future version of C# implements proper tuples with named members; hopefully with decent hashcodes ;-).

Update select2 data without rebuilding the control

Using Select2 4.0 with Meteor you can do something like this:

Template.TemplateName.rendered = ->

  $("#select2-el").select2({
    data  : Session.get("select2Data")
  })

  @autorun ->

    # Clear the existing list options. 
    $("#select2-el").select2().empty()

    # Re-create with new options.
    $("#select2-el").select2({
      data  : Session.get("select2Data")
    })

What's happening:

  1. When Template is rendered...
  2. Init a select2 control with data from Session.
  3. @autorun (this.autorun) function runs every time the value of Session.get("select2Data") changes.
  4. Whenever Session changes, clear existing select2 options and re-create with new data.

This works for any reactive data source - such as a Collection.find().fetch() - not just Session.get().

NOTE: as of Select2 version 4.0 you must remove existing options before adding new onces. See this GitHub Issue for details. There is no method to 'update the options' without clearing the existing ones.

The above is coffeescript. Very similar for Javascript.

How can I iterate through a string and also know the index (current position)?

I would use it-str.begin() In this particular case std::distance and operator- are the same. But if container will change to something without random access, std::distance will increment first argument until it reach second, giving thus linear time and operator- will not compile. Personally I prefer the second behaviour - it's better to be notified when you algorithm from O(n) became O(n^2)...

How do I use a 32-bit ODBC driver on 64-bit Server 2008 when the installer doesn't create a standard DSN?

Open IIS manager, select Application Pools, select the application pool you are using, click on Advanced Settings in the right-hand menu. Under General, set "Enable 32-Bit Applications" to "True".

jQuery: click function exclude children.

I'm using following markup and had encoutered the same problem:

<ul class="nav">
    <li><a href="abc.html">abc</a></li>
    <li><a href="def.html">def</a></li>
</ul>

Here I have used the following logic:

$(".nav > li").click(function(e){
    if(e.target != this) return; // only continue if the target itself has been clicked
    // this section only processes if the .nav > li itself is clicked.
    alert("you clicked .nav > li, but not it's children");
});

In terms of the exact question, I can see that working as follows:

$(".example").click(function(e){
   if(e.target != this) return; // only continue if the target itself has been clicked
   $(".example").fadeOut("fast");
});

or of course the other way around:

$(".example").click(function(e){
   if(e.target == this){ // only if the target itself has been clicked
       $(".example").fadeOut("fast");
   }
});

Hope that helps.

Function to calculate distance between two coordinates

What you're using is called the haversine formula, which calculates the distance between two points on a sphere as the crow flies. The Google Maps link you provided shows the distance as 2.2 km because it's not a straight line.

Wolphram Alpha is a great resource for doing geographic calculations, and also shows a distance of 1.652 km between these two points.

Drive distance vs. straight line distance (red line mine).

If you're looking for straight-line distance (as the crow files), your function is working correctly. If what you want is driving distance (or biking distance or public transportation distance or walking distance), you'll have to use a mapping API (Google or Bing being the most popular) to get the appropriate route, which will include the distance.

Incidentally, the Google Maps API provides a packaged method for spherical distance, in its google.maps.geometry.spherical namespace (look for computeDistanceBetween). It's probably better than rolling your own (for starters, it uses a more precise value for the Earth's radius).

For the picky among us, when I say "straight-line distance", I'm referring to a "straight line on a sphere", which is actually a curved line (i.e. the great-circle distance), of course.

Using crontab to execute script every minute and another every 24 hours

This is the format of /etc/crontab:

# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

I recommend copy & pasting that into the top of your crontab file so that you always have the reference handy. RedHat systems are setup that way by default.

To run something every minute:

* * * * * username /var/www/html/a.php

To run something at midnight of every day:

0 0 * * * username /var/www/html/reset.php

You can either include /usr/bin/php in the command to run, or you can make the php scripts directly executable:

chmod +x file.php

Start your php file with a shebang so that your shell knows which interpreter to use:

#!/usr/bin/php
<?php
// your code here

Align div with fixed position on the right side

With position fixed, you need to provide values to set where the div will be placed, since it's a fixed position.

Something like....

.test
{
   position:fixed;
   left:100px;
   top:150px;
}

Fixed - Generates an absolutely positioned element, positioned relative to the browser window. The element's position is specified with the "left", "top", "right", and "bottom" properties

More on position here.

Pad left or right with string.format (not padleft or padright) with arbitrary string

There is another solution.

Implement IFormatProvider to return a ICustomFormatter that will be passed to string.Format :

public class StringPadder : ICustomFormatter
{
  public string Format(string format, object arg,
       IFormatProvider formatProvider)
  {
     // do padding for string arguments
     // use default for others
  }
}

public class StringPadderFormatProvider : IFormatProvider
{
  public object GetFormat(Type formatType)
  { 
     if (formatType == typeof(ICustomFormatter))
        return new StringPadder();

     return null;
  }
  public static readonly IFormatProvider Default =
     new StringPadderFormatProvider();
}

Then you can use it like this :

string.Format(StringPadderFormatProvider.Default, "->{0:x20}<-", "Hello");

Running Google Maps v2 on the Android emulator

I have successfully run our app, which requires Google Maps API 2, on an AndroVM virtual machine.

AndroVM does not come with Google Maps or Google Play installed, but provides a modified copy of the Cyanogen Gapps archive, which is a set of the proprietary Google apps installed on most Android devices.

The instructions, copied from the AndroVM FAQ:

How can I install Google Apps (including the Market/Play app) ?

  • Download Google Apps : gapps-jb-20121011-androvm.tgz [basically the /system directory from the Cyanogen gapps archive without the GoogleTTS app which crashes on AndroVM]
  • Untar the gapps…tgz file on your host – you’ll have a system directory created
  • Get the management IP address of your AndroVM (“AndroVM Configuration” tool) and do “adb connect x.y.z.t”
  • do “adb root”
  • reconnect with “adn connect x.y.z.t”
  • do “adb remount”
  • do “adb push system/ /system/”

Your VM will reboot and you should have google apps including Market/Play.

You won’t have some Google Apps, like Maps, but they can be downloaded from the Market/Play.

So follow those instructions, then just install Google Maps using Google Play!

Some great side effects of using a VM rather than the emulator:

  • Vastly superior general performance
  • OpenGL acceleration
  • Google Play support

The only bump in the road so far has been lack of multi-touch gestures, which is a bummer for a mapping app! I plan to work around this with a hidden UI mechanism, so not such a huge problem.

How do I get the path of the Python script I am running in?

7.2 of Dive Into Python: Finding the Path.

import sys, os

print('sys.argv[0] =', sys.argv[0])             
pathname = os.path.dirname(sys.argv[0])        
print('path =', pathname)
print('full path =', os.path.abspath(pathname)) 

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

Firstly, I would try a non-secure websocket connection. So remove one of the s's from the connection address:

conn = new WebSocket('ws://localhost:8080');

If that doesn't work, then the next thing I would check is your server's firewall settings. You need to open port 8080 both in TCP_IN and TCP_OUT.

How do I print output in new line in PL/SQL?

Pass the string and replace space with line break, it gives you desired result.

select replace('shailendra kumar',' ',chr(10)) from dual;

Got a NumberFormatException while trying to parse a text file for objects

NumberFormatException invoke when you ll try to convert inavlid String for eg:"abc" value to integer..

this is valid string is eg"123". in your case split by space..

split(" "); will split line by " " by space..

Delete empty rows

If you are trying to delete empty spaces , try using ='' instead of is null. Hence , if your row contains empty spaces , is null will not capture those records. Empty space is not null and null is not empty space.

Dec  Hex     Binary    Char-acter Description
0    00  00000000      NUL        null

32  20  00100000      Space       space

So I recommend:

delete  from foo_table  where bar = ''

#or 

delete  from foo_table  where bar = '' or bar is null 

#or even better , 

delete from foo_table where rtrim(ltrim(isnull(bar,'')))='';

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

while installing vc_redist.x64.exe, getting error "Failed to configure per-machine MSU package."

I would like to give you a background on Universal CRT this would help you in understanding as to why the system should be updated before installing vc_redist.x64.exe.

  1. A large portion of the C-runtime moved into the OS in Windows 10 (ucrtbase.dll) and is serviced just like any other OS DLL (e.g. kernel32.dll). It is no longer serviced by Visual Studio directly. MSU packages are the file type for Windows Updates.
  2. In order to get the Windows 10 Universal CRT to earlier OSes, Windows Update packages were created to bring this OS component downlevel. KB2999226 brings the Windows 10 RTM Universal CRT to downlevel platforms (Windows Vista through Windows 8.1). KB3118401 brings Windows 10 November Update to the Universal CRT to downlevel platforms.
    • Windows XP (latest SP) is an exception here. Windows Servicing does not provide downlevel packages for that OS, so Visual Studio (Visual C++) provides a mechanism to install the UCRT into System32 via the VCRedist and MSMs.
  3. The Windows Universal Runtime is included in the VC Redist exe package as it has dependency on the Windows Universal Runtime (KB2999226).
  4. Windows 10 is the only OS that ships the UCRT in-box. All prior OSes obtain the UCRT via Windows Update only. This applies to all Vista->8.1 and associated Server SKUs.

For Windows 7, 8, and 8.1 the Windows Universal Runtime must be installed via KB2999226. However it has a prerequisite update KB2919355 which contains updates that facilitate installing the KB2999226 package.

Why does KB2999226 not always install when the runtime is installed from the redistributable? What could prevent KB2999226 from installing as part of the runtime?

The UCRT MSU included in the VCRedist is installed by making a call into the Windows Update service and the KB can fail to install based upon Windows Update service activity/state:

  1. If the machine has not updated to the required servicing baseline, the UCRT MSU will be viewed as being “Not Applicable”. Ensure KB2919355 is installed. Also, there were known issues with KB2919355 so before this the following hotfix should be installed. KB2939087 KB2975061
  2. If the Windows Update service is installing other updates when the VCRedist installs, you can either see long delays or errors indicating the machine is busy.
    • This one can be resolved by waiting and trying again later (which may be why installing via Windows Update UI at a later time succeeds).
  3. If the Windows Update service is in a non-ready state, you can see errors reflecting that.

    • We recently investigated a failure with an error code indicating the WUSA service was shutting down.
  4. To identify if the prerequisite KB2919355 is installed there are 2 options:

    1. Registry key: 64bit hive

      HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\Packages\Package_for_KB2919355~31bf3856ad364e35~amd64~~6.3.1.14
      CurrentState = 112
      

      32bit hive

      HKLM\SOFTWARE\[WOW6432Node\]Microsoft\Windows\CurrentVersion\Component Based Servicing\Packages\Package_for_KB2919355~31bf3856ad364e35~x86~~6.3.1.14
      CurrentState = 112
      
    2. Or check the file version of:

      C:\Windows\SysWOW64\wuaueng.dll
      C:\Windows\System32\wuaueng.dll
      

      is 7.9.9600.17031 or later

How can I sanitize user input with PHP?

Easiest way to avoid mistakes in sanitizing input and escaping data is using PHP framework like Symfony, Nette etc. or part of that framework (templating engine, database layer, ORM).

Templating engine like Twig or Latte has output escaping on by default - you don't have to solve manually if you have properly escaped your output depending on context (HTML or Javascript part of web page).

Framework is automatically sanitizing input and you should't use $_POST, $_GET or $_SESSION variables directly, but through mechanism like routing, session handling etc.

And for database (model) layer there are ORM frameworks like Doctrine or wrappers around PDO like Nette Database.

You can read more about it here - What is a software framework?

Horizontal scroll on overflow of table

   .search-table-outter {border:2px solid red; overflow-x:scroll;}
   .search-table{table-layout: fixed; margin:40px auto 0px auto;   }
   .search-table, td, th{border-collapse:collapse; border:1px solid #777;}
   th{padding:20px 7px; font-size:15px; color:#444; background:#66C2E0;}
   td{padding:5px 10px; height:35px;}

You should provide scroll in div.

How to secure database passwords in PHP?

Your choices are kind of limited as as you say you need the password to access the database. One general approach is to store the username and password in a seperate configuration file rather than the main script. Then be sure to store that outside the main web tree. That was if there is a web configuration problem that leaves your php files being simply displayed as text rather than being executed you haven't exposed the password.

Other than that you are on the right lines with minimal access for the account being used. Add to that

  • Don't use the combination of username/password for anything else
  • Configure the database server to only accept connections from the web host for that user (localhost is even better if the DB is on the same machine) That way even if the credentials are exposed they are no use to anyone unless they have other access to the machine.
  • Obfuscate the password (even ROT13 will do) it won't put up much defense if some does get access to the file, but at least it will prevent casual viewing of it.

Peter

CodeIgniter 404 Page Not Found, but why?

If you installed new Codeigniter, please check if you added .htaccess file on root directory. If you didn't add it yet, please add it. You can put default content it the .htaccess file like below.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

#When your application folder isn't in the system folder
#This snippet prevents user access to the application folder
#Submitted by: Fabdrol
#Rename 'application' to your applications folder name.
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin

ErrorDocument 404 /index.php
</IfModule>

How to set alignment center in TextBox in ASP.NET?

To center align text

input[type='text'] { text-align:center;}

To center align the textbox in the container that it sits in, apply text-align:center to the container.

Error Running React Native App From Terminal (iOS)

You may need to install or set the location of the Xcode Command Line Tools.

Via command line

If you have Xcode downloaded you can run the following to set the path:

sudo xcode-select -s /Applications/Xcode.app

If the command line tools haven't been installed yet, you may need to run this first:

xcode-select --install

You may need to accept the Xcode license before installing command line tools:

sudo xcodebuild -license accept 

Via Xcode

Or adjust the Command Line Tools setting via Xcode (Xcode > Preferences > Locations):

Xcode preferences - Locations tab

VBA: activating/selecting a worksheet/row/cell

This is just a sample code, but it may help you get on your way:

Public Sub testIt()
    Workbooks("Workbook2").Activate
    ActiveWorkbook.Sheets("Sheet2").Activate
    ActiveSheet.Range("B3").Select
    ActiveCell.EntireRow.Insert
End Sub

I am assuming that you can open the book (called Workbook2 in the example).


I think (but I'm not sure) you can squash all this in a single line of code:

    Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert

This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.

Deleting multiple elements from a list

How about one of these (I'm very new to Python, but they seem ok):

ocean_basin = ['a', 'Atlantic', 'Pacific', 'Indian', 'a', 'a', 'a']
for i in range(1, (ocean_basin.count('a') + 1)):
    ocean_basin.remove('a')
print(ocean_basin)

['Atlantic', 'Pacific', 'Indian']

ob = ['a', 'b', 4, 5,'Atlantic', 'Pacific', 'Indian', 'a', 'a', 4, 'a']
remove = ('a', 'b', 4, 5)
ob = [i for i in ob if i not in (remove)]
print(ob)

['Atlantic', 'Pacific', 'Indian']

How do I get the AM/PM value from a DateTime?

Something like bool isPM = GetHour() > 11. But if you want to format a date to a string, you shouldn't need to do this yourself. Use the date formatting functions for that.

How to convert list of numpy arrays into single numpy array?

In general you can concatenate a whole sequence of arrays along any axis:

numpy.concatenate( LIST, axis=0 )

but you do have to worry about the shape and dimensionality of each array in the list (for a 2-dimensional 3x5 output, you need to ensure that they are all 2-dimensional n-by-5 arrays already). If you want to concatenate 1-dimensional arrays as the rows of a 2-dimensional output, you need to expand their dimensionality.

As Jorge's answer points out, there is also the function stack, introduced in numpy 1.10:

numpy.stack( LIST, axis=0 )

This takes the complementary approach: it creates a new view of each input array and adds an extra dimension (in this case, on the left, so each n-element 1D array becomes a 1-by-n 2D array) before concatenating. It will only work if all the input arrays have the same shape—even along the axis of concatenation.

vstack (or equivalently row_stack) is often an easier-to-use solution because it will take a sequence of 1- and/or 2-dimensional arrays and expand the dimensionality automatically where necessary and only where necessary, before concatenating the whole list together. Where a new dimension is required, it is added on the left. Again, you can concatenate a whole list at once without needing to iterate:

numpy.vstack( LIST )

This flexible behavior is also exhibited by the syntactic shortcut numpy.r_[ array1, ...., arrayN ] (note the square brackets). This is good for concatenating a few explicitly-named arrays but is no good for your situation because this syntax will not accept a sequence of arrays, like your LIST.

There is also an analogous function column_stack and shortcut c_[...], for horizontal (column-wise) stacking, as well as an almost-analogous function hstack—although for some reason the latter is less flexible (it is stricter about input arrays' dimensionality, and tries to concatenate 1-D arrays end-to-end instead of treating them as columns).

Finally, in the specific case of vertical stacking of 1-D arrays, the following also works:

numpy.array( LIST )

...because arrays can be constructed out of a sequence of other arrays, adding a new dimension to the beginning.

C++ compile error: has initializer but incomplete type

You need this include:

#include <sstream>

XAMPP installation on Win 8.1 with UAC Warning

There's nothing to be worried upon for this. Like other servers, install xampp somewhere outside of the default Program Files folder of Windows. It shall work fine.

I previously had wamp server installed on my machine and i never understood why wamp server installs itself outside of the default directory. Xampp cleared this, now i have both the servers lying outside the Program Files folder and are running fine.

Using grep to help subset a data frame in R

It's pretty straightforward using [ to extract:

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

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

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

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

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

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

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

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

How many bytes is unsigned long long?

Use the operator sizeof, it will give you the size of a type expressed in byte. One byte is eight bits. See the following program:

#include <iostream>

int main(int,char**)
{
 std::cout << "unsigned long long " << sizeof(unsigned long long) << "\n";
 std::cout << "unsigned long long int " << sizeof(unsigned long long int) << "\n";
 return 0;
}

RE error: illegal byte sequence on Mac OS X

A sample command that exhibits the symptom: sed 's/./@/' <<<$'\xfc' fails, because byte 0xfc is not a valid UTF-8 char.
Note that, by contrast, GNU sed (Linux, but also installable on macOS) simply passes the invalid byte through, without reporting an error.

Using the formerly accepted answer is an option if you don't mind losing support for your true locale (if you're on a US system and you never need to deal with foreign characters, that may be fine.)

However, the same effect can be had ad-hoc for a single command only:

LC_ALL=C sed -i "" 's|"iphoneos-cross","llvm-gcc:-O3|"iphoneos-cross","clang:-Os|g' Configure

Note: What matters is an effective LC_CTYPE setting of C, so LC_CTYPE=C sed ... would normally also work, but if LC_ALL happens to be set (to something other than C), it will override individual LC_*-category variables such as LC_CTYPE. Thus, the most robust approach is to set LC_ALL.

However, (effectively) setting LC_CTYPE to C treats strings as if each byte were its own character (no interpretation based on encoding rules is performed), with no regard for the - multibyte-on-demand - UTF-8 encoding that OS X employs by default, where foreign characters have multibyte encodings.

In a nutshell: setting LC_CTYPE to C causes the shell and utilities to only recognize basic English letters as letters (the ones in the 7-bit ASCII range), so that foreign chars. will not be treated as letters, causing, for instance, upper-/lowercase conversions to fail.

Again, this may be fine if you needn't match multibyte-encoded characters such as é, and simply want to pass such characters through.

If this is insufficient and/or you want to understand the cause of the original error (including determining what input bytes caused the problem) and perform encoding conversions on demand, read on below.


The problem is that the input file's encoding does not match the shell's.
More specifically, the input file contains characters encoded in a way that is not valid in UTF-8 (as @Klas Lindbäck stated in a comment) - that's what the sed error message is trying to say by invalid byte sequence.

Most likely, your input file uses a single-byte 8-bit encoding such as ISO-8859-1, frequently used to encode "Western European" languages.

Example:

The accented letter à has Unicode codepoint 0xE0 (224) - the same as in ISO-8859-1. However, due to the nature of UTF-8 encoding, this single codepoint is represented as 2 bytes - 0xC3 0xA0, whereas trying to pass the single byte 0xE0 is invalid under UTF-8.

Here's a demonstration of the problem using the string voilà encoded as ISO-8859-1, with the à represented as one byte (via an ANSI-C-quoted bash string ($'...') that uses \x{e0} to create the byte):

Note that the sed command is effectively a no-op that simply passes the input through, but we need it to provoke the error:

  # -> 'illegal byte sequence': byte 0xE0 is not a valid char.
sed 's/.*/&/' <<<$'voil\x{e0}'

To simply ignore the problem, the above LCTYPE=C approach can be used:

  # No error, bytes are passed through ('á' will render as '?', though).
LC_CTYPE=C sed 's/.*/&/' <<<$'voil\x{e0}'

If you want to determine which parts of the input cause the problem, try the following:

  # Convert bytes in the 8-bit range (high bit set) to hex. representation.
  # -> 'voil\x{e0}'
iconv -f ASCII --byte-subst='\x{%02x}' <<<$'voil\x{e0}'

The output will show you all bytes that have the high bit set (bytes that exceed the 7-bit ASCII range) in hexadecimal form. (Note, however, that that also includes correctly encoded UTF-8 multibyte sequences - a more sophisticated approach would be needed to specifically identify invalid-in-UTF-8 bytes.)


Performing encoding conversions on demand:

Standard utility iconv can be used to convert to (-t) and/or from (-f) encodings; iconv -l lists all supported ones.

Examples:

Convert FROM ISO-8859-1 to the encoding in effect in the shell (based on LC_CTYPE, which is UTF-8-based by default), building on the above example:

  # Converts to UTF-8; output renders correctly as 'voilà'
sed 's/.*/&/' <<<"$(iconv -f ISO-8859-1 <<<$'voil\x{e0}')"

Note that this conversion allows you to properly match foreign characters:

  # Correctly matches 'à' and replaces it with 'ü': -> 'voilü'
sed 's/à/ü/' <<<"$(iconv -f ISO-8859-1 <<<$'voil\x{e0}')"

To convert the input BACK to ISO-8859-1 after processing, simply pipe the result to another iconv command:

sed 's/à/ü/' <<<"$(iconv -f ISO-8859-1 <<<$'voil\x{e0}')" | iconv -t ISO-8859-1

Can I set a breakpoint on 'memory access' in GDB?

Assuming the first answer is referring to the C-like syntax (char *)(0x135700 +0xec1a04f) then the answer to do rwatch *0x135700+0xec1a04f is incorrect. The correct syntax is rwatch *(0x135700+0xec1a04f).

The lack of ()s there caused me a great deal of pain trying to use watchpoints myself.

The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'

Using SSMS, I made sure the user had connect permissions on both the database and ReportServer.

On the specific database being queried, under properties, I mapped their credentials and enabled datareader and public permissions. Also, as others have stated-I made sure there were no denyread/denywrite boxes selected.

I did not want to enable db ownership when for their reports since they only needed to have select permissions.

How to open Console window in Eclipse?

I also deleted my eclipse console by mistake, however what worked best for me was to type "console" in the "Quick Access" box to the right of the menu and that brought it right back! I'm running version 4.2.1, not sure if this Quick Accessbox is available in other versions.

New line character in VB.Net?

In asp.net for giving new line character in string you should use <br> .

For window base application Environment.NewLine will work fine.

/** and /* in Java Comments

For the Java programming language, there is no difference between the two. Java has two types of comments: traditional comments (/* ... */) and end-of-line comments (// ...). See the Java Language Specification. So, for the Java programming language, both /* ... */ and /** ... */ are instances of traditional comments, and they are both treated exactly the same by the Java compiler, i.e., they are ignored (or more correctly: they are treated as white space).

However, as a Java programmer, you do not only use a Java compiler. You use a an entire tool chain, which includes e.g. the compiler, an IDE, a build system, etc. And some of these tools interpret things differently than the Java compiler. In particular, /** ... */ comments are interpreted by the Javadoc tool, which is included in the Java platform and generates documentation. The Javadoc tool will scan the Java source file and interpret the parts between /** ... */ as documentation.

This is similar to tags like FIXME and TODO: if you include a comment like // TODO: fix this or // FIXME: do that, most IDEs will highlight such comments so that you don't forget about them. But for Java, they are just comments.

MAVEN_HOME, MVN_HOME or M2_HOME

$M2_HOMEis used sometimes, for example, to install Takari Extensions for Apache Maven

One way to find $M2_HOME value is to search for mvn:

sudo find / -name "mvn" 2>/dev/null

And, probably it will be: /opt/maven/

How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?

It seems like you can also use the patch command. Put the diff in the root of the repository and run patch from the command line.

patch -i yourcoworkers.diff

or

patch -p0 -i yourcoworkers.diff

You may need to remove the leading folder structure if they created the diff without using --no-prefix.

If so, then you can remove the parts of the folder that don't apply using:

patch -p1 -i yourcoworkers.diff

The -p(n) signifies how many parts of the folder structure to remove.

More information on creating and applying patches here.

You can also use

git apply yourcoworkers.diff --stat 

to see if the diff by default will apply any changes. It may say 0 files affected if the patch is not applied correctly (different folder structure).

NuGet Package Restore Not Working

The best workaround that I found creating a new Project from scratch, then import all the source files with the code. My project was not so complicated so I had no problem from there.

How to run Java program in terminal with external library JAR

For compiling the java file having dependency on a jar

javac -cp path_of_the_jar/jarName.jar className.java

For executing the class file

java -cp .;path_of_the_jar/jarName.jar className

Init function in javascript and how it works

I can't believe no-one has answered the ops question!

The last set of brackets are used for passing in the parameters to the anonymous function. So, the following example creates a function, then runs it with the x=5 and y=8

(function(x,y){
    //code here
})(5,8)

This may seem not so useful, but it has its place. The most common one I have seen is

(function($){
    //code here
})(jQuery)

which allows for jQuery to be in compatible mode, but you can refer to it as "$" within the anonymous function.

Count specific character occurrences in a string

    ' Trying to find the amount of "." in the text
    ' if txtName looks like "hi...hi" then intdots will = 3
    Dim test As String = txtName.Text
    Dim intdots As Integer = 0
    For i = 1 To test.Length
        Dim inta As Integer = 0 + 1
        Dim stra As String = test.Substring(inta)
        If stra = "." Then
            intdots = intdots + 1
        End If
    Next
    txttest.text = intdots

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

A simpler version of your code would be:

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

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

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

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

Difference between "Complete binary tree", "strict binary tree","full binary Tree"?

Concluding from above answers, Here is the exact difference between full/strictly, complete and perfect binary trees

  1. Full/Strictly binary tree :- Every node except the leaf nodes have two children

  2. Complete binary tree :- Every level except the last level is completely filled and all the nodes are left justified.

  3. Perfect binary tree :- Every node except the leaf nodes have two children and every level (last level too) is completely filled.

Find UNC path of a network drive?

This question has been answered already, but since there is a more convenient way to get the UNC path and some more I recommend using Path Copy, which is free and you can practically get any path you want with one click:

https://pathcopycopy.github.io/

Here is a screenshot demonstrating how it works. The latest version has more options and definitely UNC Path too:

enter image description here

Is there StartsWith or Contains in t sql with variables?

I would use

like 'Express Edition%'

Example:

DECLARE @edition varchar(50); 
set @edition = cast((select SERVERPROPERTY ('edition')) as varchar)

DECLARE @isExpress bit
if @edition like 'Express Edition%'
    set @isExpress = 1;
else
    set @isExpress = 0;

print @isExpress

Get value of multiselect box using jQuery or pure JS

the val function called from the select will return an array if its a multiple. $('select#my_multiselect').val() will return an array of the values for the selected options - you dont need to loop through and get them yourself.

Postgres: clear entire database before re-creating / re-populating from bash script

If you don't actually need a backup of the database dumped onto disk in a plain-text .sql script file format, you could connect pg_dump and pg_restore directly together over a pipe.

To drop and recreate tables, you could use the --clean command-line option for pg_dump to emit SQL commands to clean (drop) database objects prior to (the commands for) creating them. (This will not drop the whole database, just each table/sequence/index/etc. before recreating them.)

The above two would look something like this:

pg_dump -U username --clean | pg_restore -U username

is not JSON serializable

It's worth noting that the QuerySet.values_list() method doesn't actually return a list, but an object of type django.db.models.query.ValuesListQuerySet, in order to maintain Django's goal of lazy evaluation, i.e. the DB query required to generate the 'list' isn't actually performed until the object is evaluated.

Somewhat irritatingly, though, this object has a custom __repr__ method which makes it look like a list when printed out, so it's not always obvious that the object isn't really a list.

The exception in the question is caused by the fact that custom objects cannot be serialized in JSON, so you'll have to convert it to a list first, with...

my_list = list(self.get_queryset().values_list('code', flat=True))

...then you can convert it to JSON with...

json_data = json.dumps(my_list)

You'll also have to place the resulting JSON data in an HttpResponse object, which, apparently, should have a Content-Type of application/json, with...

response = HttpResponse(json_data, content_type='application/json')

...which you can then return from your function.

What's the correct way to communicate between controllers in AngularJS?

I've actually started using Postal.js as a message bus between controllers.

There are lots of benefits to it as a message bus such as AMQP style bindings, the way postal can integrate w/ iFrames and web sockets, and many more things.

I used a decorator to get Postal set up on $scope.$bus...

angular.module('MyApp')  
.config(function ($provide) {
    $provide.decorator('$rootScope', ['$delegate', function ($delegate) {
        Object.defineProperty($delegate.constructor.prototype, '$bus', {
            get: function() {
                var self = this;

                return {
                    subscribe: function() {
                        var sub = postal.subscribe.apply(postal, arguments);

                        self.$on('$destroy',
                        function() {
                            sub.unsubscribe();
                        });
                    },
                    channel: postal.channel,
                    publish: postal.publish
                };
            },
            enumerable: false
        });

        return $delegate;
    }]);
});

Here's a link to a blog post on the topic...
http://jonathancreamer.com/an-angular-event-bus-with-postal-js/

Back button and refreshing previous activity

 @Override
protected void onRestart() {
    super.onRestart();
    finish();
    overridePendingTransition(0, 0);
    startActivity(getIntent());
    overridePendingTransition(0, 0);
}

In previous activity use this code. This will do a smooth transition and reload the activity when you come back by pressing back button.

Spring cron expression for every after 30 minutes

in web app java spring what worked for me

cron="0 0/30 * * * ?"

This will trigger on for example 10:00AM then 10:30AM etc...

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:beans="http://www.springframework.org/schema/beans"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/task 
    http://www.springframework.org/schema/task/spring-task.xsd">

    <beans profile="cron">
        <bean id="executorService" class="java.util.concurrent.Executors" factory-method="newFixedThreadPool">
            <beans:constructor-arg value="5" />
        </bean>

        <task:executor id="threadPoolTaskExecutor" pool-size="5" />
        <task:annotation-driven executor="executorService" />

        <beans:bean id="expireCronJob" class="com.cron.ExpireCron"/>

        <task:scheduler id="serverScheduler" pool-size="5"/>
        <task:scheduled-tasks scheduler="serverScheduler">
            <task:scheduled ref="expireCronJob" method="runTask" cron="0 0/30 * * * ?"/> <!-- every thirty minute -->
        </task:scheduled-tasks>

    </beans>

</beans>

I dont know why but this is working on my local develop and production, but other changes if i made i have to be careful because it may work local and on develop but not on production

JQuery style display value

Just call css with one argument

  $('#idDetails').css('display');

If I understand your question. Otherwise, you want cletus' answer.

How does a hash table work?

It's even simpler than that.

A hashtable is nothing more than an array (usually sparse one) of vectors which contain key/value pairs. The maximum size of this array is typically smaller than the number of items in the set of possible values for the type of data being stored in the hashtable.

The hash algorithm is used to generate an index into that array based on the values of the item that will be stored in the array.

This is where storing vectors of key/value pairs in the array come in. Because the set of values that can be indexes in the array is typically smaller than the number of all possible values that the type can have, it is possible that your hash algorithm is going to generate the same value for two separate keys. A good hash algorithm will prevent this as much as possible (which is why it is relegated to the type usually because it has specific information which a general hash algorithm can't possibly know), but it's impossible to prevent.

Because of this, you can have multiple keys that will generate the same hash code. When that happens, the items in the vector are iterated through, and a direct comparison is done between the key in the vector and the key that is being looked up. If it is found, great and the value associated with the key is returned, otherwise, nothing is returned.

How to get the Power of some Integer in Swift language?

Array(repeating: a, count: b).reduce(1, *)

Number to String in a formula field

I believe this is what you're looking for:

Convert Decimal Numbers to Text showing only the non-zero decimals

Especially this line might be helpful:

StringVar text     :=  Totext ( {Your.NumberField} , 6 , ""  )  ;

The first parameter is the decimal to be converted, the second parameter is the number of decimal places and the third parameter is the separator for thousands/millions etc.

How to zip a file using cmd line?

ZIP FILE via Cross-platform Java without manifest and META-INF folder:

jar -cMf {yourfile.zip} {yourfolder}

Convert JSONArray to String Array

String[] arr = jsonArray.toString().replace("},{", " ,").split(" ");

How do I see the commit differences between branches in git?

If you are on Linux, gitg is way to go to do it very quickly and graphically.

If you insist on command line you can use:

git log --oneline --decorate

To make git log nicer by default, I typically set these global preferences:

git config --global log.decorate true
git config --global log.abbrevCommit true

How can I remove non-ASCII characters but leave periods and spaces using Python?

According to @artfulrobot, this should be faster than filter and lambda:

import re
re.sub(r'[^\x00-\x7f]',r'', your-non-ascii-string) 

See more examples here Replace non-ASCII characters with a single space

how to convert `content://media/external/images/media/Y` to `file:///storage/sdcard0/Pictures/X.jpg` in android?

Will something like this work for you? What this does is query the content resolver to find the file path data that is stored for that content entry

public static String getRealPathFromUri(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

This will end up giving you an absolute file path that you can construct a file uri from

Printing a java map Map<String, Object> - How?

I'm sure there's some nice library that does this sort of thing already for you... But to just stick with the approach you're already going with, Map#entrySet gives you a combined Object with the key and the value. So something like:

for (Map.Entry<String, Object> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ":" + entry.getValue().toString());
}

will do what you're after.


If you're using java 8, there's also the new streaming approach.

map.forEach((key, value) -> System.out.println(key + ":" + value));

Angular - Set headers for every request

For Angular 5 and above, we can use HttpInterceptor for generalizing the request and response operations. This helps us avoid duplicating:

1) Common headers

2) Specifying response type

3) Querying request

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpResponse,
  HttpErrorResponse
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';

@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {

  requestCounter: number = 0;
  constructor() {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    request = request.clone({
      responseType: 'json',
      setHeaders: {
        Authorization: `Bearer token_value`,
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    });

    return next.handle(request).do((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        // do stuff with response if you want
      }
    }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        // do stuff with response error if you want
      }
    });
  }
}

We can use this AuthHttpInterceptor class as a provider for the HttpInterceptors:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app.routing-module';
import { AuthHttpInterceptor } from './services/auth-http.interceptor';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    BrowserAnimationsModule,
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthHttpInterceptor,
      multi: true
    }
  ],
  exports: [],
  bootstrap: [AppComponent]
})
export class AppModule {
}

Simple URL GET/POST function in Python

I know you asked for GET and POST but I will provide CRUD since others may need this just in case: (this was tested in Python 3.7)

#!/usr/bin/env python3
import http.client
import json

print("\n GET example")
conn = http.client.HTTPSConnection("httpbin.org")
conn.request("GET", "/get")
response = conn.getresponse()
data = response.read().decode('utf-8')
print(response.status, response.reason)
print(data)


print("\n POST example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body = {'text': 'testing post'}
json_data = json.dumps(post_body)
conn.request('POST', '/post', json_data, headers)
response = conn.getresponse()
print(response.read().decode())
print(response.status, response.reason)


print("\n PUT example ")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing put'}
json_data = json.dumps(post_body)
conn.request('PUT', '/put', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)


print("\n delete example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing delete'}
json_data = json.dumps(post_body)
conn.request('DELETE', '/delete', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

Can you append strings to variables in PHP?

This is because PHP uses the period character . for string concatenation, not the plus character +. Therefore to append to a string you want to use the .= operator:

for ($i=1;$i<=100;$i++)
{
    $selectBox .= '<option value="' . $i . '">' . $i . '</option>';
}
$selectBox .= '</select>';

Is there a timeout for idle PostgreSQL connections?

Another option is set this value "tcp_keepalives_idle". Check more in documentation https://www.postgresql.org/docs/10/runtime-config-connection.html.

How many significant digits do floats and doubles have in java?

A normal math answer.

Understanding that a floating point number is implemented as some bits representing the exponent and the rest, most for the digits (in the binary system), one has the following situation:

With a high exponent, say 10²³ if the least significant bit is changed, a large difference between two adjacent distinghuishable numbers appear. Furthermore the base 2 decimal point makes that many base 10 numbers can only be approximated; 1/5, 1/10 being endless numbers.

So in general: floating point numbers should not be used if you care about significant digits. For monetary amounts with calculation, e,a, best use BigDecimal.

For physics floating point doubles are adequate, floats almost never. Furthermore the floating point part of processors, the FPU, can even use a bit more precission internally.

Linux shell script for database backup

Now, copy the following content in a script file (like: /backup/mysql-backup.sh) and save on your Linux system.

    #!/bin/bash

    export PATH=/bin:/usr/bin:/usr/local/bin
    TODAY=`date +"%d%b%Y"`

    DB_BACKUP_PATH='/backup/dbbackup'
    MYSQL_HOST='localhost'
    MYSQL_PORT='3306'
    MYSQL_USER='root'
    MYSQL_PASSWORD='mysecret'
    DATABASE_NAME='mydb'
    BACKUP_RETAIN_DAYS=30   

    mkdir -p ${DB_BACKUP_PATH}/${TODAY}
    echo "Backup started for database - ${DATABASE_NAME}"

    mysqldump -h ${MYSQL_HOST} \
   -P ${MYSQL_PORT} \
   -u ${MYSQL_USER} \
   -p${MYSQL_PASSWORD} \
   ${DATABASE_NAME} | gzip > ${DB_BACKUP_PATH}/${TODAY}/${DATABASE_NAME}-${TODAY}.sql.gz

if [ $? -eq 0 ]; then
  echo "Database backup successfully completed"
else
  echo "Error found during backup"
  exit 1
fi


##### Remove backups older than {BACKUP_RETAIN_DAYS} days  #####

DBDELDATE=`date +"%d%b%Y" --date="${BACKUP_RETAIN_DAYS} days ago"`

if [ ! -z ${DB_BACKUP_PATH} ]; then
      cd ${DB_BACKUP_PATH}
      if [ ! -z ${DBDELDATE} ] && [ -d ${DBDELDATE} ]; then
            rm -rf ${DBDELDATE}
      fi
fi

After creating or downloading script make sure to set execute permission to run properly.

$ chmod +x /backup/mysql-backup.sh

Edit crontab on your system with crontab -e command. Add following settings to enable backup at 3 in the morning.

0 3 * * * root /backup/mysql-backup.sh

How do you use bcrypt for hashing passwords in PHP?

The password_hash() function in PHP is an inbuilt function , used to create a new password hash with different algorithms and options. the function uses a strong hashing algorithm.

the function take 2 mandetory parametres ($password and $algorithm,) and 1 optional parameter ($options).

$strongPassword = password_hash( $password, $algorithm, $options )


Algoristrong textthms allowed right now for password_hash() are :

  • PASSWORD_DEFAULT

  • PASSWORD_BCRYPT

  • ASSWORD_ARGON2I

  • PASSWORD_ARGON2ID


example : echo password_hash("abcDEF", PASSWORD_DEFAULT);

answer : $2y$10$KwKceUaG84WInAif5ehdZOkE4kHPWTLp0ZK5a5OU2EbtdwQ9YIcGy


example: `echo password_hash("abcDEF", PASSWORD_BCRYPT);`

answer :$2y$10$SNly5bFzB/R6OVbBMq1bj.yiOZdsk6Mwgqi4BLR2sqdCvMyv/AyL2


to use the BCRYPT as password, use option cost =12 in an array , also change 1st parameter $password to some strong password like "wgt167yuWBGY@#1987__"

Example: echo password_hash("wgt167yuWBGY@#1987__", PASSWORD_BCRYPT ,['cost' => 12]);

Answer : $2y$12$TjSggXiFSidD63E.QP8PJOds2texJfsk/82VaNU8XRZ/niZhzkJ6S

Java get last element of a collection

There isn't a last() or first() method in a Collection interface. For getting the last method, you can either do get(size() - 1) on a List or reverse the List and do get(0). I don't see a need to have last() method in any Collection API unless you are dealing with Stacks or Queues

When should an IllegalArgumentException be thrown?

Treat IllegalArgumentException as a preconditions check, and consider the design principle: A public method should both know and publicly document its own preconditions.

I would agree this example is correct:

void setPercentage(int pct) {
    if( pct < 0 || pct > 100) {
         throw new IllegalArgumentException("bad percent");
     }
}

If EmailUtil is opaque, meaning there's some reason the preconditions cannot be described to the end-user, then a checked exception is correct. The second version, corrected for this design:

import com.someoneelse.EmailUtil;

public void scanEmail(String emailStr, InputStream mime) throws ParseException {
    EmailAddress parsedAddress = EmailUtil.parseAddress(emailStr);
}

If EmailUtil is transparent, for instance maybe it's a private method owned by the class under question, IllegalArgumentException is correct if and only if its preconditions can be described in the function documentation. This is a correct version as well:

/** @param String email An email with an address in the form [email protected]
 * with no nested comments, periods or other nonsense.
 */
public String scanEmail(String email)
  if (!addressIsProperlyFormatted(email)) {
      throw new IllegalArgumentException("invalid address");
  }
  return parseEmail(emailAddr);
}
private String parseEmail(String emailS) {
  // Assumes email is valid
  boolean parsesJustFine = true;
  // Parse logic
  if (!parsesJustFine) {
    // As a private method it is an internal error if address is improperly
    // formatted. This is an internal error to the class implementation.
    throw new AssertError("Internal error");
  }
}

This design could go either way.

  • If preconditions are expensive to describe, or if the class is intended to be used by clients who don't know whether their emails are valid, then use ParseException. The top level method here is named scanEmail which hints the end user intends to send unstudied email through so this is likely correct.
  • If preconditions can be described in function documentation, and the class does not intent for invalid input and therefore programmer error is indicated, use IllegalArgumentException. Although not "checked" the "check" moves to the Javadoc documenting the function, which the client is expected to adhere to. IllegalArgumentException where the client can't tell their argument is illegal beforehand is wrong.

A note on IllegalStateException: This means "this object's internal state (private instance variables) is not able to perform this action." The end user cannot see private state so loosely speaking it takes precedence over IllegalArgumentException in the case where the client call has no way to know the object's state is inconsistent. I don't have a good explanation when it's preferred over checked exceptions, although things like initializing twice, or losing a database connection that isn't recovered, are examples.

Disabling Minimize & Maximize On WinForm?

The Form has two properties called MinimizeBox and MaximizeBox, set both of them to false.

To stop the form closing, handle the FormClosing event, and set e.Cancel = true; in there and after that, set WindowState = FormWindowState.Minimized;, to minimize the form.

Ubuntu - Run command on start-up with "sudo"

You can add the command in the /etc/rc.local script that is executed at the end of startup.

Write the command before exit 0. Anything written after exit 0 will never be executed.

Oracle date "Between" Query

Following query also can be used:

select * 
  from t23
 where trunc(start_date) between trunc(to_date('01/15/2010','mm/dd/yyyy')) and trunc(to_date('01/17/2010','mm/dd/yyyy'))

How can I read the client's machine/computer name from the browser?

No this data is not exposed. The only data that is available is what is exposed through the HTTP request which might include their OS and other such information. But certainly not machine name.

How to initialise a string from NSData in Swift

Since the third version of Swift you can do the following:

let desiredString = NSString(data: yourData, encoding: String.Encoding.utf8.rawValue)

simialr to what Sunkas advised.

How to install bcmath module?

ubuntu and php7.1

sudo apt install php7.1-bcmath

ubuntu and php without version specification

sudo apt install php-bcmath

How to set max width of an image in CSS

You can write like this:

img{
    width:100%;
    max-width:600px;
}

Check this http://jsfiddle.net/ErNeT/

iOS: set font size of UILabel Programmatically

In Swift 3.0, you could use this code below:

let textLabel = UILabel(frame: CGRect(x:containerView.frame.width/2 - 35, y: 
    containerView.frame.height/2 + 10, width: 70, height: 20))
    textLabel.text = "Add Text"
    textLabel.font = UIFont(name: "Helvetica", size: 15.0) // set fontName and Size
    textLabel.textAlignment = .center
    containerView.addSubview(textLabel) // containerView is a UIView

How can I merge properties of two JavaScript objects dynamically?

Similar to jQuery extend(), you have the same function in AngularJS:

// Merge the 'options' object into the 'settings' object
var settings = {validate: false, limit: 5, name: "foo"};
var options  = {validate: true, name: "bar"};
angular.extend(settings, options);

Difference between DTO, VO, POJO, JavaBeans?

First Talk About

Normal Class - that's mean any class define that's a normally in java it's means you create different type of method properties etc.
Bean - Bean is nothing it's only a object of that particular class using this bean you can access your java class same as object..

and after that talk about last one POJO

POJO - POJO is that class which have no any services it's have only a default constructor and private property and those property for setting a value corresponding setter and getter methods. It's short form of Plain Java Object.

How to know if an object has an attribute in Python

Another possible option, but it depends if what you mean by before:

undefined = object()

class Widget:

    def __init__(self):
        self.bar = 1

    def zoom(self):
        print("zoom!")

a = Widget()

bar = getattr(a, "bar", undefined)
if bar is not undefined:
    print("bar:%s" % (bar))

foo = getattr(a, "foo", undefined)
if foo is not undefined:
    print("foo:%s" % (foo))

zoom = getattr(a, "zoom", undefined)
if zoom is not undefined:
    zoom()

output:

bar:1
zoom!

This allows you to even check for None-valued attributes.

But! Be very careful you don't accidentally instantiate and compare undefined multiple places because the is will never work in that case.

Update:

because of what I was warning about in the above paragraph, having multiple undefineds that never match, I have recently slightly modified this pattern:

undefined = NotImplemented

NotImplemented, not to be confused with NotImplementedError, is a built-in: it semi-matches the intent of a JS undefined and you can reuse its definition everywhere and it will always match. The drawbacks is that it is "truthy" in booleans and it can look weird in logs and stack traces (but you quickly get over it when you know it only appears in this context).

Problem with SMTP authentication in PHP using PHPMailer, with Pear Mail works

This isn't on the code parter it's on the server side Contact your Server Manager or fix it from server if you own it If you use CPANEL/WHM GO TO WHM/SMTP RESTRICTIONS AND DISABLE IT

What is the most efficient way to create a dictionary of two pandas Dataframe columns?

In [9]: pd.Series(df.Letter.values,index=df.Position).to_dict()
Out[9]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

Speed comparion (using Wouter's method)

In [6]: df = pd.DataFrame(randint(0,10,10000).reshape(5000,2),columns=list('AB'))

In [7]: %timeit dict(zip(df.A,df.B))
1000 loops, best of 3: 1.27 ms per loop

In [8]: %timeit pd.Series(df.A.values,index=df.B).to_dict()
1000 loops, best of 3: 987 us per loop

How to open the terminal in Atom?

  1. Open your Atom IDE
  2. press ctrl+shift+P and search for "platformio-ide-terminal" package
  3. press install
  4. once installed press ctrl+~ (tilde above tab key in a standard keyboard)
  5. terminal opens enjoy!!!

Fast Bitmap Blur For Android SDK

For future Googlers, here is an algorithm that I ported from Quasimondo. It's kind of a mix between a box blur and a gaussian blur, it's very pretty and quite fast too.

Update for people encountering the ArrayIndexOutOfBoundsException problem : @anthonycr in the comments provides this information :

I found that by replacing Math.abs with StrictMath.abs or some other abs implementation, the crash does not occur.

/**
 * Stack Blur v1.0 from
 * http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
 * Java Author: Mario Klingemann <mario at quasimondo.com>
 * http://incubator.quasimondo.com
 *
 * created Feburary 29, 2004
 * Android port : Yahel Bouaziz <yahel at kayenko.com>
 * http://www.kayenko.com
 * ported april 5th, 2012
 *
 * This is a compromise between Gaussian Blur and Box blur
 * It creates much better looking blurs than Box Blur, but is
 * 7x faster than my Gaussian Blur implementation.
 *
 * I called it Stack Blur because this describes best how this
 * filter works internally: it creates a kind of moving stack
 * of colors whilst scanning through the image. Thereby it
 * just has to add one new block of color to the right side
 * of the stack and remove the leftmost color. The remaining
 * colors on the topmost layer of the stack are either added on
 * or reduced by one, depending on if they are on the right or
 * on the left side of the stack.
 *  
 * If you are using this algorithm in your code please add
 * the following line:
 * Stack Blur Algorithm by Mario Klingemann <[email protected]>
 */

public Bitmap fastblur(Bitmap sentBitmap, float scale, int radius) {

    int width = Math.round(sentBitmap.getWidth() * scale);
    int height = Math.round(sentBitmap.getHeight() * scale);
    sentBitmap = Bitmap.createScaledBitmap(sentBitmap, width, height, false);

    Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);

    if (radius < 1) {
        return (null);
    }

    int w = bitmap.getWidth();
    int h = bitmap.getHeight();

    int[] pix = new int[w * h];
    Log.e("pix", w + " " + h + " " + pix.length);
    bitmap.getPixels(pix, 0, w, 0, 0, w, h);

    int wm = w - 1;
    int hm = h - 1;
    int wh = w * h;
    int div = radius + radius + 1;

    int r[] = new int[wh];
    int g[] = new int[wh];
    int b[] = new int[wh];
    int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
    int vmin[] = new int[Math.max(w, h)];

    int divsum = (div + 1) >> 1;
    divsum *= divsum;
    int dv[] = new int[256 * divsum];
    for (i = 0; i < 256 * divsum; i++) {
        dv[i] = (i / divsum);
    }

    yw = yi = 0;

    int[][] stack = new int[div][3];
    int stackpointer;
    int stackstart;
    int[] sir;
    int rbs;
    int r1 = radius + 1;
    int routsum, goutsum, boutsum;
    int rinsum, ginsum, binsum;

    for (y = 0; y < h; y++) {
        rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
        for (i = -radius; i <= radius; i++) {
            p = pix[yi + Math.min(wm, Math.max(i, 0))];
            sir = stack[i + radius];
            sir[0] = (p & 0xff0000) >> 16;
            sir[1] = (p & 0x00ff00) >> 8;
            sir[2] = (p & 0x0000ff);
            rbs = r1 - Math.abs(i);
            rsum += sir[0] * rbs;
            gsum += sir[1] * rbs;
            bsum += sir[2] * rbs;
            if (i > 0) {
                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];
            } else {
                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];
            }
        }
        stackpointer = radius;

        for (x = 0; x < w; x++) {

            r[yi] = dv[rsum];
            g[yi] = dv[gsum];
            b[yi] = dv[bsum];

            rsum -= routsum;
            gsum -= goutsum;
            bsum -= boutsum;

            stackstart = stackpointer - radius + div;
            sir = stack[stackstart % div];

            routsum -= sir[0];
            goutsum -= sir[1];
            boutsum -= sir[2];

            if (y == 0) {
                vmin[x] = Math.min(x + radius + 1, wm);
            }
            p = pix[yw + vmin[x]];

            sir[0] = (p & 0xff0000) >> 16;
            sir[1] = (p & 0x00ff00) >> 8;
            sir[2] = (p & 0x0000ff);

            rinsum += sir[0];
            ginsum += sir[1];
            binsum += sir[2];

            rsum += rinsum;
            gsum += ginsum;
            bsum += binsum;

            stackpointer = (stackpointer + 1) % div;
            sir = stack[(stackpointer) % div];

            routsum += sir[0];
            goutsum += sir[1];
            boutsum += sir[2];

            rinsum -= sir[0];
            ginsum -= sir[1];
            binsum -= sir[2];

            yi++;
        }
        yw += w;
    }
    for (x = 0; x < w; x++) {
        rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
        yp = -radius * w;
        for (i = -radius; i <= radius; i++) {
            yi = Math.max(0, yp) + x;

            sir = stack[i + radius];

            sir[0] = r[yi];
            sir[1] = g[yi];
            sir[2] = b[yi];

            rbs = r1 - Math.abs(i);

            rsum += r[yi] * rbs;
            gsum += g[yi] * rbs;
            bsum += b[yi] * rbs;

            if (i > 0) {
                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];
            } else {
                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];
            }

            if (i < hm) {
                yp += w;
            }
        }
        yi = x;
        stackpointer = radius;
        for (y = 0; y < h; y++) {
            // Preserve alpha channel: ( 0xff000000 & pix[yi] )
            pix[yi] = ( 0xff000000 & pix[yi] ) | ( dv[rsum] << 16 ) | ( dv[gsum] << 8 ) | dv[bsum];

            rsum -= routsum;
            gsum -= goutsum;
            bsum -= boutsum;

            stackstart = stackpointer - radius + div;
            sir = stack[stackstart % div];

            routsum -= sir[0];
            goutsum -= sir[1];
            boutsum -= sir[2];

            if (x == 0) {
                vmin[y] = Math.min(y + r1, hm) * w;
            }
            p = x + vmin[y];

            sir[0] = r[p];
            sir[1] = g[p];
            sir[2] = b[p];

            rinsum += sir[0];
            ginsum += sir[1];
            binsum += sir[2];

            rsum += rinsum;
            gsum += ginsum;
            bsum += binsum;

            stackpointer = (stackpointer + 1) % div;
            sir = stack[stackpointer];

            routsum += sir[0];
            goutsum += sir[1];
            boutsum += sir[2];

            rinsum -= sir[0];
            ginsum -= sir[1];
            binsum -= sir[2];

            yi += w;
        }
    }

    Log.e("pix", w + " " + h + " " + pix.length);
    bitmap.setPixels(pix, 0, w, 0, 0, w, h);

    return (bitmap);
}

Why doesn't document.addEventListener('load', function) work in a greasemonkey script?

Apparently, document.addEventListener() is unreliable, and hence, my error. Use window.addEventListener() with the same parameters, instead.

Attach IntelliJ IDEA debugger to a running Java process

Yes! Here is how you set it up.

Run Configuration

Create a Remote run configuration:

  1. Run -> Edit Configurations...
  2. Click the "+" in the upper left
  3. Select the "Remote" option in the left-most pane
  4. Choose a name (I named mine "remote-debugging")
  5. Click "OK" to save:

enter image description here

JVM Options

The configuration above provides three read-only fields. These are options that tell the JVM to open up port 5005 for remote debugging when running your application. Add the appropriate one to the JVM options of the application you are debugging. One way you might do this would be like so:

export JAVA_OPTS="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"

But it depends on how your run your application. If you're not sure which of the three applies to you, start with the first and go down the list until you find the one that works.

You can change suspend=n to suspend=y to force your application to wait until you connect with IntelliJ before it starts up. This is helpful if the breakpoint you want to hit occurs on application startup.

Debug

Start your application as you would normally, then in IntelliJ select the new configuration and hit 'Debug'.

enter image description here

IntelliJ will connect to the JVM and initiate remote debugging.

You can now debug the application by adding breakpoints to your code where desired. The output of the application will still appear wherever it did before, but your breakpoints will hit in IntelliJ.

How to verify Facebook access token?

The officially supported method for this is:

GET graph.facebook.com/debug_token?
     input_token={token-to-inspect}
     &access_token={app-token-or-admin-token}

See the check token docs for more information.

An example response is:

{
    "data": {
        "app_id": 138483919580948, 
        "application": "Social Cafe", 
        "expires_at": 1352419328, 
        "is_valid": true, 
        "issued_at": 1347235328, 
        "metadata": {
            "sso": "iphone-safari"
        }, 
        "scopes": [
            "email", 
            "publish_actions"
        ], 
        "user_id": 1207059
    }
}

Using the passwd command from within a shell script

Nowadays, you can use this command:

echo "user:pass" | chpasswd

Excel doesn't update value unless I hit Enter

This doesn't sound intuitive but select the column you're having the issue with and use "text to column" and just press finish. This is the suggested answer from Excel help as well. For some reason in converts text to numbers.

Visual Studio can't build due to rc.exe

Add to your environment variable window sdk 8.1 path

C:\Program Files (x86)\Windows Kits\8.1\bin\x64

then open Visual studio x64 Native tools command prompt and enter

vcvarsall.bat

PHP combine two associative arrays into one array

I use a wrapper around array_merge to deal with SeanWM's comment about null arrays; I also sometimes want to get rid of duplicates. I'm also generally wanting to merge one array into another, as opposed to creating a new array. This ends up as:

/**
 * Merge two arrays - but if one is blank or not an array, return the other.
 * @param $a array First array, into which the second array will be merged
 * @param $b array Second array, with the data to be merged
 * @param $unique boolean If true, remove duplicate values before returning
 */
function arrayMerge(&$a, $b, $unique = false) {
    if (empty($b)) {
        return;  // No changes to be made to $a
    }
    if (empty($a)) {
        $a = $b;
        return;
    }
    $a = array_merge($a, $b);
    if ($unique) {
        $a = array_unique($a);
    }
}

How do I get the time of day in javascript/Node.js?

This function will return you the date and time in the following format: YYYY:MM:DD:HH:MM:SS. It also works in Node.js.

function getDateTime() {

    var date = new Date();

    var hour = date.getHours();
    hour = (hour < 10 ? "0" : "") + hour;

    var min  = date.getMinutes();
    min = (min < 10 ? "0" : "") + min;

    var sec  = date.getSeconds();
    sec = (sec < 10 ? "0" : "") + sec;

    var year = date.getFullYear();

    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;

    var day  = date.getDate();
    day = (day < 10 ? "0" : "") + day;

    return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;

}

How do I increase the contrast of an image in Python OpenCV

Best explanation for X = aY + b (in fact it f(x) = ax + b)) is provided at https://math.stackexchange.com/a/906280/357701

A Simpler one by just adjusting lightness/luma/brightness for contrast as is below:

import cv2

img = cv2.imread('test.jpg')
cv2.imshow('test', img)
cv2.waitKey(1000)
imghsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)


imghsv[:,:,2] = [[max(pixel - 25, 0) if pixel < 190 else min(pixel + 25, 255) for pixel in row] for row in imghsv[:,:,2]]
cv2.imshow('contrast', cv2.cvtColor(imghsv, cv2.COLOR_HSV2BGR))
cv2.waitKey(1000)
raw_input()

Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

The bitmap constructor has resizing built in.

Bitmap original = (Bitmap)Image.FromFile("DSC_0002.jpg");
Bitmap resized = new Bitmap(original,new Size(original.Width/4,original.Height/4));
resized.Save("DSC_0002_thumb.jpg");

http://msdn.microsoft.com/en-us/library/0wh0045z.aspx

If you want control over interpolation modes see this post.

How does the compilation/linking process work?

GCC compiles a C/C++ program into executable in 4 steps.

For example, gcc -o hello hello.c is carried out as follows:

1. Pre-processing

Preprocessing via the GNU C Preprocessor (cpp.exe), which includes the headers (#include) and expands the macros (#define).

cpp hello.c > hello.i

The resultant intermediate file "hello.i" contains the expanded source code.

2. Compilation

The compiler compiles the pre-processed source code into assembly code for a specific processor.

gcc -S hello.i

The -S option specifies to produce assembly code, instead of object code. The resultant assembly file is "hello.s".

3. Assembly

The assembler (as.exe) converts the assembly code into machine code in the object file "hello.o".

as -o hello.o hello.s

4. Linker

Finally, the linker (ld.exe) links the object code with the library code to produce an executable file "hello".

    ld -o hello hello.o ...libraries...

Read properties file outside JAR file

Here if you mention .getPath() then that will return the path of Jar and I guess you will need its parent to refer to all other config files placed with the jar. This code works on Windows. Add the code within the main class.

File jarDir = new File(MyAppName.class.getProtectionDomain().getCodeSource().getLocation().getPath());
String jarDirpath = jarDir.getParent();

System.out.println(jarDirpath);

Tomcat: How to find out running tomcat version

run on terminal of the Unix server

w3m http://localhost:8080/

to quit press q and next y

When to encode space to plus (+) or %20?

http://www.example.com/some/path/to/resource?param1=value1

The part before the question mark must use % encoding (so %20 for space), after the question mark you can use either %20 or + for a space. If you need an actual + after the question mark use %2B.

What is the use of BindingResult interface in spring MVC?

Basically BindingResult is an interface which dictates how the object that stores the result of validation should store and retrieve the result of the validation(errors, attempt to bind to disallowed fields etc)

From Spring MVC Form Validation with Annotations Tutorial:

[BindingResult] is Spring’s object that holds the result of the validation and binding and contains errors that may have occurred. The BindingResult must come right after the model object that is validated or else Spring will fail to validate the object and throw an exception.

When Spring sees @Valid, it tries to find the validator for the object being validated. Spring automatically picks up validation annotations if you have “annotation-driven” enabled. Spring then invokes the validator and puts any errors in the BindingResult and adds the BindingResult to the view model.

How to tell if a JavaScript function is defined

New to JavaScript I am not sure if the behaviour has changed but the solution given by Jason Bunting (6 years ago) won't work if possibleFunction is not defined.

function isFunction(possibleFunction) {
  return (typeof(possibleFunction) == typeof(Function));
}

This will throw a ReferenceError: possibleFunction is not defined error as the engine tries to resolve the symbol possibleFunction (as mentioned in the comments to Jason's answer)

To avoid this behaviour you can only pass the name of the function you want to check if it exists. So

var possibleFunction = possibleFunction || {};
if (!isFunction(possibleFunction)) return false;

This sets a variable to be either the function you want to check or the empty object if it is not defined and so avoids the issues mentioned above.

Node.js Error: connect ECONNREFUSED

I was having the same issue with ghost and heroku.

heroku config:set NODE_ENV=production 

solved it!

Check your config and env that the server is running on.

Change the encoding of a file in Visual Studio Code

Apart from the settings explained in the answer by @DarkNeuron:

"files.encoding": "any encoding"

you can also specify settings for a specific language like so:

"[language id]": {
  "files.encoding": "any encoding"
}

For example, I use this when I need to edit PowerShell files previously created with ISE (which are created in ANSI format):

"[powershell]": {
    "files.encoding": "windows1252"
}

You can get a list of identifiers of well-known languages here.

Get single listView SelectedItem

This works for single as well as multi selection list:

foreach (ListViewItem item in listView1.SelectedItems)
{
    int index = ListViewItem.Index;
    //index is now zero based index of selected item
}

Getting value from a cell from a gridview on RowDataBound event

I had a similar question, but found the solution through a slightly different approach. Instead of looking up the control as Chris suggested, I first changed the way the field was specified in the .aspx page. Instead of using a <asp:TemplateField ...> tag, I changed the field in question to use <asp:BoundField ...>. Then, when I got to the RowDataBound event, the data could be accessed in the cell directly.

The relevant fragments: First, the aspx page:

<asp:GridView ID="gvVarianceReport" runat="server" ... >
...Other fields...
    <asp:BoundField DataField="TotalExpected" 
     HeaderText="Total Expected <br />Filtration Events" 
     HtmlEncode="False" ItemStyle-HorizontalAlign="Left" 
     SortExpression="TotalExpected" />
...
</asp:Gridview>

Then in the RowDataBound event I can access the values directly:

protected void gvVarianceReport_Sorting(object sender, GridViewSortEventArgs e)
{
    if (e.Row.Cells[2].Text == "0")
    {
        e.Row.Cells[2].Text = "N/A";
        e.Row.Cells[3].Text = "N/A";
        e.Row.Cells[4].Text = "N/A";
    }
}

If someone could comment on why this works, I'd appreciate it. I don't fully understand why without the BoundField the value is not in the cell after the bind, but you have to look it up via the control.

Add single element to array in numpy

This command,

numpy.append(a, a[0])

does not alter a array. However, it returns a new modified array. So, if a modification is required, then the following must be used.

a = numpy.append(a, a[0])

PSEXEC, access denied errors

I just solved an identical symptom, by creating the registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system\LocalAccountTokenFilterPolicy and setting it to 1. More details are available here.

How to mock static methods in c# using MOQ framework?

Moq (and other DynamicProxy-based mocking frameworks) are unable to mock anything that is not a virtual or abstract method.

Sealed/static classes/methods can only be faked with Profiler API based tools, like Typemock (commercial) or Microsoft Moles (free, known as Fakes in Visual Studio 2012 Ultimate /2013 /2015).

Alternatively, you could refactor your design to abstract calls to static methods, and provide this abstraction to your class via dependency injection. Then you'd not only have a better design, it will be testable with free tools, like Moq.

A common pattern to allow testability can be applied without using any tools altogether. Consider the following method:

public class MyClass
{
    public string[] GetMyData(string fileName)
    {
        string[] data = FileUtil.ReadDataFromFile(fileName);
        return data;
    }
}

Instead of trying to mock FileUtil.ReadDataFromFile, you could wrap it in a protected virtual method, like this:

public class MyClass
{
    public string[] GetMyData(string fileName)
    {
        string[] data = GetDataFromFile(fileName);
        return data;
    }

    protected virtual string[] GetDataFromFile(string fileName)
    {
        return FileUtil.ReadDataFromFile(fileName);
    }
}

Then, in your unit test, derive from MyClass and call it TestableMyClass. Then you can override the GetDataFromFile method to return your own test data.

Hope that helps.

Localhost not working in chrome and firefox

For my project, I am set up to use https. I just got a new computer and cloned the project in git. The protocol and port number for the project are not saved in the solution file, so you have to make sure to set it again.

enter image description here

How to resolve ORA 00936 Missing Expression Error?

Remove the coma at the end of your SELECT statement (VALUE,), and also remove the one at the end of your FROM statement (rrf b,)

How to open SharePoint files in Chrome/Firefox

Thanks to @LyphTEC that gave a very interesting way to open an Office file in edit mode!

It gave me the idea to change the function _DispEx that is called when the user clicks on a file into a document library. By hacking the original function we can them be able to open a dialog (for Firefox/Chrome) and ask the user if he/she wants to readonly or edit the file: enter image description here

See below the JavaScript code I used. My code is for Excel files, but it could be modified to work with Word documents too:

    /**
 * fix problem with Excel documents on Firefox/Chrome (see https://blog.kodono.info/wordpress/2017/02/09/how-to-open-an-excel-document-from-sharepoint-files-into-chromefirefox-in-readonlyedit-mode/)
 * @param  {HTMLElement} p the <A> element
 * @param  {HTMLEvent} a the click event
 * @param  {Boolean} h TRUE
 * @param  {Boolean} e FALSE
 * @param  {Boolean} g FALSE
 * @param  {Strin} k the ActiveX command (e.g. "SharePoint.OpenDocuments.3")
 * @param  {Number} c 0
 * @param  {String} o the activeX command, here we look at "SharePoint.OpenDocuments"
 * @param  {String} m
 * @param  {String} b the replacement URL to the xslviewer
 */
var bak_DispEx;
var modalOpenDocument; // it will be use with the modal
SP.SOD.executeOrDelayUntilEventNotified(function() {
  bak_DispEx = _DispEx;
  _DispEx=function(p, a, h, e, g, k, c, o, m, b, j, l, i, f, d) {
    // if o==="SharePoint.OpenDocuments" && !IsClientAppInstalled(o)
    // in that case we want to open ask the user if he/she wants to readonly or edit the file
    var fileURL = b.replace(/.*_layouts\/xlviewer\.aspx\?id=(.*)/, "$1");
    if (o === "SharePoint.OpenDocuments" && !IsClientAppInstalled(o) && /\.xlsx?$/.test(fileURL)) {
      // if the URL doesn't start with http
      if (!/^http/.test(fileURL)) {
        fileURL = window.location.protocol + "//" + window.location.host + fileURL;
      }
      var ohtml = document.createElement('div');
      ohtml.style.padding = "10px";
      ohtml.style.display = "inline-block";
      ohtml.style.width = "200px";
      ohtml.style.width = "200px";
      ohtml.innerHTML = '<style>'
                      + '.opendocument_button { background-color:#fdfdfd; border:1px solid #ababab; color:#444; display:inline-block; padding: 7px 10px; }'
                      + '.opendocument_button:hover { box-shadow: none }'
                      + '#opendocument_readonly,#opendocument_edit { float:none; font-size: 100%; line-height: 1.15; margin: 0; overflow: visible; box-sizing: border-box; padding: 0; height:auto }'
                      + '.opendocument_ul { list-style-type:none;margin-top:10px;margin-bottom:10px;padding-top:0;padding-bottom:0 }'
                      + '</style>'
                      + 'You are about to open:'
                      + '<ul class="opendocument_ul">'
                      + '  <li>Name: <b>'+fileURL.split("/").slice(-1)+'</b></li>'
                      + '  <li>From: <b>'+window.location.hostname+'</b></li>'
                      + '</ul>'
                      + 'How would like to open this file?'
                      + '<ul class="opendocument_ul">'
                      + '  <li><label><input type="radio" name="opendocument_choices" id="opendocument_readonly" checked> Read Only</label></li>'
                      + '  <li><label><input type="radio" name="opendocument_choices" id="opendocument_edit"> Edit</label></li>'
                      + '</ul>'
                      + '<div style="text-align: center;margin-top: 20px;"><button type="button" class="opendocument_button" style="background-color: #2d9f2d;color: #fff;" onclick="modalOpenDocument.close(document.getElementById(\'opendocument_edit\').checked)">Open</button> <button type="button" class="opendocument_button" style="margin-left:10px" onclick="modalOpenDocument.close(-1)">Cancel</button></div>';
      // show the modal
      modalOpenDocument=SP.UI.ModalDialog.showModalDialog({
        html:ohtml,
        dialogReturnValueCallback:function(ret) {
          if (ret!==-1) {
            if (ret === true) { // edit
              // reformat the fileURL
              var ext;
              if (/\.xlsx?$/.test(b)) ext = "ms-excel";
              if (/\.docx?$/.test(b)) ext = "ms-word"; // not currently supported
              fileURL = ext + ":ofe|u|" + fileURL;
            }
            window.location.href = fileURL; // open the file
          }
        }
      });
      a.preventDefault();
      a.stopImmediatePropagation()
      a.cancelBubble = true;
      a.returnValue = false;
      return false;
    }
    return bak_DispEx.apply(this, arguments);
  }
}, "sp.scriptloaded-core.js")

I use SP.SOD.executeOrDelayUntilEventNotified to make sure the function will be executed when core.js is loaded.

HttpServlet cannot be resolved to a type .... is this a bug in eclipse?

It means that servlet jar is missing .

check the libraries for your project. Configure your buildpath download **

servlet-api.jar

** and import it in your project.

How to exclude property from Json Serialization

If you are using Json.Net attribute [JsonIgnore] will simply ignore the field/property while serializing or deserialising.

public class Car
{
  // included in JSON
  public string Model { get; set; }
  public DateTime Year { get; set; }
  public List<string> Features { get; set; }

  // ignored
  [JsonIgnore]
  public DateTime LastModified { get; set; }
}

Or you can use DataContract and DataMember attribute to selectively serialize/deserialize properties/fields.

[DataContract]
public class Computer
{
  // included in JSON
  [DataMember]
  public string Name { get; set; }
  [DataMember]
  public decimal SalePrice { get; set; }

  // ignored
  public string Manufacture { get; set; }
  public int StockCount { get; set; }
  public decimal WholeSalePrice { get; set; }
  public DateTime NextShipmentDate { get; set; }
}

Refer http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size for more details

get one item from an array of name,value JSON

Arrays are normally accessed via numeric indexes, so in your example arr[0] == {name:"k1", value:"abc"}. If you know that the name property of each object will be unique you can store them in an object instead of an array, as follows:

var obj = {};
obj["k1"] = "abc";
obj["k2"] = "hi";
obj["k3"] = "oa";

alert(obj["k2"]); // displays "hi"

If you actually want an array of objects like in your post you can loop through the array and return when you find an element with an object having the property you want:

function findElement(arr, propName, propValue) {
  for (var i=0; i < arr.length; i++)
    if (arr[i][propName] == propValue)
      return arr[i];

  // will return undefined if not found; you could return a default instead
}

// Using the array from the question
var x = findElement(arr, "name", "k2"); // x is {"name":"k2", "value":"hi"}
alert(x["value"]); // displays "hi"

var y = findElement(arr, "name", "k9"); // y is undefined
alert(y["value"]); // error because y is undefined

alert(findElement(arr, "name", "k2")["value"]); // displays "hi";

alert(findElement(arr, "name", "zzz")["value"]); // gives an error because the function returned undefined which won't have a "value" property

How to prevent going back to the previous activity?

I'm not sure exactly what you want, but it sounds like it should be possible, and it also sounds like you're already on the right track.

Here are a few links that might help:

Disable back button in android

  MyActivity.java =>
    @Override
    public void onBackPressed() {

       return;
    }

How can I disable 'go back' to some activity?

  AndroidManifest.xml =>
<activity android:name=".SplashActivity" android:noHistory="true"/>

Check if a string matches a regex in Bash script

Where the usage of a regex can be helpful to determine if the character sequence of a date is correct, it cannot be used easily to determine if the date is valid. The following examples will pass the regular expression, but are all invalid dates: 20180231, 20190229, 20190431

So if you want to validate if your date string (let's call it datestr) is in the correct format, it is best to parse it with date and ask date to convert the string to the correct format. If both strings are identical, you have a valid format and valid date.

if [[ "$datestr" == $(date -d "$datestr" "+%Y%m%d" 2>/dev/null) ]]; then
     echo "Valid date"
else
     echo "Invalid date"
fi

Fetch the row which has the Max value for a column

This will also take care of duplicates (return one row for each user_id):

SELECT *
FROM (
  SELECT u.*, FIRST_VALUE(u.rowid) OVER(PARTITION BY u.user_id ORDER BY u.date DESC) AS last_rowid
  FROM users u
) u2
WHERE u2.rowid = u2.last_rowid

How to load property file from classpath?

final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("foo.properties")) {
    properties.load(stream);
    /* or properties.loadFromXML(...) */
}

How do I prevent a parent's onclick event from firing when a child anchor is clicked?

Using return false; or e.stopPropogation(); will not allow further code to execute. It will stop flow at this point itself.

IE8 support for CSS Media Query

Edited answer: IE understands just screen and print as import media. All other CSS supplied along with the import statement causes IE8 to ignore the import statement. Geco browser like safari or mozilla didn't have this problem.

Is there a Python caching library?

Look at bda.cache http://pypi.python.org/pypi/bda.cache - uses ZCA and is tested with zope and bfg.

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

Use This This Will work For sure

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class ProtectedConfigFile {

    private static final char[] PASSWORD = "enfldsgbnlsngdlksdsgm".toCharArray();
    private static final byte[] SALT = { (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12, (byte) 0xde, (byte) 0x33,
            (byte) 0x10, (byte) 0x12, };

    public static void main(String[] args) throws Exception {
        String originalPassword = "Aman";
        System.out.println("Original password: " + originalPassword);
        String encryptedPassword = encrypt(originalPassword);
        System.out.println("Encrypted password: " + encryptedPassword);
        String decryptedPassword = decrypt(encryptedPassword);
        System.out.println("Decrypted password: " + decryptedPassword);
    }

    private static String encrypt(String property) throws GeneralSecurityException, UnsupportedEncodingException {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
        return base64Encode(pbeCipher.doFinal(property.getBytes("UTF-8")));
    }

    private static String base64Encode(byte[] bytes) {
        // NB: This class is internal, and you probably should use another impl
        return new BASE64Encoder().encode(bytes);
    }

    private static String decrypt(String property) throws GeneralSecurityException, IOException {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
        return new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
    }

    private static byte[] base64Decode(String property) throws IOException {
        // NB: This class is internal, and you probably should use another impl
        return new BASE64Decoder().decodeBuffer(property);
    }

}

Webdriver Screenshot

This will take screenshot and place it in a directory of a chosen name.

import os
driver.save_screenshot(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'NameOfScreenShotDirectory', 'PutFileNameHere'))

How to create localhost database using mysql?

See here for starting the service and here for how to make it permanent. In short to test it, open a "DOS" terminal with administrator privileges and write:

shell> "C:\Program Files\MySQL\[YOUR MYSQL VERSION PATH]\bin\mysqld"

How to kill a process running on particular port in Linux?

To know the pid of service running on particular port :

netstat -tulnap | grep :*port_num*

you will get the description of that process. Now use kill or kill -9 pid. Easily killed.

e.g

netstat -ap | grep :8080

tcp6       0      0 :::8080       :::*    LISTEN      1880/java 

Now:

kill -9 1880

Remember to run all commands as root

How to get the selected value from drop down list in jsp?

I've got one more additional option to get value by id:

var idElement = document.getElementById("idName");
var selectedValue = idElement.options[idElement.selectedIndex].value;

It's a simple JavaScript solution.

setTimeout in for-loop does not print consecutive values

You can use an immediately-invoked function expression (IIFE) to create a closure around setTimeout:

_x000D_
_x000D_
for (var i = 1; i <= 3; i++) {_x000D_
    (function(index) {_x000D_
        setTimeout(function() { alert(index); }, i * 1000);_x000D_
    })(i);_x000D_
}
_x000D_
_x000D_
_x000D_

C++ sorting and keeping track of indexes

Consider using std::multimap as suggested by @Ulrich Eckhardt. Just that the code could be made even simpler.

Given

std::vector<int> a = {5, 2, 1, 4, 3};  // a: 5 2 1 4 3

To sort in the mean time of insertion

std::multimap<int, std::size_t> mm;
for (std::size_t i = 0; i != a.size(); ++i)
    mm.insert({a[i], i});

To retrieve values and original indices

std::vector<int> b;
std::vector<std::size_t> c;
for (const auto & kv : mm) {
    b.push_back(kv.first);             // b: 1 2 3 4 5
    c.push_back(kv.second);            // c: 2 1 4 3 0
}

The reason to prefer a std::multimap to a std::map is to allow equal values in original vectors. Also please note that, unlike for std::map, operator[] is not defined for std::multimap.

Rounding a double value to x number of decimal places in swift

This is a sort of a long workaround, which may come in handy if your needs are a little more complex. You can use a number formatter in Swift.

let numberFormatter: NSNumberFormatter = {
    let nf = NSNumberFormatter()
    nf.numberStyle = .DecimalStyle
    nf.minimumFractionDigits = 0
    nf.maximumFractionDigits = 1
    return nf
}()

Suppose your variable you want to print is

var printVar = 3.567

This will make sure it is returned in the desired format:

numberFormatter.StringFromNumber(printVar)

The result here will thus be "3.6" (rounded). While this is not the most economic solution, I give it because the OP mentioned printing (in which case a String is not undesirable), and because this class allows for multiple parameters to be set.

Return sql rows where field contains ONLY non-alphanumeric characters

If you have short strings you should be able to create a few LIKE patterns ('[^a-zA-Z0-9]', '[^a-zA-Z0-9][^a-zA-Z0-9]', ...) to match strings of different length. Otherwise you should use CLR user defined function and a proper regular expression - Regular Expressions Make Pattern Matching And Data Extraction Easier.

Get the time of a datetime using T-SQL?

Assuming the title of your question is correct and you want the time:

SELECT CONVERT(char,GETDATE(),14) 

Edited to include millisecond.

can't access mysql from command line mac

Just do the following in your terminal:

echo $PATH

If your given path is not in that string, you have to add it like this: export PATH=$PATH:/usr/local/ or export PATH=$PATH:/usr/local/mysql/bin

C# Debug - cannot start debugging because the debug target is missing

Try these:

  1. Make sure that output path of project is correct (Project > Properties > Build > Output path)

  2. Go in menu to Build > Configuration Manager, and check if your main/entry project has checked Build. If not, check it.

Java: Reading a file into an array

You should be able to use forward slashes in Java to refer to file locations.

The BufferedReader class is used for wrapping other file readers whos read method may not be very efficient. A more detailed description can be found in the Java APIs.

Toolkit's use of BufferedReader is probably what you need.

How to select rows in a DataFrame between two values, in Python Pandas?

If one has to call pd.Series.between(l,r) repeatedly (for different bounds l and r), a lot of work is repeated unnecessarily. In this case, it's beneficial to sort the frame/series once and then use pd.Series.searchsorted(). I measured a speedup of up to 25x, see below.

def between_indices(x, lower, upper, inclusive=True):
    """
    Returns smallest and largest index i for which holds 
    lower <= x[i] <= upper, under the assumption that x is sorted.
    """
    i = x.searchsorted(lower, side="left" if inclusive else "right")
    j = x.searchsorted(upper, side="right" if inclusive else "left")
    return i, j

# Sort x once before repeated calls of between()
x = x.sort_values().reset_index(drop=True)
# x = x.sort_values(ignore_index=True) # for pandas>=1.0
ret1 = between_indices(x, lower=0.1, upper=0.9)
ret2 = between_indices(x, lower=0.2, upper=0.8)
ret3 = ...

Benchmark

Measure repeated evaluations (n_reps=100) of pd.Series.between() as well as the method based on pd.Series.searchsorted(), for different arguments lower and upper. On my MacBook Pro 2015 with Python v3.8.0 and Pandas v1.0.3, the below code results in the following outpu

# pd.Series.searchsorted()
# 5.87 ms ± 321 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# pd.Series.between(lower, upper)
# 155 ms ± 6.08 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# Logical expressions: (x>=lower) & (x<=upper)
# 153 ms ± 3.52 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
import numpy as np
import pandas as pd

def between_indices(x, lower, upper, inclusive=True):
    # Assumption: x is sorted.
    i = x.searchsorted(lower, side="left" if inclusive else "right")
    j = x.searchsorted(upper, side="right" if inclusive else "left")
    return i, j

def between_fast(x, lower, upper, inclusive=True):
    """
    Equivalent to pd.Series.between() under the assumption that x is sorted.
    """
    i, j = between_indices(x, lower, upper, inclusive)
    if True:
        return x.iloc[i:j]
    else:
        # Mask creation is slow.
        mask = np.zeros_like(x, dtype=bool)
        mask[i:j] = True
        mask = pd.Series(mask, index=x.index)
        return x[mask]

def between(x, lower, upper, inclusive=True):
    mask = x.between(lower, upper, inclusive=inclusive)
    return x[mask]

def between_expr(x, lower, upper, inclusive=True):
    if inclusive:
        mask = (x>=lower) & (x<=upper)
    else:
        mask = (x>lower) & (x<upper)
    return x[mask]

def benchmark(func, x, lowers, uppers):
    for l,u in zip(lowers, uppers):
        func(x,lower=l,upper=u)

n_samples = 1000
n_reps = 100
x = pd.Series(np.random.randn(n_samples))
# Sort the Series.
# For pandas>=1.0:
# x = x.sort_values(ignore_index=True)
x = x.sort_values().reset_index(drop=True)

# Assert equivalence of different methods.
assert(between_fast(x, 0, 1, True ).equals(between(x, 0, 1, True)))
assert(between_expr(x, 0, 1, True ).equals(between(x, 0, 1, True)))
assert(between_fast(x, 0, 1, False).equals(between(x, 0, 1, False)))
assert(between_expr(x, 0, 1, False).equals(between(x, 0, 1, False)))

# Benchmark repeated evaluations of between().
uppers = np.linspace(0, 3, n_reps)
lowers = -uppers
%timeit benchmark(between_fast, x, lowers, uppers)
%timeit benchmark(between, x, lowers, uppers)
%timeit benchmark(between_expr, x, lowers, uppers)

Subset of rows containing NA (missing) values in a chosen column of a data frame

Prints all the rows with NA data:

tmp <- data.frame(c(1,2,3),c(4,NA,5));
tmp[round(which(is.na(tmp))/ncol(tmp)),]

Jquery open popup on button click for bootstrap

Give an ID to uniquely identify the button, lets say myBtn

// when DOM is ready
$(document).ready(function () {

     // Attach Button click event listener 
    $("#myBtn").click(function(){

         // show Modal
         $('#myModal').modal('show');
    });
});

JSFIDDLE