Programs & Examples On #Dynamic ip

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

In Excel 2010 it is easy, just takes a few more steps for each list items.

The following steps must be completed for each item within the validation list. (Have the worksheet open to where the drop down was created)

1) Click on cell with drop down list.
2) Select which answer to apply format to.
3) Click on "Home" tab, then click the "Styles" tool button on the ribbon.
4) Click "Conditional Formatting", in drop down list click the "*New Rule" option.
5) Select a Rule Type: "Format only cells that contain"
6) Edit the Rule Description: "Cell Value", "equal to", click the cell formula icon in the formula bar (far right), select which worksheet the validation list was created in, select the cell within the list to which you wish to apply the formatting.

Formula should look something like: ='Workbook Data'!$A$2

7) Click the formula icon again to return to format menu.
8) Click on Format button beside preview pane.
9) Select all format options desired.
10) Press "OK" twice.

You are finished with only one item within list. Repeat steps 1 thru 10 until all drop down list items are finished.

Environ Function code samples for VBA

Environ() gets you the value of any environment variable. These can be found by doing the following command in the Command Prompt:

set

If you wanted to get the username, you would do:

Environ("username")

If you wanted to get the fully qualified name, you would do:

Environ("userdomain") & "\" & Environ("username")

References

installing requests module in python 2.7 windows

If you want to install requests directly you can use the "-m" (module) option available to python.

python.exe -m pip install requests

You can do this directly in PowerShell, though you may need to use the full python path (eg. C:\Python27\python.exe) instead of just python.exe.

As mentioned in the comments, if you have added Python to your path you can simply do:

python -m pip install requests

jQuery text() and newlines

Alternatively, try using .html and then wrap with <pre> tags:

$(someElem).html('this\n has\n newlines').wrap('<pre />');

HorizontalScrollView within ScrollView Touch Handling

Neevek's solution works better than Joel's on devices running 3.2 and above. There is a bug in Android that will cause java.lang.IllegalArgumentException: pointerIndex out of range if a gesture detector is used inside a scollview. To duplicate the issue, implement a custom scollview as Joel suggested and put a view pager inside. If you drag (don't lift you figure) to one direction (left/right) and then to the opposite, you will see the crash. Also in Joel's solution, if you drag the view pager by moving your finger diagonally, once your finger leave the view pager's content view area, the pager will spring back to its previous position. All these issues are more to do with Android's internal design or lack of it than Joel's implementation, which itself is a piece of smart and concise code.

http://code.google.com/p/android/issues/detail?id=18990

How to make a window always stay on top in .Net?

The following code makes the window always stay on top as well as make it frameless.

using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace StayOnTop
{
    public partial class Form1 : Form
    {
        private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
        private const UInt32 SWP_NOSIZE = 0x0001;
        private const UInt32 SWP_NOMOVE = 0x0002;
        private const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

        public Form1()
        {
            InitializeComponent();
            FormBorderStyle = FormBorderStyle.None;
            TopMost = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SetWindowPos(this.Handle, HWND_TOPMOST, 100, 100, 300, 300, TOPMOST_FLAGS);
        }

        protected override void WndProc(ref Message m)
        {
            const int RESIZE_HANDLE_SIZE = 10;

            switch (m.Msg)
            {
                case 0x0084/*NCHITTEST*/ :
                    base.WndProc(ref m);

                    if ((int)m.Result == 0x01/*HTCLIENT*/)
                    {
                        Point screenPoint = new Point(m.LParam.ToInt32());
                        Point clientPoint = this.PointToClient(screenPoint);
                        if (clientPoint.Y <= RESIZE_HANDLE_SIZE)
                        {
                            if (clientPoint.X <= RESIZE_HANDLE_SIZE)
                                m.Result = (IntPtr)13/*HTTOPLEFT*/ ;
                            else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE))
                                m.Result = (IntPtr)12/*HTTOP*/ ;
                            else
                                m.Result = (IntPtr)14/*HTTOPRIGHT*/ ;
                        }
                        else if (clientPoint.Y <= (Size.Height - RESIZE_HANDLE_SIZE))
                        {
                            if (clientPoint.X <= RESIZE_HANDLE_SIZE)
                                m.Result = (IntPtr)10/*HTLEFT*/ ;
                            else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE))
                                m.Result = (IntPtr)2/*HTCAPTION*/ ;
                            else
                                m.Result = (IntPtr)11/*HTRIGHT*/ ;
                        }
                        else
                        {
                            if (clientPoint.X <= RESIZE_HANDLE_SIZE)
                                m.Result = (IntPtr)16/*HTBOTTOMLEFT*/ ;
                            else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE))
                                m.Result = (IntPtr)15/*HTBOTTOM*/ ;
                            else
                                m.Result = (IntPtr)17/*HTBOTTOMRIGHT*/ ;
                        }
                    }
                    return;
            }
            base.WndProc(ref m);
        }

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.Style |= 0x20000; // <--- use 0x20000
                return cp;
            }
        }
    }
}

How to create a string with format?

The beauty of String(format:) is that you can save a formatting string and then reuse it later in dozen of places. It also can be localized in this single place. Where as in case of the interpolation approach you must write it again and again.

Disabling user input for UITextfield in swift

you can use UILabel instead if you don't want the user to be able to modify anything in your UITextField

A programmatic solution would be to use enabled property:

yourTextField.enabled = false

A way to do it in a storyboard:

Uncheck the Enabled checkbox in the properties of your UITextField

enter image description here

XPath Query: get attribute href from a tag

The answer shared by @mockinterface is correct. Although I would like to add my 2 cents to it.

If someone is using frameworks like scrapy the you will have to use /html/body//a[contains(@href,'com')][2]/@href along with get() like this:

response.xpath('//a[contains(@href,'com')][2]/@href').get()

Check if value exists in enum in TypeScript

This works only on non-const, number-based enums. For const enums or enums of other types, see this answer above


If you are using TypeScript, you can use an actual enum. Then you can check it using in.

export enum MESSAGE_TYPE {
    INFO = 1,
    SUCCESS = 2,
    WARNING = 3,
    ERROR = 4,
};

var type = 3;

if (type in MESSAGE_TYPE) {

}

This works because when you compile the above enum, it generates the below object:

{
    '1': 'INFO',
    '2': 'SUCCESS',
    '3': 'WARNING',
    '4': 'ERROR',
    INFO: 1,
    SUCCESS: 2,
    WARNING: 3,
    ERROR: 4
}

Netbeans - Error: Could not find or load main class

try this it work out for me perfectly go to project and right click on your java file at the right corner, go to properties, go to run, go to browse, and then select Main class. now you can run your program again.

getting exception "IllegalStateException: Can not perform this action after onSaveInstanceState"

You may be calling fragmentManager.popBackStackImmediate(); when activity is paused. Activity is not finished but is paused and not on foreground. You need to check whether activity is paused or not before popBackStackImmediate().

WCF named pipe minimal example

I created this simple example from different search results on the internet.

public static ServiceHost CreateServiceHost(Type serviceInterface, Type implementation)
{
  //Create base address
  string baseAddress = "net.pipe://localhost/MyService";

  ServiceHost serviceHost = new ServiceHost(implementation, new Uri(baseAddress));

  //Net named pipe
  NetNamedPipeBinding binding = new NetNamedPipeBinding { MaxReceivedMessageSize = 2147483647 };
  serviceHost.AddServiceEndpoint(serviceInterface, binding, baseAddress);

  //MEX - Meta data exchange
  ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
  serviceHost.Description.Behaviors.Add(behavior);
  serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexNamedPipeBinding(), baseAddress + "/mex/");

  return serviceHost;
}

Using the above URI I can add a reference in my client to the web service.

Sort Go map values by keys

According to the Go spec, the order of iteration over a map is undefined, and may vary between runs of the program. In practice, not only is it undefined, it's actually intentionally randomized. This is because it used to be predictable, and the Go language developers didn't want people relying on unspecified behavior, so they intentionally randomized it so that relying on this behavior was impossible.

What you'll have to do, then, is pull the keys into a slice, sort them, and then range over the slice like this:

var m map[keyType]valueType
keys := sliceOfKeys(m) // you'll have to implement this
for _, k := range keys {
    v := m[k]
    // k is the key and v is the value; do your computation here
}

How can I make a TextArea 100% width without overflowing when padding is present in CSS?

I often fix that problem with calc(). You just give the textarea a width of 100% and a certain amount of padding, but you have to subtract the total left and right padding of the 100% width you have given to the textarea:

textarea {
    border: 0px;
    width: calc(100% -10px);
    padding: 5px; 
}

Or if you want to give the textarea a border:

textarea {
    border: 1px;
    width: calc(100% -12px); /* plus the total left and right border */
    padding: 5px; 
}

Where are $_SESSION variables stored?

Many of the answers above are opaque. In my opinion the author of this question simply wants to know where session variables are stored by default. According to this:https://canvas.seattlecentral.edu/courses/937693/pages/10-advanced-php-sessions they are simply stored on the server by default. Hopefully, others will find this contribution meaningful.

pycharm running way slow

In my case, the problem was a folder in the project directory containing 300k+ files totaling 11Gb. This was just a temporary folder with images results of some computation. After moving this folder out of the project structure, the slowness disappeared. I hope this can help someone, please check your project structure to see if there is anything that is not necessary.

Difference between fprintf, printf and sprintf?

In C, a "stream" is an abstraction; from the program's perspective it is simply a producer (input stream) or consumer (output stream) of bytes. It can correspond to a file on disk, to a pipe, to your terminal, or to some other device such as a printer or tty. The FILE type contains information about the stream. Normally, you don't mess with a FILE object's contents directly, you just pass a pointer to it to the various I/O routines.

There are three standard streams: stdin is a pointer to the standard input stream, stdout is a pointer to the standard output stream, and stderr is a pointer to the standard error output stream. In an interactive session, the three usually refer to your console, although you can redirect them to point to other files or devices:

$ myprog < inputfile.dat > output.txt 2> errors.txt

In this example, stdin now points to inputfile.dat, stdout points to output.txt, and stderr points to errors.txt.

fprintf writes formatted text to the output stream you specify.

printf is equivalent to writing fprintf(stdout, ...) and writes formatted text to wherever the standard output stream is currently pointing.

sprintf writes formatted text to an array of char, as opposed to a stream.

The performance impact of using instanceof in Java

I write a performance test based on jmh-java-benchmark-archetype:2.21. JDK is openjdk and version is 1.8.0_212. The test machine is mac pro. Test result is:

Benchmark                Mode  Cnt    Score   Error   Units
MyBenchmark.getClasses  thrpt   30  510.818 ± 4.190  ops/us
MyBenchmark.instanceOf  thrpt   30  503.826 ± 5.546  ops/us

The result shows that: getClass is better than instanceOf, which is contrary with other test. However, I don't know why.

The test code is below:

public class MyBenchmark {

public static final Object a = new LinkedHashMap<String, String>();

@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public boolean instanceOf() {
    return a instanceof Map;
}

@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public boolean getClasses() {
    return a.getClass() == HashMap.class;
}

public static void main(String[] args) throws RunnerException {
    Options opt =
        new OptionsBuilder().include(MyBenchmark.class.getSimpleName()).warmupIterations(20).measurementIterations(30).forks(1).build();
    new Runner(opt).run();
}
}

Simple proof that GUID is not unique

Any two GUIDs are very likely unique (not equal).

See this SO entry, and from Wikipedia

While each generated GUID is not guaranteed to be unique, the total number of unique keys (2^128 or 3.4×10^38) is so large that the probability of the same number being generated twice is very small. For example, consider the observable universe, which contains about 5×10^22 stars; every star could then have 6.8×10^15 universally unique GUIDs.

So probably you have to wait for many more billion of years, and hope that you hit one before the universe as we know it comes to an end.

Format decimal for percentage values?

Use the P format string. This will vary by culture:

String.Format("Value: {0:P2}.", 0.8526) // formats as 85.26 % (varies by culture)

Drop primary key using script in SQL Server database

The answer I got is that variables and subqueries will not work and we have to user dynamic SQL script. The following works:

DECLARE @SQL VARCHAR(4000)
SET @SQL = 'ALTER TABLE dbo.Student DROP CONSTRAINT |ConstraintName| '

SET @SQL = REPLACE(@SQL, '|ConstraintName|', ( SELECT   name
                                               FROM     sysobjects
                                               WHERE    xtype = 'PK'
                                                        AND parent_obj =        OBJECT_ID('Student')))

EXEC (@SQL)

npm install doesn't create node_modules directory

my problem was to copy the whole source files contains .idea directory and my webstorm terminal commands were run on the original directory of the source
I delete the .idea directory and it worked fine

Recursively list all files in a directory including files in symlink directories

find -L /var/www/ -type l

# man find
-L     Follow  symbolic links.  When find examines or prints information about files, the information used shall be taken from the

properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the symbolic link will be searched.

Updating version numbers of modules in a multi-module Maven project

You may want to look into Maven release plugin's release:update-versions goal. It will update the parent's version as well as all the modules under it.


Update: Please note that the above is the release plugin. If you are not releasing, you may want to use versions:set

mvn versions:set -DnewVersion=1.2.3-SNAPSHOT

Converting a value to 2 decimal places within jQuery

Try to use this

parseFloat().toFixed(2)

The server encountered an internal error or misconfiguration and was unable to complete your request

You should look for the error in the file error_log in the log directory. Maybe there are differences between your local and server configuration (db user/password etc.etc.)

usually the log file is in

/var/log/apache2/error.log

or

/var/log/httpd/error.log

How do I fix a "Performance counter registry hive consistency" when installing SQL Server R2 Express?

open Command line and type lodctr /r The p. counter will be resotred\recreated.

There is no need to skip it. http://technet.microsoft.com/en-us/library/cc774958.aspx

Pressed <button> selector

You can do this if you use an <a> tag instead of a button. I know it's not exactly what you asked for, but it might give you some other options if you cannot find a solution to this:

Borrowing from a demo from another answer here I produced this:

_x000D_
_x000D_
a {_x000D_
  display: block;_x000D_
  font-size: 18px;_x000D_
  border: 2px solid gray;_x000D_
  border-radius: 100px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  text-align: center;_x000D_
  line-height: 100px;_x000D_
}_x000D_
_x000D_
a:active {_x000D_
  font-size: 18px;_x000D_
  border: 2px solid green;_x000D_
  border-radius: 100px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
a:target {_x000D_
  font-size: 18px;_x000D_
  border: 2px solid red;_x000D_
  border-radius: 100px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}
_x000D_
<a id="btn" href="#btn">Demo</a>
_x000D_
_x000D_
_x000D_

Notice the use of :target; this will be the style applied when the element is targeted via the hash. Which also means your HTML will need to be this: <a id="btn" href="#btn">Demo</a> a link targeting itself. and the demo http://jsfiddle.net/rlemon/Awdq5/4/

Thanks to @BenjaminGruenbaum here is a better demo: http://jsfiddle.net/agzVt/

Also, as a footnote: this should really be done with JavaScript and applying / removing CSS classes from the element. It would be much less convoluted.

Trusting all certificates with okHttp

You should never look to override certificate validation in code! If you need to do testing, use an internal/test CA and install the CA root certificate on the device or emulator. You can use BurpSuite or Charles Proxy if you don't know how to setup a CA.

How to change default format at created_at and updated_at value laravel

If anyone is looking for a simple solution in Laravel 5.3:

  1. Let default timestamps() be saved as is i.e. '2016-11-14 12:19:49'
  2. In your views, format the field as below (or as required):

    date('F d, Y', strtotime($list->created_at))
    

It worked for me very well for me.

How to uncheck a radio button?

$('input[id^="rad"]').dblclick(function(){
    var nombre = $(this).attr('id');
    var checked =  $(this).is(":checked") ;
    if(checked){
        $("input[id="+nombre+"]:radio").prop( "checked", false );
    }
});

Every time you have a double click in a checked radio the checked changes to false

My radios begin with id=radxxxxxxxx because I use this id selector.

How to extract a single value from JSON response?

Only suggestion is to access your resp_dict via .get() for a more graceful approach that will degrade well if the data isn't as expected.

resp_dict = json.loads(resp_str)
resp_dict.get('name') # will return None if 'name' doesn't exist

You could also add some logic to test for the key if you want as well.

if 'name' in resp_dict:
    resp_dict['name']
else:
    # do something else here.

How to hide image broken Icon using only CSS/HTML?

There is no way for CSS/HTML to know if the image is broken link, so you are going to have to use JavaScript no matter what

But here is a minimal method for either hiding the image, or replacing the source with a backup.

<img src="Error.src" onerror="this.style.display='none'"/>

or

<img src="Error.src" onerror="this.src='fallback-img.jpg'"/>

Update

You can apply this logic to multiple images at once by doing something like this:

_x000D_
_x000D_
document.addEventListener("DOMContentLoaded", function(event) {_x000D_
   document.querySelectorAll('img').forEach(function(img){_x000D_
   img.onerror = function(){this.style.display='none';};_x000D_
   })_x000D_
});
_x000D_
<img src="error.src">_x000D_
<img src="error.src">_x000D_
<img src="error.src">_x000D_
<img src="error.src">
_x000D_
_x000D_
_x000D_

Update 2

For a CSS option see michalzuber's answer below. You can't hide the entire image, but you change how the broken icon looks.

Algorithm to compare two images

It is indeed much less simple than it seems :-) Nick's suggestion is a good one.

To get started, keep in mind that any worthwhile comparison method will essentially work by converting the images into a different form -- a form which makes it easier to pick similar features out. Usually, this stuff doesn't make for very light reading ...


One of the simplest examples I can think of is simply using the color space of each image. If two images have highly similar color distributions, then you can be reasonably sure that they show the same thing. At least, you can have enough certainty to flag it, or do more testing. Comparing images in color space will also resist things such as rotation, scaling, and some cropping. It won't, of course, resist heavy modification of the image or heavy recoloring (and even a simple hue shift will be somewhat tricky).

http://en.wikipedia.org/wiki/RGB_color_space
http://upvector.com/index.php?section=tutorials&subsection=tutorials/colorspace


Another example involves something called the Hough Transform. This transform essentially decomposes an image into a set of lines. You can then take some of the 'strongest' lines in each image and see if they line up. You can do some extra work to try and compensate for rotation and scaling too -- and in this case, since comparing a few lines is MUCH less computational work than doing the same to entire images -- it won't be so bad.

http://homepages.inf.ed.ac.uk/amos/hough.html
http://rkb.home.cern.ch/rkb/AN16pp/node122.html
http://en.wikipedia.org/wiki/Hough_transform

is there a post render callback for Angular JS directive?

I had the same problem and I believe the answer really is no. See Miško's comment and some discussion in the group.

Angular can track that all of the function calls it makes to manipulate the DOM are complete, but since those functions could trigger async logic that's still updating the DOM after they return, Angular couldn't be expected to know about it. Any callback Angular gives might work sometimes, but wouldn't be safe to rely on.

We solved this heuristically with a setTimeout, as you did.

(Please keep in mind that not everyone agrees with me - you should read the comments on the links above and see what you think.)

pyplot scatter plot marker size

I also attempted to use 'scatter' initially for this purpose. After quite a bit of wasted time - I settled on the following solution.

import matplotlib.pyplot as plt
input_list = [{'x':100,'y':200,'radius':50, 'color':(0.1,0.2,0.3)}]    
output_list = []   
for point in input_list:
    output_list.append(plt.Circle((point['x'], point['y']), point['radius'], color=point['color'], fill=False))
ax = plt.gca(aspect='equal')
ax.cla()
ax.set_xlim((0, 1000))
ax.set_ylim((0, 1000))
for circle in output_list:    
   ax.add_artist(circle)

enter image description here

This is based on an answer to this question

use of entityManager.createNativeQuery(query,foo.class)

Suppose your query is "select id,name from users where rollNo = 1001".

Here query will return a object with id and name column. Your Response class is like bellow:

public class UserObject{
        int id;
        String name;
        String rollNo;

        public UserObject(Object[] columns) {
            this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
            this.name = (String) columns[1];
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getRollNo() {
            return rollNo;
        }

        public void setRollNo(String rollNo) {
            this.rollNo = rollNo;
        }
    }

here UserObject constructor will get a Object Array and set data with object.

public UserObject(Object[] columns) {
            this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
            this.name = (String) columns[1];
        }

Your query executing function is like bellow :

public UserObject getUserByRoll(EntityManager entityManager,String rollNo) {

        String queryStr = "select id,name from users where rollNo = ?1";
        try {
            Query query = entityManager.createNativeQuery(queryStr);
            query.setParameter(1, rollNo);

            return new UserObject((Object[]) query.getSingleResult());
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

Here you have to import bellow packages:

import javax.persistence.Query;
import javax.persistence.EntityManager;

Now your main class, you have to call this function. First you have to get EntityManager and call this getUserByRoll(EntityManager entityManager,String rollNo) function. Calling procedure is given bellow:

@PersistenceContext
private EntityManager entityManager;

UserObject userObject = getUserByRoll(entityManager,"1001");

Now you have data in this userObject.

Here is Imports

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

Note:

query.getSingleResult() return a array. You have to maintain the column position and data type.

select id,name from users where rollNo = ?1 

query return a array and it's [0] --> id and [1] -> name.

For more info, visit this Answer

Thanks :)

How do I parse JSON into an int?

Non of them worked for me. I did this and it worked:

To encode as a json:

JSONObject obj = new JSONObject();
obj.put("productId", 100);

To decode:

long temp = (Long) obj.get("productId");

How to invert a grep expression

Add the -v option to your grep command to invert the results.

How to speed up insertion performance in PostgreSQL

If you happend to insert colums with UUIDs (which is not exactly your case) and to add to @Dennis answer (I can't comment yet), be advise than using gen_random_uuid() (requires PG 9.4 and pgcrypto module) is (a lot) faster than uuid_generate_v4()

=# explain analyze select uuid_generate_v4(),* from generate_series(1,10000);
                                                        QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------
 Function Scan on generate_series  (cost=0.00..12.50 rows=1000 width=4) (actual time=11.674..10304.959 rows=10000 loops=1)
 Planning time: 0.157 ms
 Execution time: 13353.098 ms
(3 filas)

vs


=# explain analyze select gen_random_uuid(),* from generate_series(1,10000);
                                                        QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------
 Function Scan on generate_series  (cost=0.00..12.50 rows=1000 width=4) (actual time=252.274..418.137 rows=10000 loops=1)
 Planning time: 0.064 ms
 Execution time: 503.818 ms
(3 filas)

Also, it's the suggested official way to do it

Note

If you only need randomly-generated (version 4) UUIDs, consider using the gen_random_uuid() function from the pgcrypto module instead.

This droped insert time from ~2 hours to ~10 minutes for 3.7M of rows.

Run a Java Application as a Service on Linux

Referring to Spring Boot application as a Service as well, I would go for the systemd version, since it's the easiest, least verbose, and best integrated into modern distros (and even the not-so-modern ones like CentOS 7.x).

Tool for comparing 2 binary files in Windows

If you want to find out only whether or not the files are identical, you can use the Windows fc command in binary mode:

fc.exe /b file1 file2

For details, see the reference for fc

Sort JavaScript object by key

Here is a one line solution (not the most efficient but when it comes to thin objects like in your example I'd rather use native JS functions then messing up with sloppy loops)

_x000D_
_x000D_
const unordered = { 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' }

const ordered = Object.fromEntries(Object.entries(unordered).sort())

console.log(ordered); // a->b->c
_x000D_
_x000D_
_x000D_

When do you use Java's @Override annotation and why?

The best practive is to always use it (or have the IDE fill them for you)

@Override usefulness is to detect changes in parent classes which has not been reported down the hierarchy. Without it, you can change a method signature and forget to alter its overrides, with @Override, the compiler will catch it for you.

That kind of safety net is always good to have.

Python: Random numbers into a list

import random
my_randoms = [random.randrange(1, 101, 1) for _ in range(10)]

How to set a Default Route (To an Area) in MVC

ummm, I don't know why all this programming, I think the original problem is solved easily by specifying this default route ...

routes.MapRoute("Default", "{*id}", 
                 new { controller = "Home"
                     , action = "Index"
                     , id = UrlParameter.Optional 
                     }
              );

Random string generation with upper case letters and digits

I was looking at the different answers and took time to read the documentation of secrets

The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.

In particularly, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.

Looking more into what it has to offer I found a very handy function if you want to mimic an ID like Google Drive IDs:

secrets.token_urlsafe([nbytes=None])
Return a random URL-safe text string, containing nbytes random bytes. The text is Base64 encoded, so on average each byte results in approximately 1.3 characters. If nbytes is None or not supplied, a reasonable default is used.

Use it the following way:

import secrets
import math

def id_generator():
    id = secrets.token_urlsafe(math.floor(32 / 1.3))
    return id

print(id_generator())

Output a 32 characters length id:

joXR8dYbBDAHpVs5ci6iD-oIgPhkeQFk

I know this is slightly different from the OP's question but I expect that it would still be helpful to many who were looking for the same use-case that I was looking for.

What do the icons in Eclipse mean?

This is a fairly comprehensive list from the Eclipse documentation. If anyone knows of another list — maybe with more details, or just the most common icons — feel free to add it.

Latest: JDT Icons

2019-06: JDT Icons

2019-03: JDT Icons

2018-12: JDT Icons

2018-09: JDT Icons

Photon: JDT Icons

Oxygen: JDT Icons

Neon: JDT Icons

Mars: JDT Icons

Luna: JDT Icons

Kepler: JDT Icons

Juno: JDT Icons

Indigo: JDT Icons

Helios: JDT Icons

There are also some CDT icons at the bottom of this help page.

If you're a Subversion user, the icons you're looking for may actually belong to Subclipse; see this excellent answer for more on those.

SQL How to Select the most recent date item

Select * 
FROM test_table 
WHERE user_id = value 
AND date_added = (select max(date_added) 
   from test_table 
   where user_id = value)

MongoDb shuts down with Code 100

To run Mongo DB demon with mongod command, you should have a database directory, probably you need to run:

mkdir C:\data\db

Also, MongoDB need to have a write permissions for that directory or it should be run with superuser permissions, like sudo mongod.

javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher

The algorithm you are using, "AES", is a shorthand for "AES/ECB/NoPadding". What this means is that you are using the AES algorithm with 128-bit key size and block size, with the ECB mode of operation and no padding.

In other words: you are only able to encrypt data in blocks of 128 bits or 16 bytes. That's why you are getting that IllegalBlockSizeException exception.

If you want to encrypt data in sizes that are not multiple of 16 bytes, you are either going to have to use some kind of padding, or a cipher-stream. For instance, you could use CBC mode (a mode of operation that effectively transforms a block cipher into a stream cipher) by specifying "AES/CBC/NoPadding" as the algorithm, or PKCS5 padding by specifying "AES/ECB/PKCS5", which will automatically add some bytes at the end of your data in a very specific format to make the size of the ciphertext multiple of 16 bytes, and in a way that the decryption algorithm will understand that it has to ignore some data.

In any case, I strongly suggest that you stop right now what you are doing and go study some very introductory material on cryptography. For instance, check Crypto I on Coursera. You should understand very well the implications of choosing one mode or another, what are their strengths and, most importantly, their weaknesses. Without this knowledge, it is very easy to build systems which are very easy to break.


Update: based on your comments on the question, don't ever encrypt passwords when storing them at a database!!!!! You should never, ever do this. You must HASH the passwords, properly salted, which is completely different from encrypting. Really, please, don't do what you are trying to do... By encrypting the passwords, they can be decrypted. What this means is that you, as the database manager and who knows the secret key, you will be able to read every password stored in your database. Either you knew this and are doing something very, very bad, or you didn't know this, and should get shocked and stop it.

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

Passing data through intent using Serializable

I use the following method when sending a List<MySerializableObject> via intent:

List<Thumbnail> thumbList = new ArrayList<>();
//Populate ...

Intent intent = new Intent(context, OtherClass.class);
intent.putExtra("ThumbArray", thumbList.toArray(new Thumbnail[0]));
//Send intent...

And retrieving it like so:

Thumbnail[] thumbArr = (Thumbnail[]) getIntent().getSerializableExtra("ThumbArray");
if (thumbArr != null) {
    List<Thumbnail> thumbList = Arrays.asList(thumbArr);
}

Creating threads - Task.Factory.StartNew vs new Thread()

In the first case you are simply starting a new thread while in the second case you are entering in the thread pool.

The thread pool job is to share and recycle threads. It allows to avoid losing a few millisecond every time we need to create a new thread.

There are a several ways to enter the thread pool:

  • with the TPL (Task Parallel Library) like you did
  • by calling ThreadPool.QueueUserWorkItem
  • by calling BeginInvoke on a delegate
  • when you use a BackgroundWorker

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

As you can see here:

Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

Difference between @GetMapping & @RequestMapping

@GetMapping supports the consumes attribute like @RequestMapping.

Activate tabpage of TabControl

Use SelectTab like this:

TabPage t = tabControl1.TabPages[2];
tabControl1.SelectTab(t); //go to tab

Use SelectedTab like this:

TabPage t = tabControl1.TabPages[2];
tabControl1.SelectedTab = t; //go to tab

Select all from table with Laravel and Eloquent

This worked for me.

$posts = Blog::get()->all();

How to do paging in AngularJS?

I updated Scotty.NET's plunkr http://plnkr.co/edit/FUeWwDu0XzO51lyLAEIA?p=preview so that it uses newer versions of angular, angular-ui, and bootstrap.

Controller

var todos = angular.module('todos', ['ui.bootstrap']);

todos.controller('TodoController', function($scope) {
  $scope.filteredTodos = [];
  $scope.itemsPerPage = 30;
  $scope.currentPage = 4;

  $scope.makeTodos = function() {
    $scope.todos = [];
    for (i=1;i<=1000;i++) {
      $scope.todos.push({ text:'todo '+i, done:false});
    }
  };

  $scope.figureOutTodosToDisplay = function() {
    var begin = (($scope.currentPage - 1) * $scope.itemsPerPage);
    var end = begin + $scope.itemsPerPage;
    $scope.filteredTodos = $scope.todos.slice(begin, end);
  };

  $scope.makeTodos(); 
  $scope.figureOutTodosToDisplay();

  $scope.pageChanged = function() {
    $scope.figureOutTodosToDisplay();
  };

});

Bootstrap UI component

 <pagination boundary-links="true" 
    max-size="3" 
    items-per-page="itemsPerPage"
    total-items="todos.length" 
    ng-model="currentPage" 
    ng-change="pageChanged()"></pagination>

Access non-numeric Object properties by index?

The only way I can think of doing this is by creating a method that gives you the property using Object.keys();.

var obj = {
    dog: "woof",
    cat: "meow",
    key: function(n) {
        return this[Object.keys(this)[n]];
    }
};
obj.key(1); // "meow"

Demo: http://jsfiddle.net/UmkVn/

It would be possible to extend this to all objects using Object.prototype; but that isn't usually recommended.

Instead, use a function helper:

var object = {
  key: function(n) {
    return this[ Object.keys(this)[n] ];
  }
};

function key(obj, idx) {
  return object.key.call(obj, idx);
}

key({ a: 6 }, 0); // 6

Remove background drawable programmatically in Android

I try this code in android 4+:

view.setBackgroundDrawable(0);

SaveFileDialog setting default path and file type?

The SaveFileDialog control won't do any saving at all. All it does is providing you a convenient interface to actually display Windows' default file save dialog.

  1. Set the property InitialDirectory to the drive you'd like it to show some other default. Just think of other computers that might have a different layout. By default windows will save the directory used the last time and present it again.

  2. That is handled outside the control. You'll have to check the dialog's results and then do the saving yourself (e.g. write a text or binary file).

Just as a quick example (there are alternative ways to do it). savefile is a control of type SaveFileDialog

SaveFileDialog savefile = new SaveFileDialog(); 
// set a default file name
savefile.FileName = "unknown.txt";
// set filters - this can be done in properties as well
savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";

if (savefile.ShowDialog() == DialogResult.OK)
{
    using (StreamWriter sw = new StreamWriter(savefile.FileName))
        sw.WriteLine ("Hello World!");
}

Zip folder in C#

ComponentPro ZIP can help you achieve that task. The following code snippet compress files and dirs in a folder. You can use wilcard mask as well.

using ComponentPro.Compression;
using ComponentPro.IO;

...

// Create a new instance.
Zip zip = new Zip();
// Create a new zip file.
zip.Create("test.zip");

zip.Add(@"D:\Temp\Abc"); // Add entire D:\Temp\Abc folder to the archive.

// Add all files and subdirectories from 'c:\test' to the archive.
zip.AddFiles(@"c:\test");
// Add all files and subdirectories from 'c:\my folder' to the archive.
zip.AddFiles(@"c:\my folder", "");
// Add all files and subdirectories from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2", "22");
// Add all .dat files from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2", "22", "*.dat");
// Or simply use this to add all .dat files from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2\*.dat", "22");
// Add *.dat and *.exe files from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2\*.dat;*.exe", "22");

TransferOptions opt = new TransferOptions();
// Donot add empty directories.
opt.CreateEmptyDirectories = false;
zip.AddFiles(@"c:\abc", "/", opt);

// Close the zip file.
zip.Close();

http://www.componentpro.com/doc/zip has more examples

how can I copy a conditional formatting in Excel 2010 to other cells, which is based on a other cells content?

I ran into the same situation where when I copied the formula to another cell the formula was still referencing the cell used in the first formula. To correct this when you set up the rules, select the option "use a formula to determine which cells to format. Then type in the box your formula, for example H23*.25. When you copy the cells down the formulas will change to H24*.25, H25*.25 and so on. Hope this helps.

ng if with angular for string contains

All javascript methods are applicable with angularjs because angularjs itself is a javascript framework so you can use indexOf() inside angular directives

<li ng-repeat="select in Items">   
         <foo ng-repeat="newin select.values">
<span ng-if="newin.label.indexOf(x) !== -1">{{newin.label}}</span></foo>
</li>
//where x is your character to be found

How to unmount a busy device

Multiple mounts inside a folder

An additional reason could be a secondary mount inside your primary mount folder, e.g. after you worked on an SD card for an embedded device:

# mount /dev/sdb2 /mnt       # root partition which contains /boot
# mount /dev/sdb1 /mnt/boot  # boot partition

Unmounting /mnt will fail:

# umount /mnt
umount: /mnt: target is busy.

First we have to unmount the boot folder and then the root:

# umount /mnt/boot
# umount /mnt

Basic authentication for REST API using spring restTemplate

Taken from the example on this site, I think this would be the most natural way of doing it, by filling in the header value and passing the header to the template.

This is to fill in the header Authorization:

String plainCreds = "willie:p@ssword";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);

HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);

And this is to pass the header to the REST template:

HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<Account> response = restTemplate.exchange(url, HttpMethod.GET, request, Account.class);
Account account = response.getBody();

Getting only response header from HTTP POST using curl

-D, --dump-header <file>
       Write the protocol headers to the specified file.

       This  option  is handy to use when you want to store the headers
       that a HTTP site sends to you. Cookies from  the  headers  could
       then  be  read  in  a  second  curl  invocation by using the -b,
       --cookie option! The -c, --cookie-jar option is however a better
       way to store cookies.

and

-S, --show-error
       When used with -s, --silent, it makes curl show an error message if it fails.

and

-L/--location
      (HTTP/HTTPS) If the server reports that the requested page has moved to a different location (indicated with a Location: header and a 3XX response
      code), this option will make curl redo the request on the new place. If used together with -i/--include or -I/--head, headers from  all  requested
      pages  will  be  shown.  When authentication is used, curl only sends its credentials to the initial host. If a redirect takes curl to a different
      host, it won’t be able to intercept the user+password. See also --location-trusted on how to change this. You can limit the amount of redirects to
      follow by using the --max-redirs option.

      When curl follows a redirect and the request is not a plain GET (for example POST or PUT), it will do the following request with a GET if the HTTP
      response was 301, 302, or 303. If the response code was any other 3xx code, curl will re-send the following  request  using  the  same  unmodified
      method.

from the man page. so

curl -sSL -D - www.acooke.org -o /dev/null

follows redirects, dumps the headers to stdout and sends the data to /dev/null (that's a GET, not a POST, but you can do the same thing with a POST - just add whatever option you're already using for POSTing data)

note the - after the -D which indicates that the output "file" is stdout.

How to center buttons in Twitter Bootstrap 3?

It works for me try to make an independent <div>then put the button into that. just like this :

<div id="contactBtn">
            <button type="submit" class="btn btn-primary ">Send</button>
</div>

Then Go to to your CSSStyle page and do the Text-align:center like this :

#contactBtn{text-align: center;}

Where does PostgreSQL store the database?

Postgres stores data in files in its data directory. Follow the steps below to go to a database and its files:

The database corresponding to a postgresql table file is a directory. The location of the entire data directory can be obtained by running SHOW data_directory. in a UNIX like OS (eg: Mac) /Library/PostgreSQL/9.4/data Go inside the base folder in the data directory which has all the database folders: /Library/PostgreSQL/9.4/data/base

Find the database folder name by running (Gives an integer. This is the database folder name):

SELECT oid from pg_database WHERE datname = <database_name>;

Find the table file name by running (Gives an integer. This is the file name):

SELECT relname, relfilenode FROM pg_class WHERE relname = <table_name>; 

This is a binary file. File details such as size and creation date time can be obtained as usual. For more info read this SO thread

Shell command to sum integers, one per line?

perl -lne '$x += $_; END { print $x; }' < infile.txt

Check if an excel cell exists on another worksheet in a column - and return the contents of a different column

You can use following formulas.

For Excel 2007 or later:

=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")

For Excel 2003:

=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))

Note, that

  • I'm using List!A:C in VLOOKUP and returns value from column ? 3
  • I'm using 4th argument for VLOOKUP equals to FALSE, in that case VLOOKUP will only find an exact match, and the values in the first column of List!A:C do not need to be sorted (opposite to case when you're using TRUE).

How get data from material-ui TextField, DropDownMenu components?

In 2020 for TextField, via functional components:

const Content = () => {
   ... 
      const textFieldRef = useRef();

      const readTextFieldValue = () => {
        console.log(textFieldRef.current.value)
      }
   ...
  
      return(
       ...
       <TextField
        id="myTextField"
        label="Text Field"
        variant="outlined"
        inputRef={textFieldRef}
       />
       ...
      )

}

Note that this isn't complete code.

How to install Ruby 2.1.4 on Ubuntu 14.04

There is a PPA with up-to-date versions of Ruby 2.x for Ubuntu 12.04+:

$ sudo apt-add-repository ppa:brightbox/ruby-ng
$ sudo apt-get update
$ sudo apt-get install ruby2.4

$ ruby -v
ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux-gnu]

How to avoid using Select in Excel VBA

These methods are rather stigmatized, so taking the lead of Vityata and Jeeped for the sake of drawing a line in the sand:

Call .Activate, .Select, Selection, ActiveSomething methods/properties

Basically because they're called primarily to handle user input through the application UI. Since they're the methods called when the user handles objects through the UI, they're the ones recorded by the macro-recorder, and that's why calling them is either brittle or redundant for most situations: you don't have to select an object so as to perform an action with Selection right afterwards.

However, this definition settles situations on which they are called for:

When to call .Activate, .Select, .Selection, .ActiveSomething methods/properties

Basically when you expect the final user to play a role in the execution.

If you are developing and expect the user to choose the object instances for your code to handle, then .Selection or .ActiveObject are apropriate.

On the other hand, .Select and .Activate are of use when you can infer the user's next action and you want your code to guide the user, possibly saving him/her some time and mouse clicks. For example, if your code just created a brand new instance of a chart or updated one, the user might want to check it out, and you could call .Activate on it or its sheet to save the user the time searching for it; or if you know the user will need to update some range values, you can programmatically select that range.

How to position absolute inside a div?

The absolute divs are taken out of the flow of the document so the containing div does not have any content except for the padding. Give #box a height to fill it out.

#box {
    background-color: #000;
    position: relative;
    padding: 10px;
    width: 220px;
    height:30px;
}

Plotting a list of (x, y) coordinates in python matplotlib

If you have a numpy array you can do this:

import numpy as np
from matplotlib import pyplot as plt

data = np.array([
    [1, 2],
    [2, 3],
    [3, 6],
])
x, y = data.T
plt.scatter(x,y)
plt.show()

What are .dex files in Android?

.dex file

Compiled Android application code file.

Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created automatically by Android, by translating the compiled applications written in the Java programming language.

How to avoid mysql 'Deadlock found when trying to get lock; try restarting transaction'

For Java programmers using Spring, I've avoided this problem using an AOP aspect that automatically retries transactions that run into transient deadlocks.

See @RetryTransaction Javadoc for more info.

Importing data from a JSON file into R

packages:

  • library(httr)
  • library(jsonlite)

I have had issues converting json to dataframe/csv. For my case I did:

Token <- "245432532532"
source <- "http://......."
header_type <- "applcation/json"
full_token <- paste0("Bearer ", Token)
response <- GET(n_source, add_headers(Authorization = full_token, Accept = h_type), timeout(120), verbose())
text_json <- content(response, type = 'text', encoding = "UTF-8")
jfile <- fromJSON(text_json)
df <- as.data.frame(jfile)

then from df to csv.

In this format it should be easy to convert it to multiple .csvs if needed.

The important part is content function should have type = 'text'.

Compare two objects with .equals() and == operator

Your implementation must like:

public boolean equals2(Object object2) {
    if(a.equals(object2.a)) {
        return true;
    }
    else return false;
}

With this implementation your both methods would work.

Bootstrap 3 Slide in Menu / Navbar on Mobile

Bootstrap 4

Create a responsive navbar sidebar "drawer" in Bootstrap 4?
Bootstrap horizontal menu collapse to sidemenu

Bootstrap 3

I think what you're looking for is generally known as an "off-canvas" layout. Here is the standard off-canvas example from the official Bootstrap docs: http://getbootstrap.com/examples/offcanvas/

The "official" example uses a right-side sidebar the toggle off and on separately from the top navbar menu. I also found these off-canvas variations that slide in from the left and may be closer to what you're looking for..

http://www.bootstrapzero.com/bootstrap-template/off-canvas-sidebar http://www.bootstrapzero.com/bootstrap-template/facebook

How to see top processes sorted by actual memory usage?

First, repeat this mantra for a little while: "unused memory is wasted memory". The Linux kernel keeps around huge amounts of file metadata and files that were requested, until something that looks more important pushes that data out. It's why you can run:

find /home -type f -name '*.mp3'
find /home -type f -name '*.aac'

and have the second find instance run at ridiculous speed.

Linux only leaves a little bit of memory 'free' to handle spikes in memory usage without too much effort.

Second, you want to find the processes that are eating all your memory; in top use the M command to sort by memory use. Feel free to ignore the VIRT column, that just tells you how much virtual memory has been allocated, not how much memory the process is using. RES reports how much memory is resident, or currently in ram (as opposed to swapped to disk or never actually allocated in the first place, despite being requested).

But, since RES will count e.g. /lib/libc.so.6 memory once for nearly every process, it isn't exactly an awesome measure of how much memory a process is using. The SHR column reports how much memory is shared with other processes, but there is no guarantee that another process is actually sharing -- it could be sharable, just no one else wants to share.

The smem tool is designed to help users better gage just how much memory should really be blamed on each individual process. It does some clever work to figure out what is really unique, what is shared, and proportionally tallies the shared memory to the processes sharing it. smem may help you understand where your memory is going better than top will, but top is an excellent first tool.

Bootstrap 3 Glyphicons CDN

Although Bootstrap CDN restored glyphicons to bootstrap.min.css, Bootstrap CDN's Bootswatch css files doesn't include glyphicons.

For example Amelia theme: http://bootswatch.com/amelia/

Default Amelia has glyphicons in this file: http://bootswatch.com/amelia/bootstrap.min.css

But Bootstrap CDN's css file doesn't include glyphicons: http://netdna.bootstrapcdn.com/bootswatch/3.0.0/amelia/bootstrap.min.css

So as @edsioufi mentioned, you should include you should include glphicons css, if you use Bootswatch files from the bootstrap CDN. File: http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css

Use JAXB to create Object from XML String

Or if you want a simple one-liner:

Person person = JAXB.unmarshal(new StringReader("<?xml ..."), Person.class);

What is the "Upgrade-Insecure-Requests" HTTP header?

This explains the whole thing:

The HTTP Content-Security-Policy (CSP) upgrade-insecure-requests directive instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for web sites with large numbers of insecure legacy URLs that need to be rewritten.

The upgrade-insecure-requests directive is evaluated before block-all-mixed-content and if it is set, the latter is effectively a no-op. It is recommended to set one directive or the other, but not both.

The upgrade-insecure-requests directive will not ensure that users visiting your site via links on third-party sites will be upgraded to HTTPS for the top-level navigation and thus does not replace the Strict-Transport-Security (HSTS) header, which should still be set with an appropriate max-age to ensure that users are not subject to SSL stripping attacks.

Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests

How to get access to raw resources that I put in res folder?

An advance approach is using Kotlin Extension function

fun Context.getRawInput(@RawRes resourceId: Int): InputStream {
    return resources.openRawResource(resourceId)
}

One more interesting thing is extension function use that is defined in Closeable scope

For example you can work with input stream in elegant way without handling Exceptions and memory managing

fun Context.readRaw(@RawRes resourceId: Int): String {
    return resources.openRawResource(resourceId).bufferedReader(Charsets.UTF_8).use { it.readText() }
}

Why does jQuery or a DOM method such as getElementById not find the element?

When I tried your code, it worked.

The only reason that your event is not working, may be that your DOM was not ready and your button with id "event-btn" was not yet ready. And your javascript got executed and tried to bind the event with that element.

Before using the DOM element for binding, that element should be ready. There are many options to do that.

Option1: You can move your event binding code within document ready event. Like:

document.addEventListener('DOMContentLoaded', (event) => {
  //your code to bind the event
});

Option2: You can use timeout event, so that binding is delayed for few seconds. like:

setTimeout(function(){
  //your code to bind the event
}, 500);

Option3: move your javascript include to the bottom of your page.

I hope this helps you.

How to enable CORS in ASP.NET Core

Step 1: We need Microsoft.AspNetCore.Cors package in our project. For installing go to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution. Search for Microsoft.AspNetCore.Cors and install the package.

Step 2: We need to inject CORS into the container so that it can be used by the application. In Startup.cs class, let’s go to the ConfigureServices method and register CORS.

enter image description here

So, in our server app, let’s go to Controllers -> HomeController.cs and add the EnableCors decorator to the Index method (Or your specific controller and action):

enter image description here

For More Detail Click Here

How to check for an empty struct?

Using reflect.deepEqual also works, especially when you have map inside the struct

package main

import "fmt"
import "time"
import "reflect"

type Session struct {
    playerId string
    beehive string
    timestamp time.Time
}

func (s Session) IsEmpty() bool {
  return reflect.DeepEqual(s,Session{})
}

func main() {
  x := Session{}
  if x.IsEmpty() {
    fmt.Print("is empty")
  } 
}

docker command not found even though installed with apt-get

sudo apt-get install docker # DO NOT do this

is a different library on ubuntu.

Use sudo apt-get install docker-ce to install the correct docker.

Relative path to absolute path in C#?

This worked.

var s = Path.Combine(@"C:\some\location", @"..\other\file.txt");
s = Path.GetFullPath(s);

Substring in VBA

Shorter:

   Split(stringval,":")(0)

How to mark-up phone numbers?

Using jQuery, replace all US telephone numbers on the page with the appropriate callto: or tel: schemes.

// create a hidden iframe to receive failed schemes
$('body').append('<iframe name="blackhole" style="display:none"></iframe>');

// decide which scheme to use
var scheme = (navigator.userAgent.match(/mobile/gi) ? 'tel:' : 'callto:');

// replace all on the page
$('article').each(function (i, article) {
    findAndReplaceDOMText(article, {
        find:/\b(\d\d\d-\d\d\d-\d\d\d\d)\b/g,
        replace:function (portion) {
            var a = document.createElement('a');
            a.className = 'telephone';
            a.href = scheme + portion.text.replace(/\D/g, '');
            a.textContent = portion.text;
            a.target = 'blackhole';
            return a;
        }
    });
});

Thanks to @jonas_jonas for the idea. Requires the excellent findAndReplaceDOMText function.

proper name for python * operator?

I call *args "star args" or "varargs" and **kwargs "keyword args".

Exporting result of select statement to CSV format in DB2

According to the docs, you want to export of type del (the default delimiter looks like a comma, which is what you want). See the doc page for more information on the EXPORT command.

Java Error: illegal start of expression

public static int [] locations={1,2,3};

public static test dot=new test();

Declare the above variables above the main method and the code compiles fine.

public static void main(String[] args){

Implementing a Custom Error page on an ASP.Net website

There are 2 ways to configure custom error pages for ASP.NET sites:

  1. Internet Information Services (IIS) Manager (the GUI)
  2. web.config file

This article explains how to do each:

The reason your error.aspx page is not displaying might be because you have an error in your web.config. Try this instead:

<configuration>
   <system.web>
      <customErrors defaultRedirect="error.aspx" mode="RemoteOnly">
         <error statusCode="404" redirect="error.aspx"/>
      </customErrors>
   </system.web>
</configuration>

You might need to make sure that Error Pages in IIS Manager - Feature Delegation is set to Read/Write:

IIS Manager: Feature Delegation panel

Also, this answer may help you configure the web.config file:

How do I convert a javascript object array to a string array of the object attribute I want?

You can use this function:

function createStringArray(arr, prop) {
   var result = [];
   for (var i = 0; i < arr.length; i += 1) {
      result.push(arr[i][prop]);
   }
   return result;
}

Just pass the array of objects and the property you need. The script above will work even in old EcmaScript implementations.

How to check if any value is NaN in a Pandas DataFrame

Here is another interesting way of finding null and replacing with a calculated value

    #Creating the DataFrame

    testdf = pd.DataFrame({'Tenure':[1,2,3,4,5],'Monthly':[10,20,30,40,50],'Yearly':[10,40,np.nan,np.nan,250]})
    >>> testdf2
       Monthly  Tenure  Yearly
    0       10       1    10.0
    1       20       2    40.0
    2       30       3     NaN
    3       40       4     NaN
    4       50       5   250.0

    #Identifying the rows with empty columns
    nan_rows = testdf2[testdf2['Yearly'].isnull()]
    >>> nan_rows
       Monthly  Tenure  Yearly
    2       30       3     NaN
    3       40       4     NaN

    #Getting the rows# into a list
    >>> index = list(nan_rows.index)
    >>> index
    [2, 3]

    # Replacing null values with calculated value
    >>> for i in index:
        testdf2['Yearly'][i] = testdf2['Monthly'][i] * testdf2['Tenure'][i]
    >>> testdf2
       Monthly  Tenure  Yearly
    0       10       1    10.0
    1       20       2    40.0
    2       30       3    90.0
    3       40       4   160.0
    4       50       5   250.0

Javascript array declaration: new Array(), new Array(3), ['a', 'b', 'c'] create arrays that behave differently

Arrays in JS have two types of properties:

Regular elements and associative properties (which are nothing but objects)

When you define a = new Array(), you are defining an empty array. Note that there are no associative objects yet

When you define b = new Array(2), you are defining an array with two undefined locations.

In both your examples of 'a' and 'b', you are adding associative properties i.e. objects to these arrays.

console.log (a) or console.log(b) prints the array elements i.e. [] and [undefined, undefined] respectively. But since a1/a2 and b1/b2 are associative objects inside their arrays, they can be logged only by console.log(a.a1, a.a2) kind of syntax

The entity name must immediately follow the '&' in the entity reference

You need to add a CDATA tag inside of the script tag, unless you want to manually go through and escape all XHTML characters (e.g. & would need to become &amp;). For example:

<script>
//<![CDATA[
var el = document.getElementById("pacman");

if (Modernizr.canvas && Modernizr.localstorage && 
    Modernizr.audio && (Modernizr.audio.ogg || Modernizr.audio.mp3)) {
  window.setTimeout(function () { PACMAN.init(el, "./"); }, 0);
} else { 
  el.innerHTML = "Sorry, needs a decent browser<br /><small>" + 
    "(firefox 3.6+, Chrome 4+, Opera 10+ and Safari 4+)</small>";
}
//]]>
</script>

Call a function from another file?

If your file is in the different package structure and you want to call it from a different package, then you can call it in that fashion:

Let's say you have following package structure in your python project:

Python package and file structure

in - com.my.func.DifferentFunction python file you have some function, like:

def add(arg1, arg2):
    return arg1 + arg2

def sub(arg1, arg2) :
    return arg1 - arg2

def mul(arg1, arg2) :
    return arg1 * arg2

And you want to call different functions from Example3.py, then following way you can do it:

Define import statement in Example3.py - file for import all function

from com.my.func.DifferentFunction import *

or define each function name which you want to import

from com.my.func.DifferentFunction import add, sub, mul

Then in Example3.py you can call function for execute:

num1 = 20
num2 = 10

print("\n add : ", add(num1,num2))
print("\n sub : ", sub(num1,num2))
print("\n mul : ", mul(num1,num2))

Output:

 add :  30

 sub :  10

 mul :  200

Convert PDF to image with high resolution

Personally I like this.

convert -density 300 -trim test.pdf -quality 100 test.jpg

It's a little over twice the file size, but it looks better to me.

-density 300 sets the dpi that the PDF is rendered at.

-trim removes any edge pixels that are the same color as the corner pixels.

-quality 100 sets the JPEG compression quality to the highest quality.

Things like -sharpen don't work well with text because they undo things your font rendering system did to make it more legible.

If you actually want it blown up use resize here and possibly a larger dpi value of something like targetDPI * scalingFactor That will render the PDF at the resolution/size you intend.

Descriptions of the parameters on imagemagick.org are here

How to use class from other files in C# with visual studio?

According to your explanation you haven't included your Class2.cs in your project. You have just created the required Class file but haven't included that in the project.

The Class2.cs was created with [File] -> [New] -> [File] -> [C# class] and saved in the same folder where program.cs lives.

Do the following to overcome this,

Simply Right click on your project then -> [Add] - > [Existing Item...] : Select Class2.cs and press OK

Problem should be solved now.

Furthermore, when adding new classes use this procedure,

Right click on project -> [Add] -> Select Required Item (ex - A class, Form etc.)

Is Xamarin free in Visual Studio 2015?

If you go to the visualstudio.com Visual Studio 2015 RC cross-platform and mobile apps page, then read and scroll to the bottom, it appears that Microsoft is including Xamarin, and upon installing it you do have, as James said, the Xamarin Starter edition. In 2015 RC go to Tools, Xamarin Account to see your Xamarin license. I do not know the limitations, or any expiration date, of this Starter Xamarin Account.

Still, I don't know about you, but the Visual Studio 2015 RC "Community" edition I installed expires in less than 180 days. (Check the Help menu, go to "About...", and click on your license status to check.)

Let's say Xamarin Starter edition is free, but Visual Studio 2015 "Community" has an expiration date. So the bigger question might be whether Visual Studio 2015 "Community" will be free.

Without Xamarin though, Microsoft is offering C++ tools for cross-platform development, but scroll down to the bottom of the page and you might be surprised or confused at the download link description.

Pass entire form as data in jQuery Ajax function

In general use serialize() on the form element.

Please be mindful that multiple <select> options are serialized under the same key, e.g.

<select id="foo" name="foo" multiple="multiple">
    <option value="1">one</option>
    <option value="2">two</option>
    <option value="3">three</option>
</select>

will result in a query string that includes multiple occurences of the same query parameter:

[path]?foo=1&foo=2&foo=3&someotherparams...

which may not be what you want in the backend.

I use this JS code to reduce multiple parameters to a comma-separated single key (shamelessly copied from a commenter's response in a thread over at John Resig's place):

function compress(data) {
    data = data.replace(/([^&=]+=)([^&]*)(.*?)&\1([^&]*)/g, "$1$2,$4$3");
    return /([^&=]+=).*?&\1/.test(data) ? compress(data) : data;
}

which turns the above into:

[path]?foo=1,2,3&someotherparams...

In your JS code you'd call it like this:

var inputs = compress($("#your-form").serialize());

Hope that helps.

Node.js check if path is file or directory

Here's a function that I use. Nobody is making use of promisify and await/async feature in this post so I thought I would share.

const promisify = require('util').promisify;
const lstat = promisify(require('fs').lstat);

async function isDirectory (path) {
  try {
    return (await lstat(path)).isDirectory();
  }
  catch (e) {
    return false;
  }
}

Note : I don't use require('fs').promises; because it has been experimental for one year now, better not rely on it.

Get table column names in MySQL?

The easy way, if loading results using assoc is to do this:

$sql = "SELECT p.* FROM (SELECT 1) as dummy LEFT JOIN `product_table` p on null";
$q = $this->db->query($sql);
$column_names = array_keys($q->row);

This you load a single result using this query, you get an array with the table column names as keys and null as value. E.g.

Array(
'product_id' => null,
'sku' => null,
'price' => null,
...
)

after which you can easily get the table column names using the php function array_keys($result)

if statement checks for null but still throws a NullPointerException

Change Below line

if (str == null | str.length() == 0) {

into

if (str == null || str.isEmpty()) {

now your code will run corectlly. Make sure str.isEmpty() comes after str == null because calling isEmpty() on null will cause NullPointerException. Because of Java uses Short-circuit evaluation when str == null is true it will not evaluate str.isEmpty()

How do I get a file extension in PHP?

Use

str_replace('.', '', strrchr($file_name, '.'))

for a quick extension retrieval (if you know for sure your file name has one).

What's the Use of '\r' escape sequence?

\r move the cursor to the begin of the line.

Line breaks are managed differently on different systems. Some only use \n (line feed, e.g. Unix), some use (\r e.g. MacOS before OS X afaik) and some use \r\n (e.g. Windows afaik).

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

Make sure file name "Dockerfile" is not saved with any extension. Just create a file without any extension.

And make sure Dockerfile is in same directory from where you are trying to building docker image.

Drop shadow for PNG image in CSS

This won't be possible with css - an image is a square, and so the shadow would be the shadow of a square. The easiest way would be to use photoshop/gimp or any other image editor to apply the shadow like core draw.

What is the basic difference between the Factory and Abstract Factory Design Patterns?

Abstract Factory is template for creating different type of interfaces. Suppose you have project that requires you to parse different types of csv files containing quantity, price and item specific information like some contain data about fruits other about chocolates and then after parsing you need to update this information in their corresponding database so now you can have one abstract factory returning you parser and modifier factory and then this parser factory can return you Chocolate parser object,Fruit Parser Object etc. and similarly Modifier Factory can return Chocolate modifier object , Fruit Modifier object etc.

Running Windows batch file commands asynchronously

There's a third (and potentially much easier) option. If you want to spin up multiple instances of a single program, using a Unix-style command processor like Xargs or GNU Parallel can make that a fairly straightforward process.

There's a win32 Xargs clone called PPX2 that makes this fairly straightforward.

For instance, if you wanted to transcode a directory of video files, you could run the command:

dir /b *.mpg |ppx2 -P 4 -I {} -L 1 ffmpeg.exe -i "{}" -quality:v 1 "{}.mp4"

Picking this apart, dir /b *.mpg grabs a list of .mpg files in my current directory, the | operator pipes this list into ppx2, which then builds a series of commands to be executed in parallel; 4 at a time, as specified here by the -P 4 operator. The -L 1 operator tells ppx2 to only send one line of our directory listing to ffmpeg at a time.

After that, you just write your command line (ffmpeg.exe -i "{}" -quality:v 1 "{}.mp4"), and {} gets automatically substituted for each line of your directory listing.

It's not universally applicable to every case, but is a whole lot easier than using the batch file workarounds detailed above. Of course, if you're not dealing with a list of files, you could also pipe the contents of a textfile or any other program into the input of pxx2.

ArrayList insertion and retrieval order

Yes. ArrayList is a sequential list. So, insertion and retrieval order is the same.

If you add elements during retrieval, the order will not remain the same.

How do I animate constraint changes?

Generally, you just need to update constraints and call layoutIfNeeded inside the animation block. This can be either changing the .constant property of an NSLayoutConstraint, adding remove constraints (iOS 7), or changing the .active property of constraints (iOS 8 & 9).

Sample Code:

[UIView animateWithDuration:0.3 animations:^{
    // Move to right
    self.leadingConstraint.active = false;
    self.trailingConstraint.active = true;

    // Move to bottom
    self.topConstraint.active = false;
    self.bottomConstraint.active = true;

    // Make the animation happen
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
}];

Sample Setup:

Xcode Project so sample animation project.

Controversy

There are some questions about whether the constraint should be changed before the animation block, or inside it (see previous answers).

The following is a Twitter conversation between Martin Pilkington who teaches iOS, and Ken Ferry who wrote Auto Layout. Ken explains that though changing constants outside of the animation block may currently work, it's not safe and they should really be change inside the animation block. https://twitter.com/kongtomorrow/status/440627401018466305

Animation:

Sample Project

Here's a simple project showing how a view can be animated. It's using Objective C and animates the view by changing the .active property of several constraints. https://github.com/shepting/SampleAutoLayoutAnimation

using jquery $.ajax to call a PHP function

You are going to have to expose and endpoint (URL) in your system which will accept the POST request from the ajax call in jQuery.

Then, when processing that url from PHP, you would call your function and return the result in the appropriate format (JSON most likely, or XML if you prefer).

What are the options for (keyup) in Angular2?

One like with events

(keydown)="$event.keyCode != 32 ? $event:$event.preventDefault()"

How to store Query Result in variable using mysql

Additionally, if you want to set multiple variables at once by one query, you can use the other syntax for setting variables which goes like this: SELECT @varname:=value.

A practical example:

SELECT @total_count:=COUNT(*), @total_price:=SUM(quantity*price) FROM items ...

afxwin.h file is missing in VC++ Express Edition

Found this post that may help: http://social.msdn.microsoft.com/forums/en-US/Vsexpressvc/thread/7c274008-80eb-42a0-a79b-95f5afbf6528/

Or shortly, afxwin.h is MFC and MFC is not included in the free version of VC++ (Express Edition).

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

I realize this is a rather late post but still a possible solution for the OP. I use IE9 on Win 7 and have been having Adobe Reader's grey screen issues for several months when trying to open pdf bank and credit card statements online. I could open everything in Firefox or Opera but not IE. I finally tried PDF-Viewer, set it as the default pdf viewer in its preferences and no more problems. I'm sure there are other free viewers out there, like Foxit, PDF-Xchange, etc., that will give better results than Reader with less headaches. Adobe is like some of the other big companies that develop software on a take it or leave it basis ... so I left it.

jQuery ui dialog change title after load-callback

I tried to implement the result of Nick which is:

$('.selectorUsedToCreateTheDialog').dialog('option', 'title', 'My New title');

But that didn't work for me because i had multiple dialogs on 1 page. In such a situation it will only set the title correct the first time. Trying to staple commands did not work:

    $("#modal_popup").html(data);
    $("#modal_popup").dialog('option', 'title', 'My New Title');
    $("#modal_popup").dialog({ width: 950, height: 550);

I fixed this by adding the title to the javascript function arguments of each dialog on the page:

function show_popup1() {
    $("#modal_popup").html(data);
    $("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my First Dialog'});
}

function show_popup2() {
    $("#modal_popup").html(data);
    $("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my Other Dialog'});
}

Add empty columns to a dataframe with specified names from a vector

The problem with your code is in the line:

for(i in length(namevector))

You need to ask yourself: what is length(namevector)? It's one number. So essentially you're saying:

for(i in 11)
df[,i] <- NA

Or more simply:

df[,11] <- NA

That's why you're getting an error. What you want is:

for(i in namevector)
    df[,i] <- NA

Or more simply:

df[,namevector] <- NA

JavaScript onclick redirect

Change the onclick from

onclick="javascript:SubmitFrm()"

to

onclick="SubmitFrm()"

jQuery Validate Required Select

I don't know how was the plugin the time the question was asked (2010), but I faced the same problem today and solved it this way:

  1. Give your select tag a name attribute. For example in this case

    <select name="myselect">

  2. Instead of working with the attribute value="default" in the tag option, disable the default option or set value="" as suggested by Andrew Coats

    <option disabled="disabled">Choose...</option>

    or

    <option value="">Choose...</option>

  3. Set the plugin validation rule

    $( "#YOUR_FORM_ID" ).validate({ rules: { myselect: { required: true } } });

    or

    <select name="myselect" class="required">

Obs: Andrew Coats' solution works only if you have just one select in your form. If you want his solution to work with more than one select add a name attribute to your select.

Hope it helps! :)

How to determine if one array contains all elements of another array

This can be achieved by doing

(a2 & a1) == a2

This creates the intersection of both arrays, returning all elements from a2 which are also in a1. If the result is the same as a2, you can be sure you have all elements included in a1.

This approach only works if all elements in a2 are different from each other in the first place. If there are doubles, this approach fails. The one from Tempos still works then, so I wholeheartedly recommend his approach (also it's probably faster).

How can I check the extension of a file?

one easy way could be:

import os

if os.path.splitext(file)[1] == ".mp3":
    # do something

os.path.splitext(file) will return a tuple with two values (the filename without extension + just the extension). The second index ([1]) will therefor give you just the extension. The cool thing is, that this way you can also access the filename pretty easily, if needed!

How to return PDF to browser in MVC?

I know this question is old but I thought I would share this as I could not find anything similar.

I wanted to create my views/models as normal using Razor and have them rendered as Pdfs.

This way I had control over the pdf presentation using standard html output rather than figuring out how to layout the document using iTextSharp.

The project and source code is available here with nuget installation instructions:

https://github.com/andyhutch77/MvcRazorToPdf

Install-Package MvcRazorToPdf

Want to make Font Awesome icons clickable

If you don't want it to add it to a link, you can just enclose it within a span and that would work.

<span id='clickableAwesomeFont'><i class="fa fa-behance-square fa-4x"></span>

in your css, then you can:

#clickableAwesomeFont {
     cursor: pointer
}

Then in java script, you can just add a click handler.

In cases where it's actually not a link, I think this is much cleaner and using a link would be changing its semantics and abusing its meaning.

Submit button doesn't work

If you are not using any javascript/jquery for form validation, then a simple layout for your form would look like this.

within the body of your html document:

<form action="formHandler.php" name="yourForm" id="theForm" method="post">    
    <input type="text" name="fname" id="fname" />    
    <input type="submit" value="submit"/>
</form>

You need to ensure you have the submit button within the form tags, and an appropriate action assigned. Such as sending to a php file.

For a more direct answer, provide the code you are working with.

You may find the following of use: http://www.w3.org/TR/html401/interact/forms.html

Downloading a file from spring controllers

You should be able to write the file on the response directly. Something like

response.setContentType("application/pdf");      
response.setHeader("Content-Disposition", "attachment; filename=\"somefile.pdf\""); 

and then write the file as a binary stream on response.getOutputStream(). Remember to do response.flush() at the end and that should do it.

jQuery event for images loaded

$( "img.photo" ).load(function() {

    $(".parrentDiv").css('height',$("img.photo").height());
    // very simple

}); 

What is an efficient way to implement a singleton pattern in Java?

Depending on the usage, there are several "correct" answers.

Since Java 5, the best way to do it is to use an enum:

public enum Foo {
   INSTANCE;
}

Pre Java 5, the most simple case is:

public final class Foo {

    private static final Foo INSTANCE = new Foo();

    private Foo() {
        if (INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");
        }
    }

    public static Foo getInstance() {
        return INSTANCE;
    }

    public Object clone() throws CloneNotSupportedException{
        throw new CloneNotSupportedException("Cannot clone instance of this class");
    }
}

Let's go over the code. First, you want the class to be final. In this case, I've used the final keyword to let the users know it is final. Then you need to make the constructor private to prevent users to create their own Foo. Throwing an exception from the constructor prevents users to use reflection to create a second Foo. Then you create a private static final Foo field to hold the only instance, and a public static Foo getInstance() method to return it. The Java specification makes sure that the constructor is only called when the class is first used.

When you have a very large object or heavy construction code and also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization.

You can use a private static class to load the instance. The code would then look like:

public final class Foo {

    private static class FooLoader {
        private static final Foo INSTANCE = new Foo();
    }

    private Foo() {
        if (FooLoader.INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");
        }
    }

    public static Foo getInstance() {
        return FooLoader.INSTANCE;
    }
}

Since the line private static final Foo INSTANCE = new Foo(); is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread safe.

When you also want to be able to serialize your object you need to make sure that deserialization won't create a copy.

public final class Foo implements Serializable {

    private static final long serialVersionUID = 1L;

    private static class FooLoader {
        private static final Foo INSTANCE = new Foo();
    }

    private Foo() {
        if (FooLoader.INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");
        }
    }

    public static Foo getInstance() {
        return FooLoader.INSTANCE;
    }

    @SuppressWarnings("unused")
    private Foo readResolve() {
        return FooLoader.INSTANCE;
    }
}

The method readResolve() will make sure the only instance will be returned, even when the object was serialized in a previous run of your program.

Get SELECT's value and text in jQuery

$('select').val()  // Get's the value

$('select option:selected').val() ; // Get's the value

$('select').find('option:selected').val() ; // Get's the value

$('select option:selected').text()  // Gets you the text of the selected option

Check FIDDLE

Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity

I've preferred using the params filter for parameter-centric content-type.. I believe that should work in conjunction with the produces attribute.

@GetMapping(value="/person/{id}/", 
            params="format=json",
            produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Person> getPerson(@PathVariable Integer id){
    Person person = personMapRepository.findPerson(id);
    return ResponseEntity.ok(person);
} 
@GetMapping(value="/person/{id}/", 
            params="format=xml",
            produces=MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<Person> getPersonXML(@PathVariable Integer id){
    return GetPerson(id); // delegate
}

What is the difference between a candidate key and a primary key?

A Primary key is a special kind of index in that:

there can be only one;
it cannot be nullable
it must be unique.

Candidate keys are selected from the set of super keys, the only thing we take care while selecting the candidate key is: It should not have any redundant attribute.

Example of an Employee table: Employee ( Employee ID, FullName, SSN, DeptID )

  1. Candidate Key: are individual columns in a table that qualifies for the uniqueness of all the rows. Here in Employee table EmployeeID & SSN are Candidate keys.

  2. Primary Key: are the columns you choose to maintain uniqueness in a table. Here in Employee table, you can choose either EmployeeID or SSN columns, EmployeeID is a preferable choice, as SSN is a secure value.

  3. Alternate Key: Candidate column other the Primary column, like if EmployeeID is PK then SSN would be the Alternate key.

  4. Super Key: If you add any other column/attribute to a Primary Key then it becomes a super key, like EmployeeID + FullName, is a Super Key.

  5. Composite Key: If a table does not have a single column that qualifies for a Candidate key, then you have to select 2 or more columns to make a row unique. Like if there is no EmployeeID or SSN columns, then you can make FullName + DateOfBirth as Composite primary Key. But still, there can be a narrow chance of duplicate row.

html table cell width for different rows

You can't have cells of arbitrarily different widths, this is generally a standard behaviour of tables from any space, e.g. Excel, otherwise it's no longer a table but just a list of text.

You can however have cells span multiple columns, such as:

<table>
    <tr>
        <td>25</td>
        <td>50</td>
        <td>25</td>
    </tr>
    <tr>
        <td colspan="2">75</td>
        <td>20</td>
    </tr>
</table>

As an aside, you should avoid using style attributes like border and bgcolor and prefer CSS for those.

How to use cURL in Java?

Use Runtime to call Curl. This code works for both Ubuntu and Windows.

String[] commands = new String {"curl", "-X", "GET", "http://checkip.amazonaws.com"};
Process process = Runtime.getRuntime().exec(commands);
BufferedReader reader = new BufferedReader(new 
InputStreamReader(process.getInputStream()));
String line;
String response;
while ((line = reader.readLine()) != null) {
    response.append(line);
}

What is the most efficient way to get first and last line of a text file?

w=open(file.txt, 'r')
print ('first line is : ',w.readline())
for line in w:  
    x= line
print ('last line is : ',x)
w.close()

The for loop runs through the lines and x gets the last line on the final iteration.

What do hjust and vjust do when making a plot using ggplot?

The value of hjust and vjust are only defined between 0 and 1:

  • 0 means left-justified
  • 1 means right-justified

Source: ggplot2, Hadley Wickham, page 196

(Yes, I know that in most cases you can use it beyond this range, but don't expect it to behave in any specific way. This is outside spec.)

hjust controls horizontal justification and vjust controls vertical justification.

An example should make this clear:

td <- expand.grid(
    hjust=c(0, 0.5, 1),
    vjust=c(0, 0.5, 1),
    angle=c(0, 45, 90),
    text="text"
)

ggplot(td, aes(x=hjust, y=vjust)) + 
    geom_point() +
    geom_text(aes(label=text, angle=angle, hjust=hjust, vjust=vjust)) + 
    facet_grid(~angle) +
    scale_x_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2)) +
    scale_y_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2))

enter image description here


To understand what happens when you change the hjust in axis text, you need to understand that the horizontal alignment for axis text is defined in relation not to the x-axis, but to the entire plot (where this includes the y-axis text). (This is, in my view, unfortunate. It would be much more useful to have the alignment relative to the axis.)

DF <- data.frame(x=LETTERS[1:3],y=1:3)
p <- ggplot(DF, aes(x,y)) + geom_point() + 
    ylab("Very long label for y") +
    theme(axis.title.y=element_text(angle=0))


p1 <- p + theme(axis.title.x=element_text(hjust=0)) + xlab("X-axis at hjust=0")
p2 <- p + theme(axis.title.x=element_text(hjust=0.5)) + xlab("X-axis at hjust=0.5")
p3 <- p + theme(axis.title.x=element_text(hjust=1)) + xlab("X-axis at hjust=1")

library(ggExtra)
align.plots(p1, p2, p3)

enter image description here


To explore what happens with vjust aligment of axis labels:

DF <- data.frame(x=c("a\na","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()

p1 <- p + theme(axis.text.x=element_text(vjust=0, colour="red")) + 
        xlab("X-axis labels aligned with vjust=0")
p2 <- p + theme(axis.text.x=element_text(vjust=0.5, colour="red")) + 
        xlab("X-axis labels aligned with vjust=0.5")
p3 <- p + theme(axis.text.x=element_text(vjust=1, colour="red")) + 
        xlab("X-axis labels aligned with vjust=1")


library(ggExtra)
align.plots(p1, p2, p3)

enter image description here

Media query to detect if device is touchscreen

This solution will work until CSS4 is globally supported by all browsers. When that day comes just use CSS4. but until then, this works for current browsers.

browser-util.js

export const isMobile = {
  android: () => navigator.userAgent.match(/Android/i),
  blackberry: () => navigator.userAgent.match(/BlackBerry/i),
  ios: () => navigator.userAgent.match(/iPhone|iPad|iPod/i),
  opera: () => navigator.userAgent.match(/Opera Mini/i),
  windows: () => navigator.userAgent.match(/IEMobile/i),
  any: () => (isMobile.android() || isMobile.blackberry() || 
  isMobile.ios() || isMobile.opera() || isMobile.windows())
};

onload:

old way:

isMobile.any() ? document.getElementsByTagName("body")[0].className += 'is-touch' : null;

newer way:

isMobile.any() ? document.body.classList.add('is-touch') : null;

The above code will add the "is-touch" class to the body tag if the device has a touch screen. Now any location in your web application where you would have css for :hover you can call body:not(.is-touch) the_rest_of_my_css:hover

for example:

button:hover

becomes:

body:not(.is-touch) button:hover

This solution avoids using modernizer as the modernizer lib is a very big library. If all you're trying to do is detect touch screens, This will be best when the size of the final compiled source is a requirement.

Building with Lombok's @Slf4j and Intellij: Cannot find symbol log

Presumably, that's the Lombok @Slf4j annotation you're using. You'll need to install the Lombok plugin in IntelliJ if you want IntelliJ to recognize Lombok annotations. Otherwise, what do you expect if you try to use a field that doesn't exist?

NoClassDefFoundError on Maven dependency

For some reason, the lib is present while compiling, but missing while running.

My situation is, two versions of one lib conflict.

For example, A depends on B and C, while B depends on D:1.0, C depends on D:1.1, maven may just import D:1.0. If A uses one class which is in D:1.1 but not in D:1.0, a NoClassDefFoundError will be throwed.

If you are in this situation too, you need to resolve the dependency conflict.

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

I've resolved the issue, by going to setting and permalink, just choose post-name.

it should work and you'll see the exact page.. rather than dashboard/xampp page again

Best of Luck

how to set the default value to the drop down list control?

if you know the index of the item of default value,just

lstDepartment.SelectedIndex = 1;//the second item

or if you know the value you want to set, just

lstDepartment.SelectedValue = "the value you want to set";

Exercises to improve my Java programming skills

Once you are quite good in Java SE (lets say you are able to pass SCJP), I'd suggest you get junior Java programmer job and improve yourself on real world problems

Understanding dict.copy() - shallow or deep?

It's not a matter of deep copy or shallow copy, none of what you're doing is deep copy.

Here:

>>> new = original 

you're creating a new reference to the the list/dict referenced by original.

while here:

>>> new = original.copy()
>>> # or
>>> new = list(original) # dict(original)

you're creating a new list/dict which is filled with a copy of the references of objects contained in the original container.

C/C++ maximum stack size of program

Platform-dependent, toolchain-dependent, ulimit-dependent, parameter-dependent.... It is not at all specified, and there are many static and dynamic properties that can influence it.

Finish an activity from another activity

That you can do, but I think you should not break the normal flow of activity. If you want to finish you activity then you can simply send a broadcast from your activity B to activity A.

Create a broadcast receiver before starting your activity B:

BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context arg0, Intent intent) {
        String action = intent.getAction();
        if (action.equals("finish_activity")) {
            finish();
            // DO WHATEVER YOU WANT.
        }
    }
};
registerReceiver(broadcastReceiver, new IntentFilter("finish_activity"));

Send broadcast from activity B to activity A when you want to finish activity A from B

Intent intent = new Intent("finish_activity");
sendBroadcast(intent);

I hope it will work for you...

How to change an image on click using CSS alone?

You can use the different states of the link for different images example

You can also use the same image (css sprite) which combines all the different states and then just play with the padding and position to show only the one you want to display.

Another option would be using javascript to replace the image, that would give you more flexibility

ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

All these answers are fine if you execute one line at a time. However, the original question was to input a sql script that would be executed by a single db execute and all the solutions ( like checking to see if the column is there ahead of time ) would require the executing program either have knowledge of what tables and columns are being altered/added or do pre-processing and parsing of the input script to determine this information. Typically you are not going to run this in realtime or often. So the idea of catching an exception is acceptable and then moving on. Therein lies the problem...how to move on. Luckily the error message gives us all the information we need to do this. The idea is to execute the sql if it exceptions on an alter table call we can find the alter table line in the sql and return the remaining lines and execute until it either succeeds or no more matching alter table lines can be found. Heres some example code where we have sql scripts in an array. We iterate the array executing each script. We call it twice to get the alter table command to fail but the program succeeds because we remove the alter table command from the sql and re-execute the updated code.

#!/bin/sh
# the next line restarts using wish \

exec /opt/usr8.6.3/bin/tclsh8.6  "$0" ${1+"$@"}
foreach pkg {sqlite3 } {
    if { [ catch {package require {*}$pkg } err ] != 0 } {
    puts stderr "Unable to find package $pkg\n$err\n ... adjust your auto_path!";
    }
}
array set sqlArray {
    1 {
    CREATE TABLE IF NOT EXISTS Notes (
                      id INTEGER PRIMARY KEY AUTOINCREMENT,
                      name text,
                      note text,
                      createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
                      updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) 
                      );
    CREATE TABLE IF NOT EXISTS Version (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        version text,
                        createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
                        updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) )
                        );
    INSERT INTO Version(version) values('1.0');
    }
    2 {
    CREATE TABLE IF NOT EXISTS Tags (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name text,
        tag text,
        createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
        updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) 
        );
    ALTER TABLE Notes ADD COLUMN dump text;
    INSERT INTO Version(version) values('2.0');
    }
    3 {
    ALTER TABLE Version ADD COLUMN sql text;
    INSERT INTO Version(version) values('3.0');
    }
}

# create db command , use in memory database for demonstration purposes
sqlite3 db :memory:

proc createSchema { sqlArray } {
    upvar $sqlArray sql
    # execute each sql script in order 
    foreach version [lsort -integer [array names sql ] ] {
    set cmd $sql($version)
    set ok 0
    while { !$ok && [string length $cmd ] } {  
        try {
        db eval $cmd
        set ok 1  ;   # it succeeded if we get here
        } on error { err backtrace } {
        if { [regexp {duplicate column name: ([a-zA-Z0-9])} [string trim $err ] match columnname ] } {
            puts "Error:  $err ... trying again" 
            set cmd [removeAlterTable $cmd $columnname ]
        } else {
            throw DBERROR "$err\n$backtrace"
        }
        }
    }
    }
}
# return sqltext with alter table command with column name removed
# if no matching alter table line found or result is no lines then
# returns ""
proc removeAlterTable { sqltext columnname } {
    set mode skip
    set result [list]
    foreach line [split $sqltext \n ] {
    if { [string first "alter table" [string tolower [string trim $line] ] ] >= 0 } {
        if { [string first $columnname $line ] } {
        set mode add
        continue;
        }
    }
    if { $mode eq "add" } {
        lappend result $line
    }
    }
    if { $mode eq "skip" } {
    puts stderr "Unable to find matching alter table line"
    return ""
    } elseif { [llength $result ] }  { 
    return [ join $result \n ]
    } else {
    return ""
    }
}
               
proc printSchema { } {
    db eval { select * from sqlite_master } x {
    puts "Table: $x(tbl_name)"
    puts "$x(sql)"
    puts "-------------"
    }
}
createSchema sqlArray
printSchema
# run again to see if we get alter table errors 
createSchema sqlArray
printSchema

expected output

Table: Notes
CREATE TABLE Notes (
                      id INTEGER PRIMARY KEY AUTOINCREMENT,
                      name text,
                      note text,
                      createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
                      updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) 
                      , dump text)
-------------
Table: sqlite_sequence
CREATE TABLE sqlite_sequence(name,seq)
-------------
Table: Version
CREATE TABLE Version (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        version text,
                        createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
                        updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) )
                        , sql text)
-------------
Table: Tags
CREATE TABLE Tags (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name text,
        tag text,
        createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
        updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) 
        )
-------------
Error:  duplicate column name: dump ... trying again
Error:  duplicate column name: sql ... trying again
Table: Notes
CREATE TABLE Notes (
                      id INTEGER PRIMARY KEY AUTOINCREMENT,
                      name text,
                      note text,
                      createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
                      updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) 
                      , dump text)
-------------
Table: sqlite_sequence
CREATE TABLE sqlite_sequence(name,seq)
-------------
Table: Version
CREATE TABLE Version (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        version text,
                        createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
                        updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) )
                        , sql text)
-------------
Table: Tags
CREATE TABLE Tags (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name text,
        tag text,
        createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
        updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) 
        )
-------------

How to get Java Decompiler / JD / JD-Eclipse running in Eclipse Helios

Just download the site from the JD page. I was able to install from a local site in the isntalled software section of eclipse.

Open page in new window without popup blocking

For the Submit button, add this code and then set your form target="newwin"

onclick=window.open("about:blank","newwin") 

How to use css style in php

You can also embed it in the php. E.g.

<?php
    echo "<p style='color:blue; border:2px red solid;'>CSS Styling in php</p>";
?>

hope this help for anyone in the future.

How do I connect to a Websphere Datasource with a given JNDI name?

DNS for Services

JNDI needs to be approached with the understanding that it is a service locator. When the desired service is hosted on the same server/node as the application, then your use of InitialContext may work.

What makes it more complicated is that defining a Data Source in Web Sphere (at least back in 4.0) allowed you to define the visibility to various degrees. Basically it adds namespaces to the environment and clients have to know where the resource is hosted.

Simple example.

javax.naming.InitialContext ctx = new javax.naming.InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/DataSourceAlias");

Here is IBM's reference page.

If you are trying to reference a data source from an app that is NOT in the J2EE container, you'll need a slightly different approach starting with needing some J2EE client jars in your classpath. http://www.coderanch.com/t/75386/Websphere/lookup-datasources-JNDI-outside-EE

Oracle get previous day records

how about sysdate?

SELECT field,datetime_field 
FROM database
WHERE datetime_field > (sysdate-1)

How do I get the current timezone name in Postgres 9.3?

It seems to work fine in Postgresql 9.5:

SELECT current_setting('TIMEZONE');

https connection using CURL from command line

use --cacert to specify a .crt file. ca-root-nss.crt for example.

How do I get NuGet to install/update all the packages in the packages.config?

Here's another solution if you are using website projects, or don't want to enable NuGet Package restore.

You can use the package manager console to enumerate all the packages in the package.config file and re-install them.

# read the packages.config file into an XML object
[xml]$packages = gc packages.config

# install each package 
$packages.packages.package | % { Install-Package -id $($_.id) -Version $($_.version) }

Format / Suppress Scientific Notation from Python Pandas Aggregation Results

Granted, the answer I linked in the comments is not very helpful. You can specify your own string converter like so.

In [25]: pd.set_option('display.float_format', lambda x: '%.3f' % x)

In [28]: Series(np.random.randn(3))*1000000000
Out[28]: 
0    -757322420.605
1   -1436160588.997
2   -1235116117.064
dtype: float64

I'm not sure if that's the preferred way to do this, but it works.

Converting numbers to strings purely for aesthetic purposes seems like a bad idea, but if you have a good reason, this is one way:

In [6]: Series(np.random.randn(3)).apply(lambda x: '%.3f' % x)
Out[6]: 
0     0.026
1    -0.482
2    -0.694
dtype: object

Callback functions in Java

A method is not (yet) a first-class object in Java; you can't pass a function pointer as a callback. Instead, create an object (which usually implements an interface) that contains the method you need and pass that.

Proposals for closures in Java—which would provide the behavior you are looking for—have been made, but none will be included in the upcoming Java 7 release.

Mean of a column in a data frame, given the column's name

Suppose you have a data frame(say df) with columns "x" and "y", you can find mean of column (x or y) using:

1.Using mean() function

z<-mean(df$x)

2.Using the column name(say x) as a variable using attach() function

 attach(df)
 mean(x)

When done you can call detach() to remove "x"

detach()

3.Using with() function, it lets you use columns of data frame as distinct variables.

 z<-with(df,mean(x))

Cannot find Microsoft.Office.Interop Visual Studio

Just doing like @Kjartan.

Steps are as follows:

  1. Right click your C# project name in Visual Studio's "Solution Explorer";

  2. Then, select "add -> Reference -> COM -> Type Libraries " in order;

  3. Find the "Microsoft Office 16.0 Object Library", and add it to reference (Note: the version number may vary with the OFFICE you have installed);

  4. After doing this, you will see "Microsoft.Office.Interop.Word" under the "Reference" item in your project.

Why did my Git repo enter a detached HEAD state?

I reproduced this just now by accident:

  1. lists the remote branches

    git branch -r
          origin/Feature/f1234
          origin/master
    
  2. I want to checkout one locally, so I cut paste:

    git checkout origin/Feature/f1234
    
  3. Presto! Detached HEAD state

    You are in 'detached HEAD' state. [...])
    

Solution #1:

Do not include origin/ at the front of my branch spec when checking it out:

git checkout Feature/f1234

Solution #2:

Add -b parameter which creates a local branch from the remote

git checkout -b origin/Feature/f1234 or

git checkout -b Feature/f1234 it will fall back to origin automatically

How do I "shake" an Android device within the Android emulator to bring up the dev menu to debug my React Native app

With a React Native running in the emulator,
Press ctrl+m (for Linux, I suppose it's the same for Windows and ?+m for Mac OS X) or run the following in terminal:

adb shell input keyevent 82

The number of method references in a .dex file cannot exceed 64k API 17

This error can also occur when you load all google play services apis when you only using afew.

As stated by google:"In versions of Google Play services prior to 6.5, you had to compile the entire package of APIs into your app. In some cases, doing so made it more difficult to keep the number of methods in your app (including framework APIs, library methods, and your own code) under the 65,536 limit.

From version 6.5, you can instead selectively compile Google Play service APIs into your app."

For example when your app needs play-services-maps ,play-services-location .You need to add only the two apis in your build.gradle file at app level as show below:

compile 'com.google.android.gms:play-services-maps:10.2.1'
compile 'com.google.android.gms:play-services-location:10.2.1'

Instead of:

compile 'com.google.android.gms:play-services:10.2.1'

For full documentation and list of google play services apis click here

Responsive css background images

You can use this. I have tested and its working 100% correct:

background-image:url('../images/bg.png'); 
background-repeat:no-repeat;
background-size:100%;
background-position:center;

You can test your website with responsiveness at this Screen Size Simulator: http://www.infobyip.com/testwebsiteresolution.php

Clear Your cache each time you make changes and i would prefer to use Firefox to test it.

If you want to use an Image form other site/URL and not like: background-image:url('../images/bg.png'); //This structure is to use the image from your own hosted server. Then use like this: background-image: url(http://173.254.28.15/~brettedm/wp-content/uploads/Brett-Edmonds-Photography-14.jpg) ;

Enjoy :)

How to create JSON string in JavaScript?

The function JSON.stringify will turn your json object into a string:

var jsonAsString = JSON.stringify(obj);

In case the browser does not implement it (IE6/IE7), use the JSON2.js script. It's safe as it uses the native implementation if it exists.

Passing a dictionary to a function as keyword parameters

Figured it out for myself in the end. It is simple, I was just missing the ** operator to unpack the dictionary

So my example becomes:

d = dict(p1=1, p2=2)
def f2(p1,p2):
    print p1, p2
f2(**d)

How can I create download link in HTML?

The download attribute is new for the <a> tag in HTML5

<a href="http://www.odin.com/form.pdf" download>Download Form</a>
or
<a href="http://www.odin.com/form.pdf" download="Form">Download Form</a>

I prefer the first one it is preferable in respect to any extension.

How can I make a checkbox readonly? not disabled?

<input type="checkbox" checked onclick="return false;" onkeydown="return false;"/>

http://jsfiddle.net/2srjc/

If you are worried about tab order, only return false for the keydown event when the tab key was not pressed:

<input type="checkbox" checked onclick="return false;" onkeydown="e = e || window.event; if(e.keyCode !== 9) return false;"/>

http://jsfiddle.net/2srjc/149/

Syntax error due to using a reserved word as a table or column name in MySQL

The Problem

In MySQL, certain words like SELECT, INSERT, DELETE etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.

As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):

Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.

...

If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.

...

The identifier quote character is the backtick ("`"):

A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.

  • ADD
  • AND
  • BEFORE
  • BY
  • CALL
  • CASE
  • CONDITION
  • DELETE
  • DESC
  • DESCRIBE
  • FROM
  • GROUP
  • IN
  • INDEX
  • INSERT
  • INTERVAL
  • IS
  • KEY
  • LIKE
  • LIMIT
  • LONG
  • MATCH
  • NOT
  • OPTION
  • OR
  • ORDER
  • PARTITION
  • RANK
  • REFERENCES
  • SELECT
  • TABLE
  • TO
  • UPDATE
  • WHERE

The Solution

You have two options.

1. Don't use reserved words as identifiers

The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.

Doing this has a couple of advantages:

  • It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.

  • The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.

Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.

2. Use backticks

If renaming the table or column isn't possible, wrap the offending identifier in backticks (`) as described in the earlier quote from 10.2 Schema Object Names.

An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):

mysql> CREATE TABLE interval (begin INT, end INT);
ERROR 1064 (42000): You have an error in your SQL syntax.
near 'interval (begin INT, end INT)'

mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)

Similarly, the query from the question can be fixed by wrapping the keyword key in backticks, as shown below:

INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)";               ^   ^

Run a mySQL query as a cron job?

This was a very handy page as I have a requirement to DELETE records from a mySQL table where the expiry date is < Today.

I am on a shared host and CRON did not like the suggestion AndrewKDay. it also said (and I agree) that exposing the password in this way could be insecure.

I then tried turning Events ON in phpMyAdmin but again being on a shared host this was a no no. Sorry fancyPants.

So I turned to embedding the SQL script in a PHP file. I used the example [here][1]

[1]: https://www.w3schools.com/php/php_mysql_create_table.asp stored it in a sub folder somewhere safe and added an empty index.php for good measure. I was then able to test that this PHP file (and my SQL script) was working from the browser URL line.

All good so far. On to CRON. Following the above example almost worked. I ended up calling PHP before the path for my *.php file. Otherwise CRON didn't know what to do with the file.

my cron is set to run once per day and looks like this, modified for security.

00 * * * * php mywebsiteurl.com/wp-content/themes/ForteChildTheme/php/DeleteExpiredAssessment.php

For the final testing with CRON I initially set it to run each minute and had email alerts turned on. This quickly confirmed that it was running as planned and I changed it back to once per day.

Hope this helps.

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

Don't pass id(pk) to persist method or try save() method instead of persist().

ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist

In my case here, I just had to resurrect a server that was 9 years old, and Oracle was giving me this error.

For some reason, the server had been renamed, but the app/oracle/product/10.2.0/server/network/admin/listener.ora file was still declaring a LISTENER with the old HOST.

I had to put the same name that I had in /etc/hostname in the /etc/hosts, and also fix the name used in the listener.ora.

How can I check whether a option already exist in select by JQuery

if ( $("#your_select_id option[value=<enter_value_here>]").length == 0 ){
  alert("option doesn't exist!");
}

Remove blank lines with grep

Use:

$ dos2unix file
$ grep -v "^$" file

Or just simply awk:

awk 'NF' file

If you don't have dos2unix, then you can use tools like tr:

tr -d '\r' < "$file" > t ; mv t "$file"

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

A very simple solution is to search your file(s) for non-ascii characters using a regular expression. This will nicely highlight all the spots where they are found with a border.

Search for [^\x00-\x7F] and check the box for Regex.

The result will look like this (in dark mode):

zero width space made visible

IIS: Where can I find the IIS logs?

I'm adding this answer because after researching the web, I ended up at this answer but still didn't know which subfolder of the IIS logs folder to look in.

If your server has multiple websites, you will need to know the IIS ID for the site. An easy way to get this in IIS is to simply click on the Sites folder in the left panel. The ID for each site is shown in the right panel.

Once you know the ID, let's call it n, the corresponding logs are in the W3SVCn subfolder of the IIS logs folder. So, if your website ID is 4, say, and the IIS logs are in the default location, then the logs are in this folder:

%SystemDrive%\inetpub\logs\LogFiles\W3SVC4

Acknowlegements:

  • Answer by @jishi tells where the logs are by default.
  • Answer by @Rafid explains how to find actual location (maybe not default).
  • Answer by @Bergius gives a programmatic way to find the log folder location for a specific website, taking ID into account, without using IIS.

How to get date and time from server

No need to use date_default_timezone_set for the whole script, just specify the timezone you want with a DateTime object:

$now = new DateTime(null, new DateTimeZone('America/New_York'));
$now->setTimezone(new DateTimeZone('Europe/London'));    // Another way
echo $now->format("Y-m-d\TH:i:sO"); // something like "2015-02-11T06:16:47+0100" (ISO 8601)

Does List<T> guarantee insertion order?

If you will change the order of operations, you will avoid the strange behavior: First insert the value to the right place in the list, and then delete it from his first position. Make sure you delete it by his index, because if you will delete it by reference, you might delete them both...

Why does Eclipse automatically add appcompat v7 library support whenever I create a new project?

Sorry with my English, When you create a new android project, you should choose api of high level, for example: from api 17 to api 21, It will not have appcompat and very easy to share project. If you did it with lower API, you just edit in Android Manifest to have upper API :), after that, you can delete Appcompat V7.

jQuery Set Select Index

This may also be useful, so I thought I'd add it here.

If you would like to select a value based on the item's value and not the index of that item then you can do the following:

Your select list:

<select id="selectBox">
    <option value="A">Number 0</option>
    <option value="B">Number 1</option>
    <option value="C">Number 2</option>
    <option value="D">Number 3</option>
    <option value="E">Number 4</option>
    <option value="F">Number 5</option>
    <option value="G">Number 6</option>
    <option value="H">Number 7</option>
</select>

The jquery:

$('#selectBox option[value=C]').attr('selected', 'selected');

$('#selectBox option[value=C]').prop('selected', true);

The selected item would be "Number 2" now.

How to use PDO to fetch results array in PHP?

There are three ways to fetch multiple rows returned by PDO statement.

The simplest one is just to iterate over PDOStatement itself:

$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// iterating over a statement
foreach($stmt as $row) {
    echo $row['name'];
}

another one is to fetch rows using fetch() method inside a familiar while statement:

$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
    echo $row['name'];
}

but for the modern web application we should have our datbase iteractions separated from output and thus the most convenient method would be to fetch all rows at once using fetchAll() method:

$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// fetching rows into array
$data = $stmt->fetchAll();

or, if you need to preprocess some data first, use the while loop and collect the data into array manually

$result = [];
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
    $result[] = [
        'newname' => $row['oldname'],
        // etc
    ];
}

and then output them in a template:

<ul>
<?php foreach($data as $row): ?>
    <li><?=$row['name']?></li>
<?php endforeach ?>
</ul>

Note that PDO supports many sophisticated fetch modes, allowing fetchAll() to return data in many different formats.

How to get the number of characters in a string

I should point out that none of the answers provided so far give you the number of characters as you would expect, especially when you're dealing with emojis (but also some languages like Thai, Korean, or Arabic). VonC's suggestions will output the following:

fmt.Println(utf8.RuneCountInString("??")) // Outputs "6".
fmt.Println(len([]rune("??"))) // Outputs "6".

That's because these methods only count Unicode code points. There are many characters which can be composed of multiple code points.

Same for using the Normalization package:

var ia norm.Iter
ia.InitString(norm.NFKD, "??")
nc := 0
for !ia.Done() {
    nc = nc + 1
    ia.Next()
}
fmt.Println(nc) // Outputs "6".

Normalization is not really the same as counting characters and many characters cannot be normalized into a one-code-point equivalent.

masakielastic's answer comes close but only handles modifiers (the rainbow flag contains a modifier which is thus not counted as its own code point):

fmt.Println(GraphemeCountInString("??"))  // Outputs "5".
fmt.Println(GraphemeCountInString2("??")) // Outputs "5".

The correct way to split Unicode strings into (user-perceived) characters, i.e. grapheme clusters, is defined in the Unicode Standard Annex #29. The rules can be found in Section 3.1.1. The github.com/rivo/uniseg package implements these rules so you can determine the correct number of characters in a string:

fmt.Println(uniseg.GraphemeClusterCount("??")) // Outputs "2".

How to create a bash script to check the SSH connection?

Example Using BASH 4+ script:

# -- ip/host and res which is result of nmap (note must have nmap installed)
ip="192.168.0.1"
res=$(nmap ${ip} -PN -p ssh | grep open)

# -- if result contains open, we can reach ssh else assume failure) --
if [[ "${res}" =~ "open" ]] ;then
    echo "It's Open! Let's SSH to it.."
else
    echo "The host ${ip} is not accessible!"
fi

Invoking a static method using reflection

String methodName= "...";
String[] args = {};

Method[] methods = clazz.getMethods();
for (Method m : methods) {
    if (methodName.equals(m.getName())) {
        // for static methods we can use null as instance of class
        m.invoke(null, new Object[] {args});
        break;
    }
}

How do you reverse a string in place in C or C++?

I like Evgeny's K&R answer. However, it is nice to see a version using pointers. Otherwise, it's essentially the same:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *reverse(char *str) {
    if( str == NULL || !(*str) ) return NULL;
    int i, j = strlen(str)-1;
    char *sallocd;
    sallocd = malloc(sizeof(char) * (j+1));
    for(i=0; j>=0; i++, j--) {
        *(sallocd+i) = *(str+j);
    }
    return sallocd;
}

int main(void) {
    char *s = "a man a plan a canal panama";
    char *sret = reverse(s);
    printf("%s\n", reverse(sret));
    free(sret);
    return 0;
}

Why does the 260 character path length limit exist in Windows?

Quoting this article https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#maximum-path-length-limitation

Maximum Path Length Limitation

In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:\some 256-character path string<NUL>" where "<NUL>" represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.)

Now we see that it is 1+2+256+1 or [drive][:\][path][null] = 260. One could assume that 256 is a reasonable fixed string length from the DOS days. And going back to the DOS APIs we realize that the system tracked the current path per drive, and we have 26 (32 with symbols) maximum drives (and current directories).

The INT 0x21 AH=0x47 says “This function returns the path description without the drive letter and the initial backslash.” So we see that the system stores the CWD as a pair (drive, path) and you ask for the path by specifying the drive (1=A, 2=B, …), if you specify a 0 then it assumes the path for the drive returned by INT 0x21 AH=0x15 AL=0x19. So now we know why it is 260 and not 256, because those 4 bytes are not stored in the path string.

Why a 256 byte path string, because 640K is enough RAM.

Could not extract response: no suitable HttpMessageConverter found for response type

Since you return to the client just String and its content type == 'text/plain', there is no any chance for default converters to determine how to convert String response to the FFSampleResponseHttp object.

The simple way to fix it:

  • remove expected-response-type from <int-http:outbound-gateway>
  • add to the replyChannel1 <json-to-object-transformer>

Otherwise you should write your own HttpMessageConverter to convert the String to the appropriate object.

To make it work with MappingJackson2HttpMessageConverter (one of default converters) and your expected-response-type, you should send your reply with content type = 'application/json'.

If there is a need, just add <header-enricher> after your <service-activator> and before sending a reply to the <int-http:inbound-gateway>.

So, it's up to you which solution to select, but your current state doesn't work, because of inconsistency with default configuration.

UPDATE

OK. Since you changed your server to return FfSampleResponseHttp object as HTTP response, not String, just add contentType = 'application/json' header before sending the response for the HTTP and MappingJackson2HttpMessageConverter will do the stuff for you - your object will be converted to JSON and with correct contentType header.

From client side you should come back to the expected-response-type="com.mycompany.MyChannel.model.FFSampleResponseHttp" and MappingJackson2HttpMessageConverter should do the stuff for you again.

Of course you should remove <json-to-object-transformer> from you message flow after <int-http:outbound-gateway>.

Linq style "For Each"

The official MS line is "because it's not a functional operation" (ie it's a stateful operation).

Couldn't you do something like:

list.Select( x => x+1 )

or if you really need it in a List:

var someValues = new List<int>( list.Select( x => x+1 ) );

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

I have the same problem, in build.gradle (Module:app) add the following line of code inside dependencies:

dependencies 
{
   ...
   compile 'com.android.support:support-annotations:27.1.1'
}

It worked for me perfectly

What does a lazy val do?

scala> lazy val lazyEight = {
     |   println("I am lazy !")
     |   8
     | }
lazyEight: Int = <lazy>

scala> lazyEight
I am lazy !
res1: Int = 8
  • All vals are initialized during object construction
  • Use lazy keyword to defer initialization until first usage
  • Attention: Lazy vals are not final and therefore might show performance drawbacks

List of all index & index columns in SQL Server DB

--Short and sweet:

SELECT OBJECT_SCHEMA_NAME(T.[object_id],DB_ID()) AS [Schema],  
  T.[name] AS [table_name], I.[name] AS [index_name], AC.[name] AS [column_name],  
  I.[type_desc], I.[is_unique], I.[data_space_id], I.[ignore_dup_key], I.[is_primary_key], 
  I.[is_unique_constraint], I.[fill_factor],    I.[is_padded], I.[is_disabled], I.[is_hypothetical], 
  I.[allow_row_locks], I.[allow_page_locks], IC.[is_descending_key], IC.[is_included_column] 
FROM sys.[tables] AS T  
  INNER JOIN sys.[indexes] I ON T.[object_id] = I.[object_id]  
  INNER JOIN sys.[index_columns] IC ON I.[object_id] = IC.[object_id] 
  INNER JOIN sys.[all_columns] AC ON T.[object_id] = AC.[object_id] AND IC.[column_id] = AC.[column_id] 
WHERE T.[is_ms_shipped] = 0 AND I.[type_desc] <> 'HEAP' 
ORDER BY T.[name], I.[index_id], IC.[key_ordinal]   

Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
response = client.execute(httppost, localContext);

doesn't work in 4.5 version without

cookie.setDomain(".domain.com");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");

How to choose an AWS profile when using boto3 to connect to CloudFront

Do this to use a profile with name 'dev':

session = boto3.session.Session(profile_name='dev')
s3 = session.resource('s3')
for bucket in s3.buckets.all():
    print(bucket.name)

Visual Studio 2017 - Git failed with a fatal error

In my case, Windows had ran an update and was waiting to restart the PC. I hadn't seen any notifications but, well... turning it off and turning it on again fixed the problem.

Try that first before monkeying with any of these Visual Studio directories and applications.