Programs & Examples On #One to one

Refers to the quantity of an entity as a relationship to another entity. Meaning that for every instance of an entity, there is a single related instance of another entity.

How can I make a JPA OneToOne relation lazy

This question is quite old, but with Hibernate 5.1.10, there are some new better comfortable solution.

Lazy loading works except for the parent side of a @OneToOne association. This is because Hibernate has no other way of knowing whether to assign a null or a Proxy to this variable. More details you can find in this article

  • You can activate lazy loading bytecode enhancement
  • Or, you can just remove the parent side and use the client side with @MapsId as explained in the article above. This way, you will find that you don’t really need the parent side since the child shares the same id with the parent so you can easily fetch the child by knowing the parent id .

How to Create a real one-to-one relationship in SQL Server

What about this ?

create table dbo.[Address]
(
Id int identity not null,
City nvarchar(255) not null,
Street nvarchar(255) not null,
CONSTRAINT PK_Address PRIMARY KEY (Id)
)

create table dbo.[Person]
(
Id int identity not null,
AddressId int not null,
FirstName nvarchar(255) not null,
LastName nvarchar(255) not null,
CONSTRAINT PK_Person PRIMARY KEY (Id),
CONSTRAINT FK_Person_Address FOREIGN KEY (AddressId) REFERENCES dbo.[Address] (Id)
)

JavaScript: replace last occurrence of text in a string

Thought I'd answer here since this came up first in my Google search and there's no answer (outside of Matt's creative answer :)) that generically replaces the last occurrence of a string of characters when the text to replace might not be at the end of the string.

if (!String.prototype.replaceLast) {
    String.prototype.replaceLast = function(find, replace) {
        var index = this.lastIndexOf(find);

        if (index >= 0) {
            return this.substring(0, index) + replace + this.substring(index + find.length);
        }

        return this.toString();
    };
}

var str = 'one two, one three, one four, one';

// outputs: one two, one three, one four, finish
console.log(str.replaceLast('one', 'finish'));

// outputs: one two, one three, one four; one
console.log(str.replaceLast(',', ';'));

Using a string variable as a variable name

You will be much happier using a dictionary instead:

my_data = {}
foo = "hello"
my_data[foo] = "goodbye"
assert my_data["hello"] == "goodbye"

How to check if IEnumerable is null or empty?

Here's a modified version of @Matt Greer's useful answer that includes a static wrapper class so you can just copy-paste this into a new source file, doesn't depend on Linq, and adds a generic IEnumerable<T> overload, to avoid the boxing of value types that would occur with the non-generic version. [EDIT: Note that use of IEnumerable<T> does not prevent boxing of the enumerator, duck-typing can't prevent that, but at least the elements in a value-typed collection will not each be boxed.]

using System.Collections;
using System.Collections.Generic;

public static class IsNullOrEmptyExtension
{
    public static bool IsNullOrEmpty(this IEnumerable source)
    {
        if (source != null)
        {
            foreach (object obj in source)
            {
                return false;
            }
        }
        return true;
    }

    public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
    {
        if (source != null)
        {
            foreach (T obj in source)
            {
                return false;
            }
        }
        return true;
    }
}

Restoring Nuget References?

In case this helps someone, for me, none of the above was sufficient. I still couldn't build, VS still couldn't find the references. The key was simply to close and reopen the solution after restoring the packages.

Here's the scenario (using Visual Studio 2012):

You open a Solution that has missing packages. The references show that VS can't find them. There are many ways to restore the missing packages, including

  • building a solution that is set to auto-restore
  • opening the Package Manager Console and clicking the nice "Restore" button
  • doing nuget restore if you have the command line nuget installed

But no matter what the approach, those references will still be shown as missing. And when you build it will fail. Sigh. However if you close the solution and re-open it, now VS checks those nice <HintPath>s again, finds that the packages are back where they belong, and all is well with the world.

Update

Is Visual Studio still not seeing that you have the package? Still showing a reference that it can't resolve? Make sure that the version of package you restored is exactly the same as the <HintPath> in your .csproj file. Even a minor bug fix number (e.g. 1.10.1 to 1.10.2) will cause the reference to fail. You can fix this either by directly editing your csproj xml, or else by removing the reference and making a new one pointing at the newly-restored version in the packages directory.

How to set CATALINA_HOME variable in windows 7?

Here is tutorial how to do that (CATALINA_HOME is path to your Tomcat, so I suppose something like C:/Program Files/Tomcat/. And for starting server, you need to execute script startup.bat from command line, this will make it:)

Uses of content-disposition in an HTTP response header

Well, it seems that the Content-Disposition header was originally created for e-mail, not the web. (Link to relevant RFC.)

I'm guessing that web browsers may respond to

Response.AppendHeader("content-disposition", "inline; filename=" + fileName);

when saving, but I'm not sure.

Neither BindingResult nor plain target object for bean name available as request attribute

Just add

model.addAttribute("login", new Login());

to your method ..

it will work..

How to get first object out from List<Object> using Linq

[0] or .First() will give you the same performance whatever happens.
But your Dictionary could contains IEnumerable<Component> instead of List<Component>, and then you cant use the [] operator. That is where the difference is huge.

So for your example, it doesn't really matters, but for this code, you have no choice to use First():

var dic = new Dictionary<String, IEnumerable<Component>>();
foreach (var components in dic.Values)
{
    // you can't use [0] because components is an IEnumerable<Component>
    var firstComponent = components.First(); // be aware that it will throw an exception if components is empty.
    var depCountry = firstComponent.ComponentValue("Dep");
}

Undo a Git merge that hasn't been pushed yet

Okay, the answers other people here gave me were close, but it didn't work. Here's what I did.

Doing this...

git reset --hard HEAD^
git status

...gave me the following status.

# On branch master
# Your branch and 'origin/master' have diverged,
# and have 3 and 3 different commit(s) each, respectively.

I then had to type in the same git reset command several more times. Each time I did that, the message changed by one as you can see below.

> git reset --hard HEAD^
HEAD is now at [...truncated...]
> git status
# On branch master
# Your branch and 'origin/master' have diverged,
# and have 3 and 3 different commit(s) each, respectively.
> git reset --hard HEAD^
HEAD is now at [...truncated...]
> git status
# On branch master
# Your branch and 'origin/master' have diverged,
# and have 2 and 3 different commit(s) each, respectively.
> git reset --hard HEAD^
HEAD is now at [...truncated...]
> git status
# On branch master
# Your branch and 'origin/master' have diverged,
# and have 1 and 3 different commit(s) each, respectively.
> git reset --hard HEAD^
HEAD is now at [...truncated...]
> git status
# On branch master
# Your branch is behind 'origin/master' by 3 commits, and can be fast-forwarded.

At this point, I saw the status message changed, so I tried doing a git pull, and that seemed to work:

> git pull
Updating 2df6af4..12bbd2f
Fast forward
 app/views/truncated |    9 ++++++---
 app/views/truncated |   13 +++++++++++++
 app/views/truncated |    2 +-
 3 files changed, 20 insertions(+), 4 deletions(-)
> git status
# On branch master

So long story short, my commands came down to this:

git reset --hard HEAD^
git reset --hard HEAD^
git reset --hard HEAD^
git reset --hard HEAD^
git pull

Is a URL allowed to contain a space?

Shorter answer: no, you must encode a space; it is correct to encode a space as +, but only in the query string; in the path you must use %20.

Shell script not running, command not found

#! /bin/bash
  ^---

remove the indicated space. The shebang should be

#!/bin/bash

Python equivalent of a given wget command

I had to do something like this on a version of linux that didn't have the right options compiled into wget. This example is for downloading the memory analysis tool 'guppy'. I'm not sure if it's important or not, but I kept the target file's name the same as the url target name...

Here's what I came up with:

python -c "import requests; r = requests.get('https://pypi.python.org/packages/source/g/guppy/guppy-0.1.10.tar.gz') ; open('guppy-0.1.10.tar.gz' , 'wb').write(r.content)"

That's the one-liner, here's it a little more readable:

import requests
fname = 'guppy-0.1.10.tar.gz'
url = 'https://pypi.python.org/packages/source/g/guppy/' + fname
r = requests.get(url)
open(fname , 'wb').write(r.content)

This worked for downloading a tarball. I was able to extract the package and download it after downloading.

EDIT:

To address a question, here is an implementation with a progress bar printed to STDOUT. There is probably a more portable way to do this without the clint package, but this was tested on my machine and works fine:

#!/usr/bin/env python

from clint.textui import progress
import requests

fname = 'guppy-0.1.10.tar.gz'
url = 'https://pypi.python.org/packages/source/g/guppy/' + fname

r = requests.get(url, stream=True)
with open(fname, 'wb') as f:
    total_length = int(r.headers.get('content-length'))
    for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_length/1024) + 1): 
        if chunk:
            f.write(chunk)
            f.flush()

Add a column in a table in HIVE QL

You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);, you just need to get rid of default sum(max_count). No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL as the value for every cell in that column.

So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.

You also have the option to always COALESCE the column to your desired default and leave it NULL for now. This option fails when you want NULL to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE.

If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.

IntelliJ Organize Imports

Goto Help -> Find Action (Short Cut for this is Cntl + Shift + A) and type Optimize imports (Short cut for this is Cntl + Alt + O)

How to make background of table cell transparent

Just set the opacity for the inner table. You can do inline CSS if you want it just for a specific table element, so it doesn't apply to the entire table.

style="opacity: 0%;"

Where/How to getIntent().getExtras() in an Android Fragment?

What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an Intent in an Activity and then pass any extra data to fragments by instantiating them with arguments.

There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using FragmentActivity and Fragment from the support library.

You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:

public static class DetailsActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // (omitted some other stuff)

        if (savedInstanceState == null) {
            // During initial setup, plug in the details fragment.
            DetailsFragment details = new DetailsFragment();
            details.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction().add(
                    android.R.id.content, details).commit();
        }
    }
}

In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called newInstance in the examples given by Google. There actually is a newInstance method in DetailsFragment, so I'm unsure why it isn't used in the snippet above...

Anyways, all extras provided as argument upon creating the fragment, will be available by calling getArguments(). Since this returns a Bundle, its usage is similar to that of the extras in an Activity.

public static class DetailsFragment extends Fragment {
    /**
     * Create a new instance of DetailsFragment, initialized to
     * show the text at 'index'.
     */
    public static DetailsFragment newInstance(int index) {
        DetailsFragment f = new DetailsFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);

        return f;
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }

    // (other stuff omitted)

}

jQuery - Click event on <tr> elements with in a table and getting <td> element values

<script>
jQuery(document).ready(function() {
    jQuery("tr").click(function(){
       alert("Click! "+ jQuery(this).find('td').html());
    });
});
</script>

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

How to initialize a variable of date type in java?

Here's the Javadoc in Oracle's website for the Date class: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html
If you scroll down to "Constructor Summary," you'll see the different options for how a Date object can be instantiated. Like all objects in Java, you create a new one with the following:

Date firstDate = new Date(ConstructorArgsHere);

Now you have a bit of a choice. If you don't pass in any arguments, and just do this,

Date firstDate = new Date();

it will represent the exact date and time at which you called it. Here are some other constructors you may want to make use of:

Date firstDate1 = new Date(int year, int month, int date);
Date firstDate2 = new Date(int year, int month, int date, int hrs, int min);
Date firstDate3 = new Date(int year, int month, int date, int hrs, int min, int sec);

WPF Binding StringFormat Short Date String

Or use this for an English (or mix it up for custom) format:

StringFormat='{}{0:dd/MM/yyyy}'

excel - if cell is not blank, then do IF statement

You need to use AND statement in your formula

=IF(AND(IF(NOT(ISBLANK(Q2));TRUE;FALSE);Q2<=R2);"1";"0")

And if both conditions are met, return 1.

You could also add more conditions in your AND statement.

Body set to overflow-y:hidden but page is still scrollable in Chrome

Another solution I found to work is to set a mousewheel handler on the inside container and make sure it doesn't propagate by setting its last parameter to false and stopping the event bubble.

document.getElementById('content').addEventListener('mousewheel',function(evt){evt.cancelBubble=true;   if (evt.stopPropagation) evt.stopPropagation},false);

Scroll works fine in the inner container, but the event doesn't propagate to the body and so it does not scroll. This is in addition to setting the body properties overflow:hidden and height:100%.

How to do Base64 encoding in node.js?

Buffers can be used for taking a string or piece of data and doing base64 encoding of the result. For example:

You can install Buffer via npm like :- npm i buffer --save

you can use this in your js file like this :-

var buffer = require('buffer/').Buffer;

->> console.log(buffer.from("Hello Vishal Thakur").toString('base64'));
SGVsbG8gVmlzaGFsIFRoYWt1cg==  // Result

->> console.log(buffer.from("SGVsbG8gVmlzaGFsIFRoYWt1cg==", 'base64').toString('ascii'))
Hello Vishal Thakur   // Result

ImportError: No module named sqlalchemy

Okay,I have re-installed the package via pip even that didn't help. And then I rsync'ed the entire /usr/lib/python-2.7 directory from other working machine with similar configuration to the current machine.It started working. I don't have any idea ,what was wrong with my setup. I see some difference "print sys.path" output earlier and now. but now my issue is resolved by this work around.

EDIT:Found the real solution for my setup. upgrading "sqlalchemy only doesn't solve the issue" I also need to upgrade flask-sqlalchemy that resolved the issue.

In C# check that filename is *possibly* valid (not that it exists)

Thought I would post a solution I cobbled together from bits of answers I found after searching for a robust solution to the same problem. Hopefully it helps someone else.

using System;
using System.IO;
//..

public static bool ValidateFilePath(string path, bool RequireDirectory, bool IncludeFileName, bool RequireFileName = false)
{
    if (string.IsNullOrEmpty(path)) { return false; }
    string root = null;
    string directory = null;
    string filename = null;
    try
    {
        // throw ArgumentException - The path parameter contains invalid characters, is empty, or contains only white spaces.
        root = Path.GetPathRoot(path);

        // throw ArgumentException - path contains one or more of the invalid characters defined in GetInvalidPathChars.
        // -or- String.Empty was passed to path.
        directory = Path.GetDirectoryName(path);

        // path contains one or more of the invalid characters defined in GetInvalidPathChars
        if (IncludeFileName) { filename = Path.GetFileName(path); }
    }
    catch (ArgumentException)
    {
        return false;
    }

    // null if path is null, or an empty string if path does not contain root directory information
    if (String.IsNullOrEmpty(root)) { return false; }

    // null if path denotes a root directory or is null. Returns String.Empty if path does not contain directory information
    if (String.IsNullOrEmpty(directory)) { return false; }

    if (RequireFileName)
    {
        // if the last character of path is a directory or volume separator character, this method returns String.Empty
        if (String.IsNullOrEmpty(filename)) { return false; }

        // check for illegal chars in filename
        if (filename.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { return false; }
    }
    return true;
}

How to convert a command-line argument to int?

Like that we can do....

int main(int argc, char *argv[]) {

    int a, b, c;
    *// Converting string type to integer type
    // using function "atoi( argument)"* 

    a = atoi(argv[1]);     
    b = atoi(argv[2]);
    c = atoi(argv[3]);

 }

How can I pad a String in Java?

A simple solution without any API will be as follows:

public String pad(String num, int len){
    if(len-num.length() <=0) return num;
    StringBuffer sb = new StringBuffer();
    for(i=0; i<(len-num.length()); i++){
        sb.append("0");
    }
    sb.append(num);
    return sb.toString();
}

Convert a list to a data frame

Sometimes your data may be a list of lists of vectors of the same length.

lolov = list(list(c(1,2,3),c(4,5,6)), list(c(7,8,9),c(10,11,12),c(13,14,15)) )

(The inner vectors could also be lists, but I'm simplifying to make this easier to read).

Then you can make the following modification. Remember that you can unlist one level at a time:

lov = unlist(lolov, recursive = FALSE )
> lov
[[1]]
[1] 1 2 3

[[2]]
[1] 4 5 6

[[3]]
[1] 7 8 9

[[4]]
[1] 10 11 12

[[5]]
[1] 13 14 15

Now use your favorite method mentioned in the other answers:

library(plyr)
>ldply(lov)
  V1 V2 V3
1  1  2  3
2  4  5  6
3  7  8  9
4 10 11 12
5 13 14 15

addClass and removeClass in jQuery - not removing class

Try this :

$('.close-button').on('click', function(){
  $('.element').removeClass('grown');
  $('.element').addClass('spot');
});

$('.element').on('click', function(){
  $(this).removeClass('spot');
  $(this).addClass('grown');
});

I hope I understood your question.

How can I convert an HTML table to CSV?

This method is not really a library OR a program, but for ad hoc conversions you can

  • put the HTML for a table in a text file called something.xls
  • open it with a spreadsheet
  • save it as CSV.

I know this works with Excel, and I believe I've done it with the OpenOffice spreadsheet.

But you probably would prefer a Perl or Ruby script...

Importing a GitHub project into Eclipse

As mentioned in Alain Beauvois's answer, and now (Q4 2013) better explained in

Copy the URL from GitHub and select in Eclipse from the menu the

File ? Import ? Git ? Projects from Git

http://wiki.eclipse.org/images/5/5a/Egit-0.9-import-projects-select-repository.png


If the Git repo isn't cloned yet:

In> order to checkout a remote project, you will have to clone its repository first.
Open the Eclipse Import wizard (e.g. File => Import), select Git => Projects from Git and click Next.
Select “URI” and click Next.
Now you will have to enter the repository’s location and connection data. Entering the URI will automatically fill some fields. Complete any other required fields and hit Next. If you use GitHub, you can copy the URI from the web page.

Select all branches you wish to clone and hit Next again.

Hit the Clone… button to open another wizard for cloning Git repositories.

http://eclipsesource.com/blogs/wp-content/uploads/2012/12/14-282x300.png


Original answer (July 2011)

First, if your "Working Directory" is C:\Users, that is odd, since it would mean you have cloned the GitHub repo directly within C:\Users (i.e. you have a .git directory in C:\Users)

Usually, you would clone a GitHub repo in "any directory of your choice\theGitHubRepoName".

As described in the EGit user Manual page:

In any case (unless you create a "bare" Repository, but that's not discussed here), the new Repository is essentially a folder on the local hard disk which contains the "working directory" and the metadata folder.
The metadata folder is a dedicated child folder named ".git" and often referred to as ".git-folder". It contains the actual repository (i.e. the Commits, the References, the logs and such).

The metadata folder is totally transparent to the Git client, while the working directory is used to expose the currently checked out Repository content as files for tools and editors.

Typically, if these files are to be used in Eclipse, they must be imported into the Eclipse workspace in one way or another. In order to do so, the easiest way would be to check in .project files from which the "Import Existing Projects" wizard can create the projects easily. Thus in most cases, the structure of a Repository containing Eclipse projects would look similar to something like this:

See also the Using EGit with Github section.


My working directory is now c:\users\projectname\.git

You should have the content of that repo checked out in c:\users\projectname (in other words, you should have more than just the .git).

So then I try to import the project using the eclipse "import" option.
When I try to import selecting the option "Use the new projects wizard", the source code is not imported.

That is normal.

If I import selecting the option "Import as general project" the source code is imported but the created project created by Eclipse is not a java project.

Again normal.

When selecting the option "Use the new projects wizard" and creating a new java project using the wizard should'nt the code be automatically imported ?

No, that would only create an empty project.
If that project is created in c:\users\projectname, you can then declare the eisting source directory in that project.
Since it is defined in the same working directory than the Git repo, that project should then appear as "versioned".

You could also use the "Import existing project" option, if your GitHub repo had versioned the .project and .classpath file, but that may not be the case here.

Reliable way to convert a file to a byte[]

byte[] bytes = System.IO.File.ReadAllBytes(filename);

That should do the trick. ReadAllBytes opens the file, reads its contents into a new byte array, then closes it. Here's the MSDN page for that method.

Python loop for inside lambda

Since a for loop is a statement (as is print, in Python 2.x), you cannot include it in a lambda expression. Instead, you need to use the write method on sys.stdout along with the join method.

x = lambda x: sys.stdout.write("\n".join(x) + "\n")

Changing the highlight color when selecting text in an HTML text input

Try this code to use:

/* For Mozile Firefox Browser */

::-moz-selection { background-color: #4CAF50; }

/* For Other Browser*/
::selection { background-color: #4CAF50; }

How to redirect the output of a PowerShell to a file during its execution

If you want to do it from the command line and not built into the script itself, use:

.\myscript.ps1 | Out-File c:\output.csv

Pass variables by reference in JavaScript

There's actually a pretty sollution:

function updateArray(context, targetName, callback) {
    context[targetName] = context[targetName].map(callback);
}

var myArray = ['a', 'b', 'c'];
updateArray(this, 'myArray', item => {return '_' + item});

console.log(myArray); //(3) ["_a", "_b", "_c"]

Responsive design with media query : screen size?

Responsive Web design (RWD) is a Web design approach aimed at crafting sites to provide an optimal viewing experience

When you design your responsive website you should consider the size of the screen and not the device type. The media queries helps you do that.

If you want to style your site per device, you can use the user agent value, but this is not recommended since you'll have to work hard to maintain your code for new devices, new browsers, browsers versions etc while when using the screen size, all of this does not matter.

You can see some standard resolutions in this link.

BUT, in my opinion, you should first design your website layout, and only then adjust it with media queries to fit possible screen sizes.

Why? As I said before, the screen resolutions variety is big and if you'll design a mobile version that is targeted to 320px your site won't be optimized to 350px screens or 400px screens.

TIPS

  1. When designing a responsive page, open it in your desktop browser and change the width of the browser to see how the width of the screen affects your layout and style.
  2. Use percentage instead of pixels, it will make your work easier.

Example

I have a table with 5 columns. The data looks good when the screen size is bigger than 600px so I add a breakpoint at 600px and hides 1 less important column when the screen size is smaller. Devices with big screens such as desktops and tablets will display all the data, while mobile phones with small screens will display part of the data.


State of mind

Not directly related to the question but important aspect in responsive design. Responsive design also relate to the fact that the user have a different state of mind when using a mobile phone or a desktop. For example, when you open your bank's site in the evening and check your stocks you want as much data on the screen. When you open the same page in the your lunch break your probably want to see few important details and not all the graphs of last year.

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

I Solved this problem adding @Cascade to the @ManyToOne attribute.

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

@ManyToOne
@JoinColumn(name="BLOODGRUPID")
@Cascade({CascadeType.MERGE, CascadeType.SAVE_UPDATE})
private Bloodgroup bloodgroup;

JSON: why are forward slashes escaped?

I asked the same question some time ago and had to answer it myself. Here's what I came up with:

It seems, my first thought [that it comes from its JavaScript roots] was correct.

'\/' === '/' in JavaScript, and JSON is valid JavaScript. However, why are the other ignored escapes (like \z) not allowed in JSON?

The key for this was reading http://www.cs.tut.fi/~jkorpela/www/revsol.html, followed by http://www.w3.org/TR/html4/appendix/notes.html#h-B.3.2. The feature of the slash escape allows JSON to be embedded in HTML (as SGML) and XML.

How to Load Ajax in Wordpress

Firstly, you should read this page thoroughly http://codex.wordpress.org/AJAX_in_Plugins

Secondly, ajax_script is not defined so you should change to: url: ajaxurl. I don't see your function1() in the above code but you might already define it in other file.

And finally, learn how to debug ajax call using Firebug, network and console tab will be your friends. On the PHP side, print_r() or var_dump() will be your friends.

Unable to get provider com.google.firebase.provider.FirebaseInitProvider

In my case, the problem was solved by adding this line to the module build.gradle:

// ADD THIS AT THE BOTTOM

apply plugin: 'com.google.gms.google-services'

Source

What is the difference between char s[] and char *s?

C99 N1256 draft

There are two different uses of character string literals:

  1. Initialize char[]:

    char c[] = "abc";      
    

    This is "more magic", and described at 6.7.8/14 "Initialization":

    An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

    So this is just a shortcut for:

    char c[] = {'a', 'b', 'c', '\0'};
    

    Like any other regular array, c can be modified.

  2. Everywhere else: it generates an:

    So when you write:

    char *c = "abc";
    

    This is similar to:

    /* __unnamed is magic because modifying it gives UB. */
    static char __unnamed[] = "abc";
    char *c = __unnamed;
    

    Note the implicit cast from char[] to char *, which is always legal.

    Then if you modify c[0], you also modify __unnamed, which is UB.

    This is documented at 6.4.5 "String literals":

    5 In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence [...]

    6 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

6.7.8/32 "Initialization" gives a direct example:

EXAMPLE 8: The declaration

char s[] = "abc", t[3] = "abc";

defines "plain" char array objects s and t whose elements are initialized with character string literals.

This declaration is identical to

char s[] = { 'a', 'b', 'c', '\0' },
t[] = { 'a', 'b', 'c' };

The contents of the arrays are modifiable. On the other hand, the declaration

char *p = "abc";

defines p with type "pointer to char" and initializes it to point to an object with type "array of char" with length 4 whose elements are initialized with a character string literal. If an attempt is made to use p to modify the contents of the array, the behavior is undefined.

GCC 4.8 x86-64 ELF implementation

Program:

#include <stdio.h>

int main(void) {
    char *s = "abc";
    printf("%s\n", s);
    return 0;
}

Compile and decompile:

gcc -ggdb -std=c99 -c main.c
objdump -Sr main.o

Output contains:

 char *s = "abc";
8:  48 c7 45 f8 00 00 00    movq   $0x0,-0x8(%rbp)
f:  00 
        c: R_X86_64_32S .rodata

Conclusion: GCC stores char* it in .rodata section, not in .text.

Note however that the default linker script puts .rodata and .text in the same segment, which has execute but no write permission. This can be observed with:

readelf -l a.out

which contains:

 Section to Segment mapping:
  Segment Sections...
   02     .text .rodata

If we do the same for char[]:

 char s[] = "abc";

we obtain:

17:   c7 45 f0 61 62 63 00    movl   $0x636261,-0x10(%rbp)

so it gets stored in the stack (relative to %rbp).

MD5 is 128 bits but why is it 32 characters?

Those are hexidecimal digits, not characters. One digit = 4 bits.

unsigned int vs. size_t

The size_t type is the type returned by the sizeof operator. It is an unsigned integer capable of expressing the size in bytes of any memory range supported on the host machine. It is (typically) related to ptrdiff_t in that ptrdiff_t is a signed integer value such that sizeof(ptrdiff_t) and sizeof(size_t) are equal.

When writing C code you should always use size_t whenever dealing with memory ranges.

The int type on the other hand is basically defined as the size of the (signed) integer value that the host machine can use to most efficiently perform integer arithmetic. For example, on many older PC type computers the value sizeof(size_t) would be 4 (bytes) but sizeof(int) would be 2 (byte). 16 bit arithmetic was faster than 32 bit arithmetic, though the CPU could handle a (logical) memory space of up to 4 GiB.

Use the int type only when you care about efficiency as its actual precision depends strongly on both compiler options and machine architecture. In particular the C standard specifies the following invariants: sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) placing no other limitations on the actual representation of the precision available to the programmer for each of these primitive types.

Note: This is NOT the same as in Java (which actually specifies the bit precision for each of the types 'char', 'byte', 'short', 'int' and 'long').

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

sudo ln -sf /usr/lib/...."adapt-it"..../qt5/plugins/platforms/ /usr/bin/

It creates the symbolic link it's missed. Good for QT ! Good for VLC !!

Create a hidden field in JavaScript

You can use jquery for create element on the fly

$('#form').append('<input type="hidden" name="fieldname" value="fieldvalue" />');

or other way

$('<input>').attr({
    type: 'hidden',
    id: 'fieldId',
    name: 'fieldname'
}).appendTo('form')

What does <> mean?

Yes, it means "not equal", either less than or greater than. e.g

If x <> y Then

can be read as

if x is less than y or x is greater than y then

The logical outcome being "If x is anything except equal to y"

How to place object files in separate subdirectory

Since you're using GNUmake, use a pattern rule for compiling object files:

$(OBJDIR)/%.o: %.c
    $(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<

The controller for path was not found or does not implement IController

This error can also be caused by the fact that Controllers must have (in their name) the word Controller; viz: HomeController; unless you implement your own ControllerFactory.

How do I stop/start a scheduled task on a remote computer programmatically?

Here's what I found.

stop:

schtasks /end /s <machine name> /tn <task name>

start:

schtasks /run /s <machine name> /tn <task name>


C:\>schtasks /?

SCHTASKS /parameter [arguments]

Description:
    Enables an administrator to create, delete, query, change, run and
    end scheduled tasks on a local or remote system. Replaces AT.exe.

Parameter List:
    /Create         Creates a new scheduled task.

    /Delete         Deletes the scheduled task(s).

    /Query          Displays all scheduled tasks.

    /Change         Changes the properties of scheduled task.

    /Run            Runs the scheduled task immediately.

    /End            Stops the currently running scheduled task.

    /?              Displays this help message.

Examples:
    SCHTASKS
    SCHTASKS /?
    SCHTASKS /Run /?
    SCHTASKS /End /?
    SCHTASKS /Create /?
    SCHTASKS /Delete /?
    SCHTASKS /Query  /?
    SCHTASKS /Change /?

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression

Change it like this and it should work:

var key = item.Key.ToString();
IQueryable<entity> pages = from p in context.pages
                           where  p.Serial == key
                           select p;

The reason why the exception is not thrown in the line the LINQ query is declared but in the line of the foreach is the deferred execution feature, i.e. the LINQ query is not executed until you try to access the result. And this happens in the foreach and not earlier.

XPath: Get parent node from child node

Use the parent axes with the parent node's name.

//*[title="50"]/parent::store

This XPath will only select the parent node if it is a store.

But you can also use one of these

//*[title="50"]/parent::*
//*[title="50"]/..

These xpaths will select any parent node. So if the document changes you will always select a node, even if it is not the node you expect.

EDIT

What happens in the given example where the parent is a bicycle but the parent of the parent is a store?

Does it ascent?

No, it only selects the store if it is a parent of the node that matches //*[title="50"].

If not, is there a method to ascent in such cases and return None if there is no such parent?

Yes, you can use ancestor axes

//*[title="50"]/ancestor::store

This will select all ancestors of the node matching //*[title="50"] that are ` stores. E.g.

<data xmlns:d="defiant-namespace" d:mi="23">
    <store mi="1">
        <store mi="22">
            <book price="8.95" d:price="Number" d:mi="13">
                <title d:constr="String" d:mi="10">50</title>
                <category d:constr="String" d:mi="11">reference</category>
                <author d:constr="String" d:mi="12">Nigel Rees</author>
            </book>
        </store>
    </store>
</data>

XPath selection result

Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)

Go to "Window -> Preferences -> General -> C/C++ -> Code analysis" and disable "Syntax and Semantics Errors -> Abstract class cannot be instantiated"

How do I calculate the date in JavaScript three months prior to today?

_x000D_
_x000D_
var d = new Date("2013/01/01");_x000D_
console.log(d.toLocaleDateString());_x000D_
d.setMonth(d.getMonth() + 18);_x000D_
console.log(d.toLocaleDateString());
_x000D_
_x000D_
_x000D_

How do I get the name of the current executable in C#?

IF you are looking for the full path information of your executable, the reliable way to do it is to use the following:

   var executable = System.Diagnostics.Process.GetCurrentProcess().MainModule
                       .FileName.Replace(".vshost", "");

This eliminates any issues with intermediary dlls, vshost, etc.

How to get 'System.Web.Http, Version=5.2.3.0?

Install-Package Microsoft.AspNet.WebApi.Core -version 5.2.3

Then in the project Add Reference -> Browse. Push the browse button and go to the C:\Users\UserName\Documents\Visual Studio 2015\Projects\ProjectName\packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45 and add the needed .dll file

How can I compare time in SQL Server?

I believe you want to use DATEPART('hour', datetime).

Reference is here:

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

What are the minimum margins most printers can handle?

The margins vary depending on the printer. In Windows GDI, you call the following functions to get the built-in margins, the "no-print zone":

GetDeviceCaps(hdc, PHYSICALWIDTH);
GetDeviceCaps(hdc, PHYSICALHEIGHT);
GetDeviceCaps(hdc, PHYSICALOFFSETX);
GetDeviceCaps(hdc, PHYSICALOFFSETY);

Printing right to the edge is called a "bleed" in the printing industry. The only laser printer I ever knew to print right to the edge was the Xerox 9700: 120 ppm, $500K in 1980.

How to remove an element from an array in Swift

If you don't know the index of the element that you want to remove, and the element is conform the Equatable protocol, you can do:

animals.remove(at: animals.firstIndex(of: "dogs")!)

See Equatable protocol answer:How do I do indexOfObject or a proper containsObject

How do I get first name and last name as whole name in a MYSQL query?

rtrim(lastname)+','+rtrim(firstname) as [Person Name]
from Table

the result will show lastname,firstname as one column header !

Pointtype command for gnuplot

You first have to tell Gnuplot to use a style that uses points, e.g. with points or with linespoints. Try for example:

plot sin(x) with points

Output:

Now try:

plot sin(x) with points pointtype 5

Output:

You may also want to look at the output from the test command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:

How to upload files in asp.net core?

Fileservice.cs:

public class FileService : IFileService
{
    private readonly IWebHostEnvironment env;

    public FileService(IWebHostEnvironment env)
    {
        this.env = env;
    }

    public string Upload(IFormFile file)
    {
        var uploadDirecotroy = "uploads/";
        var uploadPath = Path.Combine(env.WebRootPath, uploadDirecotroy);

        if (!Directory.Exists(uploadPath))
            Directory.CreateDirectory(uploadPath);

        var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
        var filePath = Path.Combine(uploadPath, fileName);

        using (var strem = File.Create(filePath))
        {
            file.CopyTo(strem);
        }
        return fileName;
    }
}

IFileService:

namespace studentapps.Services
{
    public interface IFileService
    {
        string Upload(IFormFile file);
    }
}

StudentController:

[HttpGet]
public IActionResult Create()
{
    var student = new StudentCreateVM();
    student.Colleges = dbContext.Colleges.ToList();
    return View(student);
}

[HttpPost]
public IActionResult Create([FromForm] StudentCreateVM vm)
{
    Student student = new Student()
    {
        DisplayImage = vm.DisplayImage.FileName,
        Name = vm.Name,
        Roll_no = vm.Roll_no,
        CollegeId = vm.SelectedCollegeId,
    };


    if (ModelState.IsValid)
    {
        var fileName = fileService.Upload(vm.DisplayImage);
        student.DisplayImage = fileName;
        getpath = fileName;

        dbContext.Add(student);
        dbContext.SaveChanges();
        TempData["message"] = "Successfully Added";
    }
    return RedirectToAction("Index");
}

Quick way to create a list of values in C#?

A list of values quickly? Or even a list of objects!

I am just a beginner at the C# language but I like using

  • Hashtable
  • Arraylist
  • Datatable
  • Datasets

etc.

There's just too many ways to store items

How can I programmatically get the MAC address of an iphone


NOTE As of iOS7, you can no longer retrieve device MAC addresses. A fixed value will be returned rather than the actual MAC


Somthing I stumbled across a while ago. Originally from here I modified it a bit and cleaned things up.

IPAddress.h
IPAddress.c

And to use it

InitAddresses();
GetIPAddresses();
GetHWAddresses();

int i;
NSString *deviceIP = nil;
for (i=0; i<MAXADDRS; ++i)
{
    static unsigned long localHost = 0x7F000001;        // 127.0.0.1
    unsigned long theAddr;

    theAddr = ip_addrs[i];

    if (theAddr == 0) break;
    if (theAddr == localHost) continue;

    NSLog(@"Name: %s MAC: %s IP: %s\n", if_names[i], hw_addrs[i], ip_names[i]);

        //decided what adapter you want details for
    if (strncmp(if_names[i], "en", 2) == 0)
    {
        NSLog(@"Adapter en has a IP of %s", ip_names[i]);
    }
}

Adapter names vary depending on the simulator/device as well as wifi or cell on the device.

Are the days of passing const std::string & as a parameter over?

IMO using the C++ reference for std::string is a quick and short local optimization, while using passing by value could be (or not) a better global optimization.

So the answer is: it depends on circumstances:

  1. If you write all the code from the outside to the inside functions, you know what the code does, you can use the reference const std::string &.
  2. If you write the library code or use heavily library code where strings are passed, you likely gain more in global sense by trusting std::string copy constructor behavior.

Split a large pandas dataframe

I also experienced np.array_split not working with Pandas DataFrame my solution was to only split the index of the DataFrame and then introduce a new column with the "group" label:

indexes = np.array_split(df.index,N, axis=0)
for i,index in enumerate(indexes):
   df.loc[index,'group'] = i

This makes grouby operations very convenient for instance calculation of mean value of each group:

df.groupby(by='group').mean()

How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over

I've just bumped into this same problem when listening for onMouseLeave events on a disabled button. I worked around it by listening for the native mouseleave event on an element that wraps the disabled button.

componentDidMount() {
    this.watchForNativeMouseLeave();
},
componentDidUpdate() {
    this.watchForNativeMouseLeave();
},
// onMouseLeave doesn't work well on disabled elements
// https://github.com/facebook/react/issues/4251
watchForNativeMouseLeave() {
    this.refs.hoverElement.addEventListener('mouseleave', () => {
        if (this.props.disabled) {
            this.handleMouseOut();
        }
    });
},
render() {
    return (
        <span ref='hoverElement'
            onMouseEnter={this.handleMouseEnter}
            onMouseLeave={this.handleMouseLeave}
        >
            <button disabled={this.props.disabled}>Submit</button>
        </span>
    );
}

Here's a fiddle https://jsfiddle.net/qfLzkz5x/8/

Submit a form using jQuery

jQuery("a[id=atag]").click( function(){

    jQuery('#form-id').submit();      

            **OR**

    jQuery(this).parents("#form-id").submit();
});

How can I use Helvetica Neue Condensed Bold in CSS?

After a lot of fiddling, got it working (only tested in Webkit) using:

font-family: "HelveticaNeue-CondensedBold";

font-stretch was dropped between CSS2 and 2.1, though is back in CSS3, but is only supported in IE9 (never thought I'd be able to say that about any CSS prop!)

This works because I'm using the postscript name (find the font in Font Book, hit cmd+I), which is non-standard behaviour. It's probably worth using:

font-family: "HelveticaNeue-CondensedBold", "Helvetica Neue";

As a fallback, else other browsers might default to serif if they can't work it out.

Demo: http://jsfiddle.net/ndFTL/12/

Changing navigation title programmatically

Normally, the best-practice is to set the title on the UIViewController. By doing this, the UINavigationItem is also set. Generally, this is better than programmatically allocating and initializing a UINavigationBar that's not linked to anything.

You miss out on some of the benefits and functionality that the UINavigationBar was designed for. Here is a link to the documentation that may help you. It discusses the different properties you can set on the actual bar and on a UINavigationItem.

Just keep in mind:

  1. You lose back button functionality (unless you wire it yourself)
  2. The built-in "drag from the left-hand side to swipe back" gesture is forfeited

UINavigationController's are your friends.

Chrome violation : [Violation] Handler took 83ms of runtime

"Chrome violations" don't represent errors in either Chrome or your own web app. They are instead warnings to help you improve your app. In this case, Long running JavaScript and took 83ms of runtime are alerting you there's probably an opportunity to speed up your script.

("Violation" is not the best terminology; it's used here to imply the script "violates" a pre-defined guideline, but "warning" or similar would be clearer. These messages first appeared in Chrome in early 2017 and should ideally have a "More info" prompt to elaborate on the meaning and give suggested actions to the developer. Hopefully those will be added in the future.)

Using a dictionary to count the items in a list

in 2.7 and 3.1 there is special Counter dict for this purpose.

>>> from collections import Counter
>>> Counter(['apple','red','apple','red','red','pear'])
Counter({'red': 3, 'apple': 2, 'pear': 1})

Executing multiple SQL queries in one statement with PHP

Pass 65536 to mysql_connect as 5th parameter.

Example:

$conn = mysql_connect('localhost','username','password', true, 65536 /* here! */) 
    or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
    INSERT INTO table1 (field1,field2) VALUES(1,2);

    INSERT INTO table2 (field3,field4,field5) VALUES(3,4,5);

    DELETE FROM table3 WHERE field6 = 6;

    UPDATE table4 SET field7 = 7 WHERE field8 = 8;

    INSERT INTO table5
       SELECT t6.field11, t6.field12, t7.field13
       FROM table6 t6
       INNER JOIN table7 t7 ON t7.field9 = t6.field10;

    -- etc
");

When you are working with mysql_fetch_* or mysql_num_rows, or mysql_affected_rows, only the first statement is valid.

For example, the following codes, the first statement is INSERT, you cannot execute mysql_num_rows and mysql_fetch_*. It is okay to use mysql_affected_rows to return how many rows inserted.

$conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
    INSERT INTO table1 (field1,field2) VALUES(1,2);
    SELECT * FROM table2;
");

Another example, the following codes, the first statement is SELECT, you cannot execute mysql_affected_rows. But you can execute mysql_fetch_assoc to get a key-value pair of row resulted from the first SELECT statement, or you can execute mysql_num_rows to get number of rows based on the first SELECT statement.

$conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
    SELECT * FROM table2;
    INSERT INTO table1 (field1,field2) VALUES(1,2);
");

outline on only one border

Try with Shadow( Like border ) + Border

border-bottom: 5px solid #fff;
box-shadow: 0 5px 0 #ffbf0e;

git replacing LF with CRLF

git config core.autocrlf false

Construct pandas DataFrame from items in nested dictionary

So I used to use a for loop for iterating through the dictionary as well, but one thing I've found that works much faster is to convert to a panel and then to a dataframe. Say you have a dictionary d

import pandas as pd
d
{'RAY Index': {datetime.date(2014, 11, 3): {'PX_LAST': 1199.46,
'PX_OPEN': 1200.14},
datetime.date(2014, 11, 4): {'PX_LAST': 1195.323, 'PX_OPEN': 1197.69},
datetime.date(2014, 11, 5): {'PX_LAST': 1200.936, 'PX_OPEN': 1195.32},
datetime.date(2014, 11, 6): {'PX_LAST': 1206.061, 'PX_OPEN': 1200.62}},
'SPX Index': {datetime.date(2014, 11, 3): {'PX_LAST': 2017.81,
'PX_OPEN': 2018.21},
datetime.date(2014, 11, 4): {'PX_LAST': 2012.1, 'PX_OPEN': 2015.81},
datetime.date(2014, 11, 5): {'PX_LAST': 2023.57, 'PX_OPEN': 2015.29},
datetime.date(2014, 11, 6): {'PX_LAST': 2031.21, 'PX_OPEN': 2023.33}}}

The command

pd.Panel(d)
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 2 (major_axis) x 4 (minor_axis)
Items axis: RAY Index to SPX Index
Major_axis axis: PX_LAST to PX_OPEN
Minor_axis axis: 2014-11-03 to 2014-11-06

where pd.Panel(d)[item] yields a dataframe

pd.Panel(d)['SPX Index']
2014-11-03  2014-11-04  2014-11-05 2014-11-06
PX_LAST 2017.81 2012.10 2023.57 2031.21
PX_OPEN 2018.21 2015.81 2015.29 2023.33

You can then hit the command to_frame() to turn it into a dataframe. I use reset_index as well to turn the major and minor axis into columns rather than have them as indices.

pd.Panel(d).to_frame().reset_index()
major   minor      RAY Index    SPX Index
PX_LAST 2014-11-03  1199.460    2017.81
PX_LAST 2014-11-04  1195.323    2012.10
PX_LAST 2014-11-05  1200.936    2023.57
PX_LAST 2014-11-06  1206.061    2031.21
PX_OPEN 2014-11-03  1200.140    2018.21
PX_OPEN 2014-11-04  1197.690    2015.81
PX_OPEN 2014-11-05  1195.320    2015.29
PX_OPEN 2014-11-06  1200.620    2023.33

Finally, if you don't like the way the frame looks you can use the transpose function of panel to change the appearance before calling to_frame() see documentation here http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Panel.transpose.html

Just as an example

pd.Panel(d).transpose(2,0,1).to_frame().reset_index()
major        minor  2014-11-03  2014-11-04  2014-11-05  2014-11-06
RAY Index   PX_LAST 1199.46    1195.323     1200.936    1206.061
RAY Index   PX_OPEN 1200.14    1197.690     1195.320    1200.620
SPX Index   PX_LAST 2017.81    2012.100     2023.570    2031.210
SPX Index   PX_OPEN 2018.21    2015.810     2015.290    2023.330

Hope this helps.

Is there a GUI design app for the Tkinter / grid geometry?

You have VisualTkinter also known as Visual Python. Development seems not active. You have sourceforge and googlecode sites. Web site is here.

On the other hand, you have PAGE that seems active and works in python 2.7 and py3k

As you indicate on your comment, none of these use the grid geometry. As far as I can say the only GUI builder doing that could probably be Komodo Pro GUI Builder which was discontinued and made open source in ca. 2007. The code was located in the SpecTcl repository.

It seems to install fine on win7 although has not used it yet. This is an screenshot from my PC:

enter image description here

By the way, Rapyd Tk also had plans to implement grid geometry as in its documentation says it is not ready 'yet'. Unfortunately it seems 'nearly' abandoned.

Delete cookie by name?

In my case I used blow code for different environment.

  document.cookie = name +`=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;Domain=.${document.domain.split('.').splice(1).join('.')}`;

Best way to Format a Double value to 2 Decimal places

An alternative is to use String.format:

double[] arr = { 23.59004,
    35.7,
    3.0,
    9
};

for ( double dub : arr ) {
  System.out.println( String.format( "%.2f", dub ) );
}

output:

23.59
35.70
3.00
9.00

You could also use System.out.format (same method signature), or create a java.util.Formatter which works in the same way.

How to parse an RSS feed using JavaScript?

If you want to use a plain javascript API, there is a good example at https://github.com/hongkiat/js-rss-reader/

The complete description at https://www.hongkiat.com/blog/rss-reader-in-javascript/

It uses fetch method as a global method that asynchronously fetches a resource. Below is a snap of code:

fetch(websiteUrl).then((res) => {
  res.text().then((htmlTxt) => {
    var domParser = new DOMParser()
    let doc = domParser.parseFromString(htmlTxt, 'text/html')
    var feedUrl = doc.querySelector('link[type="application/rss+xml"]').href
  })
}).catch(() => console.error('Error in fetching the website'))

adb server version doesn't match this client

I beat my head against the wall on this one. This started happening when I installed the latest version of HTC sync (3.0.5579). For some reason adb.exe was showing up multiple times in the task manager and I was getting the adb server is out of date killing errors multiple times. I found the adb.exe version in the HTC sync directory and the Android SDK platform-tools directory. I had the path setup correctly pointing at the android SDK directory and didn't see the HTC Sync path (maybe I was missing something, but I don't think so). Anyway, to fix the issue, I simply renamed the adb.exe file in the HTC Sync directory and everything worked again. This may not be the right way to go about this fix, but it worked for me.

How to use a jQuery plugin inside Vue

Step 1 We place ourselves with the terminal in the folder of our project and install JQuery through npm or yarn.

npm install jquery --save

Step 2 Within our file where we want to use JQuery, for example app.js (resources/js/app.js), in the script section we include the following code.

// We import JQuery
const $ = require('jquery');
// We declare it globally
window.$ = $;

// You can use it now
$('body').css('background-color', 'orange');

// Here you can add the code for different plugins

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

The first part:

.Cells(.Rows.Count,"A")

Sends you to the bottom row of column A, which you knew already.

The End function starts at a cell and then, depending on the direction you tell it, goes that direction until it reaches the edge of a group of cells that have text. Meaning, if you have text in cells C4:E4 and you type:

Sheet1.Cells(4,"C").End(xlToRight).Select

The program will select E4, the rightmost cell with text in it.

In your case, the code is spitting out the row of the very last cell with text in it in column A. Does that help?

Word count from a txt file program

If you are using graphLab, you can use this function. It is really powerfull

products['word_count'] = graphlab.text_analytics.count_words(your_text)

Is it possible to remove the hand cursor that appears when hovering over a link? (or keep it set as the normal pointer)

That's exactly what cursor: pointer; is supposed to do.

If you want the cursor to remain normal, you should be using cursor: default

Android new Bottom Navigation bar or BottomNavigationView

I have referred this github post and I have set the three layouts for three fragment pages in bottom tab bar.

FourButtonsActivity.java:

bottomBar.setFragmentItems(getSupportFragmentManager(), R.id.fragmentContainer,
            new BottomBarFragment(LibraryFragment.newInstance(R.layout.library_fragment_layout), R.drawable.ic_update_white_24dp, "Recents"),
            new BottomBarFragment(PhotoEffectFragment.newInstance(R.layout.photo_effect_fragment), R.drawable.ic_local_dining_white_24dp, "Food"),
            new BottomBarFragment(VideoFragment.newInstance(R.layout.video_layout), R.drawable.ic_favorite_white_24dp, "Favorites")

    );

To set the badge count :

  BottomBarBadge unreadMessages = bottomBar.makeBadgeForTabAt(1, "#E91E63", 4);
  unreadMessages.show();
  unreadMessages.setCount(4);
  unreadMessages.setAnimationDuration(200);
  unreadMessages.setAutoShowAfterUnSelection(true);

LibraryFragment.java:

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class LibraryFragment extends Fragment {
    private static final String STARTING_TEXT = "Four Buttons Bottom Navigation";

    public LibraryFragment() {
    }

    public static LibraryFragment newInstance(int resource) {
        Bundle args = new Bundle();
        args.putInt(STARTING_TEXT, resource);

        LibraryFragment sampleFragment = new LibraryFragment();
        sampleFragment.setArguments(args);

        return sampleFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


        View view = LayoutInflater.from(getActivity()).inflate(
                getArguments().getInt(STARTING_TEXT), null);
        return view;


    }

Hibernate Error: a different object with the same identifier value was already associated with the session

This means you are trying to save multiple rows in your table with the reference to the same object.

check your Entity Class' id property.

@Id
private Integer id;

to

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique = true, nullable = false)
private Integer id;

How to print a percentage value in python?

Just for the sake of completeness, since I noticed no one suggested this simple approach:

>>> print("%.0f%%" % (100 * 1.0/3))
33%

Details:

  • %.0f stands for "print a float with 0 decimal places", so %.2f would print 33.33
  • %% prints a literal %. A bit cleaner than your original +'%'
  • 1.0 instead of 1 takes care of coercing the division to float, so no more 0.0

how to convert long date value to mm/dd/yyyy format

Refer below code for formatting date

long strDate1 = 1346524199000;
Date date=new Date(strDate1);

try {
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
        SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
        date = df2.format(format.parse("yourdate");
    } catch (java.text.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

For Android 6.0 at least, the ARM Translation thing is apparently unnecessary.

Just grab an x86 + Android 6.0 package (nano is fine) from OpenGApps and install by dragging-and-dropping and telling it to flash.

It seems the ARM translation thing was previously required, before the x86 package was available. You might still need the ARM translation if you want to install ARM-only apps though.

PHP parse/syntax errors; and how to solve them

Unexpected '='

This can be caused by having invalid characters in a variable name. Variables names must follow these rules:

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

mysql datatype for telephone number and address

I usually store phone numbers as a BIGINT in E164 format.

E164 never start with a 0, with the first few digits being the country code.

+441234567890
+44 (0)1234 567890
01234 567890

etc. would be stored as 441234567890.

Cast Double to Integer in Java

Simply do it this way...

Double d = 13.5578;
int i = d.intValue();
System.out.println(i);

How to use the ConfigurationManager.AppSettings

Your web.config file should have this structure:

<configuration>
    <connectionStrings>
        <add name="MyConnectionString" connectionString="..." />
    </connectionStrings>
</configuration>

Then, to create a SQL connection using the connection string named MyConnectionString:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);

If you'd prefer to keep your connection strings in the AppSettings section of your configuration file, it would look like this:

<configuration>
    <appSettings>
        <add key="MyConnectionString" value="..." />
    </appSettings>
</configuration>

And then your SqlConnection constructor would look like this:

SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyConnectionString"]);

Why does DEBUG=False setting make my django Static Files Access fail?

Just open your project urls.py, then find this if statement.

if settings.DEBUG:
    urlpatterns += patterns(
        'django.views.static',
        (r'^media/(?P<path>.*)','serve',{'document_root': settings.MEDIA_ROOT}), )

You can change settings.DEBUG on True and it will work always. But if your project is a something serious then you should to think about other solutions mentioned above.

if True:
    urlpatterns += patterns(
        'django.views.static',
        (r'^media/(?P<path>.*)','serve',{'document_root': settings.MEDIA_ROOT}), )

In django 1.10 you can write so:

urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, { 'document_root': settings.MEDIA_ROOT, }), url(r'^static/(?P<path>.*)$', serve, { 'document_root': settings.STATIC_ROOT }), ]

How can I divide one column of a data frame through another?

Hadley Wickham

dplyr

packages is always a saver in case of data wrangling. To add the desired division as a third variable I would use mutate()

d <- mutate(d, new = min / count2.freq)

Bootstrap 3 Multi-column within a single ul not floating properly

you are thinking too much... Take a look at this [i think this is what you wanted - if not let me know]

http://www.bootply.com/118886

css

.even{background: red; color:white;}
.odd{background: darkred; color:white;}

html

<div class="container">
  <ul class="list-unstyled">
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
  </ul>
</div>

Preferred method to store PHP arrays (json_encode vs serialize)

Y just tested serialized and json encode and decode, plus the size it will take the string stored.

JSON encoded in 0.067085981369 seconds. Size (1277772)
PHP serialized in 0.12110209465 seconds. Size (1955548)
JSON decode in 0.22470498085 seconds
PHP serialized in 0.211947917938 seconds
json_encode() was roughly 80.52% faster than serialize()
unserialize() was roughly 6.02% faster than json_decode()
JSON string was roughly 53.04% smaller than Serialized string

We can conclude that JSON encodes faster and results a smaller string, but unserialize is faster to decode the string.

What is a .NET developer?

CLR, BCL and C#/VB.Net, ADO.NET, WinForms and/or ASP.NET. Most of the places that require additional .Net technologies, like WPF or WCF will call it out explicitly.

Spring Test & Security: How to mock authentication?

Pretty Late answer though. But This has worked for me , and could be useful.

While Using Spring Security ans mockMvc, all you need to is use @WithMockUser annotation like others are mentioned.

Spring security also provides another annotation called @WithAnonymousUser for testing unauthenticated requests. However you should be careful here. You would be expecting 401, but I got 403 Forbidden Error by default. In actual scenarios, when you are running actual service, It is redirected and you end up getting the correct 401 response code.Use this annotation for anonymous requests.

You may also think of ommitting the annotaions and simply keep it unauthorized. But this usually raises the correct exceptions(like AuthenticationException), but you will get correct status code if it is handled correctly(If you are using custom handler). I used to get 500 for this. So look for the exceptions raised in the debugger, and check if it is handled rightly and returns the correct status code.

What's "this" in JavaScript onclick?

Here (this) is a object which contains all features/properties of the dom element. you can see by

console.log(this);

This will display all attributes properties of the dom element with hierarchy. You can manipulate the dom element by this.

Also describe on the below link:-

http://www.quirksmode.org/js/this.html

JSON Structure for List of Objects

As others mentioned, Justin's answer was close, but not quite right. I tested this using Visual Studio's "Paste JSON as C# Classes"

{
    "foos" : [
        {
            "prop1":"value1",
            "prop2":"value2"
        },
        {
            "prop1":"value3", 
            "prop2":"value4"
        }
    ]
}

How to stop/cancel 'git log' command in terminal?

You can hit the key q (for quit) and it should take you to the prompt.

Please see this link.

how to add value to a tuple?

I was going through some details related to tuple and list, and what I understood is:

  • Tuples are Heterogeneous collection data type
  • Tuple has Fixed length (per tuple type)
  • Tuple are Always finite

So for appending new item to a tuple, need to cast it to list, and do append() operation on it, then again cast it back to tuple.

But personally what I felt about the Question is, if Tuples are supposed to be finite, fixed length items and if we are using those data types in our application logics then there should not be a scenario to appending new items OR updating an item value in it. So instead of list of tuples it should be list of list itself, Am I right on this?

How do I list all tables in all databases in SQL Server in a single result set?

I think the common approach is to SELECT * FROM INFORMATION_SCHEMA.TABLES for each database using sp_MSforeachdb

I created a snippet in VS Code that I think it might be helpful.

Query

IF OBJECT_ID('tempdb..#alltables', 'U') IS NOT NULL DROP TABLE #alltables;
SELECT * INTO #alltables FROM INFORMATION_SCHEMA.TABLES;
TRUNCATE TABLE #alltables;
EXEC sp_MSforeachdb 'USE [?];INSERT INTO #alltables SELECT * from INFORMATION_SCHEMA.TABLES';
SELECT * FROM #alltables WHERE TABLE_NAME LIKE '%<TABLE_NAME_TO_SEARCH>%';
GO 

Snippet

{
    "List all tables": {
        "prefix": "sqlListTable",
        "body": [
            "IF OBJECT_ID('tempdb..#alltables', 'U') IS NOT NULL DROP TABLE #alltables;",
            "SELECT * INTO #alltables FROM INFORMATION_SCHEMA.TABLES;",
            "TRUNCATE TABLE #alltables;",
            "EXEC sp_MSforeachdb 'USE [?];INSERT INTO #alltables SELECT * from INFORMATION_SCHEMA.TABLES';",
            "SELECT * FROM #alltables WHERE TABLE_NAME LIKE '%$0%';",
            "GO"
        ]
    }
}

$(...).datepicker is not a function - JQuery - Bootstrap

You can try the following and it worked for me.

Import following scripts and css files as there are used by the date picker.

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

The JS coding for the Date Picker I use.

<script>
        $(document).ready(function(){
            // alert ('Cliecked');
            var date_input=$('input[name="orangeDateOfBirthForm"]'); //our date input has the name "date"
            var container=$('.bootstrap-iso form').length>0 ? $('.bootstrap-iso form').parent() : "body";
            var options={
                format: 'dd/mm/yyyy', //format of the date
                container: container,
                changeYear: true, // you can change the year as you need
                changeMonth: true, // you can change the months as you need
                todayHighlight: true,
                autoclose: true,
                yearRange: "1930:2100" // the starting to end of year range 
            };
            date_input.datepicker(options);
        });
    </script>

The HTML Coding:

 <input type="text" id="orangeDateOfBirthForm" name="orangeDateOfBirthForm" class="form-control validate" required>
 <label data-error="wrong" data-success="right" for="orangeForm-email">Date of Birth</label>

Should I use JSLint or JSHint JavaScript validation?

Foreword: Well, that escalated quickly. But decided to pull it through. May this answer be helpful to you and other readers.

I got a bit carried away here

Code Hinting

While JSLint and JSHint are good tools to use, over the years I've come to appreciate what my friend @ugly_syntax calls:

smaller design space.

This is a general principle, much like a "zen monk", limiting the choices one has to make, one can be more productive and creative.

Therefore my current favourite zero-config JS code style:

StandardJS.

UPDATE:

Flow has improved a lot. With it, you can add types to your JS with will help you prevent a lot of bugs. But it can also stay out of your way, for instance when interfacing untyped JS. Give it a try!

Quickstart / TL;DR

Add standard as a dependency to you project

npm install --save standard

Then in package.json, add the following test script:

"scripts": {
    "test": "node_modules/.bin/standard && echo put further tests here"
},

For snazzier output while developing, npm install --global snazzy and run it instead of npm test.

Note: Type checking versus Heuristics

My friend when mentioning design space referred to Elm and I encourage you to give that language a try.

Why? JS is in fact inspired by LISP, which is a special class of languages, which happens to be untyped. Language such as Elm or Purescript are typed functional programming languages.

Type restrict your freedom in order for the compiler to be able to check and guide you when you end up violation the language or your own program's rules; regardless of the size (LOC) of your program.

We recently had a junior colleague implement a reactive interface twice: once in Elm, once in React; have a look to get some idea of what I'm talking about.

Compare Main.elm (typed) ? index.js (untyped, no tests)

(ps. note that the React code is not idiomatic and could be improved)

One final remark,

the reality is that JS is untyped. Who am I to suggest typed programming to you?

See, with JS we are in a different domain: freed from types, we can easily express things that are hard or impossible to give a proper type (which can certainly be an advantage).

But without types there is little to keep our programs in check, so we are forced to introduce tests and (to a lesser extend) code styles.

I recommend you look at LISP (e.g. ClojureScript) for inspiration and invest in testing your codes. Read The way of the substack to get an idea.

Peace.

Arrays vs Vectors: Introductory Similarities and Differences

Those reference pretty much answered your question. Simply put, vectors' lengths are dynamic while arrays have a fixed size. when using an array, you specify its size upon declaration:

int myArray[100];
myArray[0]=1;
myArray[1]=2;
myArray[2]=3;

for vectors, you just declare it and add elements

vector<int> myVector;
myVector.push_back(1);
myVector.push_back(2);
myVector.push_back(3);
...

at times you wont know the number of elements needed so a vector would be ideal for such a situation.

How to receive POST data in django

res = request.GET['paymentid'] will raise a KeyError if paymentid is not in the GET data.

Your sample php code checks to see if paymentid is in the POST data, and sets $payID to '' otherwise:

$payID = isset($_POST['paymentid']) ? $_POST['paymentid'] : ''

The equivalent in python is to use the get() method with a default argument:

payment_id = request.POST.get('payment_id', '')

while debugging, this is what I see in the response.GET: <QueryDict: {}>, request.POST: <QueryDict: {}>

It looks as if the problem is not accessing the POST data, but that there is no POST data. How are you are debugging? Are you using your browser, or is it the payment gateway accessing your page? It would be helpful if you shared your view.

Once you are managing to submit some post data to your page, it shouldn't be too tricky to convert the sample php to python.

How to suspend/resume a process in Windows?

I use (a very old) process explorer from SysInternals (procexp.exe). It is a replacement / addition to the standard Task manager, you can suspend a process from there.

Edit: Microsoft has bought over SysInternals, url: procExp.exe

Other than that you can set the process priority to low so that it does not get in the way of other processes, but this will not suspend the process.

How do I execute external program within C code in linux with arguments?

For a simple way, use system():

#include <stdlib.h>
...
int status = system("./foo 1 2 3");

system() will wait for foo to complete execution, then return a status variable which you can use to check e.g. exitcode (the command's exitcode gets multiplied by 256, so divide system()'s return value by that to get the actual exitcode: int exitcode = status / 256).

The manpage for wait() (in section 2, man 2 wait on your Linux system) lists the various macros you can use to examine the status, the most interesting ones would be WIFEXITED and WEXITSTATUS.

Alternatively, if you need to read foo's standard output, use popen(3), which returns a file pointer (FILE *); interacting with the command's standard input/output is then the same as reading from or writing to a file.

Command-line tool for finding out who is locking a file

In my case Handle.exe did not help. Simple program from official Microsoft called Process Explorer was useful. Just open as administrator and press Ctrl+f, type part of file name it will show process using file.

Git: add vs push vs commit

Very nice pdf about many GIT secrets.

Add is same as svn's add (how ever sometimes it is used to mark file resolved).

Commit also is same as svn's , but it commit change into your local repository.

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

Adding the following two lines at the top of my .py script worked for me (first line was necessary):

#!/usr/bin/env python
# -*- coding: utf-8 -*- 

Show Error on the tip of the Edit Text Android

private void showError() {
   mEditText.setError("Password and username didn't match");
}

Which will result in errors shown like this:

enter image description here

And if you want to remove it:

 textView.setError(null);

jQuery.ajax returns 400 Bad Request

Add this to your ajax call:

contentType: "application/json; charset=utf-8",
dataType: "json"

Calculate mean across dimension in a 2D array

Here is a non-numpy solution:

>>> a = [[40, 10], [50, 11]]
>>> [float(sum(l))/len(l) for l in zip(*a)]
[45.0, 10.5]

Appending the same string to a list of strings in Python

list2 = ['%sbar' % (x,) for x in list]

And don't use list as a name; it shadows the built-in type.

How do I create a comma-separated list using a SQL query?

I believe what you want is:

SELECT ItemName, GROUP_CONCAT(DepartmentId) FROM table_name GROUP BY ItemName

If you're using MySQL

Reference

installing JDK8 on Windows XP - advapi32.dll error

Oracle has announced fix for Windows XP installation error

Oracle has decided to fix Windows XP installation. As of the JRE 8u25 release in 10/15/2014 the code of the installer has been changes so that installation on Windows XP is again possible.

However, this does not mean that Oracle is continuing to support Windows XP. They make no guarantee about current and future releases of JRE8 being compatible with Windows XP. It looks like it's a run at your own risk kind of thing.

See the Oracle blog post here.

You can get the latest JRE8 right off the Oracle downloads site.

ERROR 1130 (HY000): Host '' is not allowed to connect to this MySQL server

mysql> CREATE USER 'name'@'%' IDENTIFIED BY 'passWord'; Query OK, 0 rows affected (0.00 sec)

mysql> GRANT ALL PRIVILEGES ON . TO 'name'@'%'; Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec)

mysql>

  1. Make sure you have your name and % the right way round
  2. Makes sure you have added your port 3306 to any firewall you may be running (although this will give a different error message)

hope this helps someone...

JavaScript, Node.js: is Array.forEach asynchronous?

This is a short asynchronous function to use without requiring third party libs

Array.prototype.each = function (iterator, callback) {
    var iterate = function () {
            pointer++;
            if (pointer >= this.length) {
                callback();
                return;
            }
            iterator.call(iterator, this[pointer], iterate, pointer);
    }.bind(this),
        pointer = -1;
    iterate(this);
};

How can I copy a file on Unix using C?

There is no baked-in equivalent CopyFile function in the APIs. But sendfile can be used to copy a file in kernel mode which is a faster and better solution (for numerous reasons) than opening a file, looping over it to read into a buffer, and writing the output to another file.

Update:

As of Linux kernel version 2.6.33, the limitation requiring the output of sendfile to be a socket was lifted and the original code would work on both Linux and — however, as of OS X 10.9 Mavericks, sendfile on OS X now requires the output to be a socket and the code won't work!

The following code snippet should work on the most OS X (as of 10.5), (Free)BSD, and Linux (as of 2.6.33). The implementation is "zero-copy" for all platforms, meaning all of it is done in kernelspace and there is no copying of buffers or data in and out of userspace. Pretty much the best performance you can get.

#include <fcntl.h>
#include <unistd.h>
#if defined(__APPLE__) || defined(__FreeBSD__)
#include <copyfile.h>
#else
#include <sys/sendfile.h>
#endif

int OSCopyFile(const char* source, const char* destination)
{    
    int input, output;    
    if ((input = open(source, O_RDONLY)) == -1)
    {
        return -1;
    }    
    if ((output = creat(destination, 0660)) == -1)
    {
        close(input);
        return -1;
    }

    //Here we use kernel-space copying for performance reasons
#if defined(__APPLE__) || defined(__FreeBSD__)
    //fcopyfile works on FreeBSD and OS X 10.5+ 
    int result = fcopyfile(input, output, 0, COPYFILE_ALL);
#else
    //sendfile will work with non-socket output (i.e. regular file) on Linux 2.6.33+
    off_t bytesCopied = 0;
    struct stat fileinfo = {0};
    fstat(input, &fileinfo);
    int result = sendfile(output, input, &bytesCopied, fileinfo.st_size);
#endif

    close(input);
    close(output);

    return result;
}

EDIT: Replaced the opening of the destination with the call to creat() as we want the flag O_TRUNC to be specified. See comment below.

Convert Java Date to UTC String

Why not just use java.text.SimpleDateFormat ?

Date someDate = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String s = df.format(someDate);

Or see: http://www.tutorialspoint.com/java/java_date_time.htm

Get ID of element that called a function

Pass a reference to the element into the function when it is called:

<area id="nose" onmouseover="zoom(this);" />

<script>
  function zoom(ele) {
    var id = ele.id;

    console.log('area element id = ' + id);
  }
</script>

MySQL: Large VARCHAR vs. TEXT?

Can you predict how long the user input would be?

VARCHAR(X)

Max Length: variable, up to 65,535 bytes (64KB)
Case: user name, email, country, subject, password


TEXT

Max Length: 65,535 bytes (64KB)
Case: messages, emails, comments, formatted text, html, code, images, links


MEDIUMTEXT

Max Length: 16,777,215 bytes (16MB)
Case: large json bodies, short to medium length books, csv strings


LONGTEXT

Max Length: 4,294,967,29 bytes (4GB)
Case: textbooks, programs, years of logs files, harry potter and the goblet of fire, scientific research logging

There's more information on this question.

Double precision - decimal places

A double holds 53 binary digits accurately, which is ~15.9545898 decimal digits. The debugger can show as many digits as it pleases to be more accurate to the binary value. Or it might take fewer digits and binary, such as 0.1 takes 1 digit in base 10, but infinite in base 2.

This is odd, so I'll show an extreme example. If we make a super simple floating point value that holds only 3 binary digits of accuracy, and no mantissa or sign (so range is 0-0.875), our options are:

binary - decimal
000    - 0.000
001    - 0.125
010    - 0.250
011    - 0.375
100    - 0.500
101    - 0.625
110    - 0.750
111    - 0.875

But if you do the numbers, this format is only accurate to 0.903089987 decimal digits. Not even 1 digit is accurate. As is easy to see, since there's no value that begins with 0.4?? nor 0.9??, and yet to display the full accuracy, we require 3 decimal digits.

tl;dr: The debugger shows you the value of the floating point variable to some arbitrary precision (19 digits in your case), which doesn't necessarily correlate with the accuracy of the floating point format (17 digits in your case).

Install .ipa to iPad with or without iTunes

If you built the IPA using PhoneGap Build online you can download and install the IPA directly on your Ipad/Iphone by opening build.phonegap.com in Safari on the device, logging in and then clicking the iOS tab (the download ipa button). You will then be asked to install the app you built.

Direct link to this after logging in is: https://build.phonegap.com/apps/YOUR-BUILD-NUMBER/download/ios

How to set radio button selected value using jquery

A clean approach I find is by giving an ID for each radio button and then setting it by using the following statement:

document.getElementById('publicedit').checked = true;

jQuery: get parent tr for selected radio button

Try this.

You don't need to prefix attribute name by @ in jQuery selector. Use closest() method to get the closest parent element matching the selector.

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');

You can simplify your method like this

function getSelectedRowGuid() {
    return GetRowGuid(
      $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}

closest() - Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.

selected value get from db into dropdown select box option using php mysql error

for example ..and please use mysqli() next time because mysql() is deprecated.

<?php
$select="select * from tbl_assign where id='".$_GET['uid']."'"; 
$q=mysql_query($select) or die($select);
$row=mysql_fetch_array($q);
?>

<select name="sclient" id="sclient" class="reginput"/>
<option value="">Select Client</option>
<?php $s="select * from tbl_new_user where type='client'";
$q=mysql_query($s) or die($s);
while($rw=mysql_fetch_array($q))
{ ?>
<option value="<?php echo $rw['login_name']; ?>"<?php if($row['clientname']==$rw['login_name']) echo 'selected="selected"'; ?>><?php echo $rw['login_name']; ?></option>
<?php } ?>
</select>

PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators

I really have the same problem, finally, i solved it.

its likey not the Swift Mail's problem. It's Yaml parser's problem. if your password only the digits, the password senmd to swift finally not the same one.

swiftmailer:
    transport:  smtp
    encryption: ssl
    auth_mode:  login
    host:       smtp.gmail.com
    username:   your_username
    password:   61548921

you need fix it with double quotes password: "61548921"

Get month name from Date

_x000D_
_x000D_
document.write(new Date().toLocaleString('en-us',{month:'long', year:'numeric', day:'numeric'}))
_x000D_
_x000D_
_x000D_

In c++ what does a tilde "~" before a function name signify?

That would be the destructor(freeing up any dynamic memory)

build maven project with propriatery libraries included

Possible solutions is put your dependencies in src/main/resources then in your pom :

<dependency>
groupId ...
artifactId ...
version ...
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/yourJar.jar</systemPath>
</dependency>

Note: system dependencies are not copied into resulted jar/war
(see How to include system dependencies in war built using maven)

How do I find which application is using up my port?

It may be possible that there is no other application running. It is possible that the socket wasn't cleanly shutdown from a previous session in which case you may have to wait for a while before the TIME_WAIT expires on that socket. Unfortunately, you won't be able to use the port till that socket expires. If you can start your server after waiting for a while (a few minutes) then the problem is not due to some other application running on port 8080.

working with negative numbers in python

How about something like that? (Uses no abs() nor mulitiplication)
Notes:

  • the abs() function is only used for the optimization trick. This snippet can either be removed or recoded.
  • the logic is less efficient since we're testing the sign of a and b with each iteration (price to pay to avoid both abs() and multiplication operator)

def multiply_by_addition(a, b):
""" School exercise: multiplies integers a and b, by successive additions.
"""
   if abs(a) > abs(b):
      a, b = b, a     # optimize by reducing number of iterations
   total = 0
   while a != 0:
      if a > 0:
         a -= 1
         total += b
      else:
         a += 1
         total -= b
   return total

multiply_by_addition(2,3)
6
multiply_by_addition(4,3)
12
multiply_by_addition(-4,3)
-12
multiply_by_addition(4,-3)
-12
multiply_by_addition(-4,-3)
12

Make a number a percentage

((portion/total) * 100).toFixed(2) + '%'

javascript set cookie with expire time

Your browser may be configured to accept only session cookies; if this is your case, any expiry time is transformed into session by your browser, you can change this setting of your browser or try another browser without such a configuration

Vertically align text within a div

Create a container for your text content, a span perhaps.

_x000D_
_x000D_
#column-content {_x000D_
  display: inline-block;_x000D_
}_x000D_
img {_x000D_
  vertical-align: middle;_x000D_
}_x000D_
span {_x000D_
  display: inline-block;_x000D_
  vertical-align: middle;_x000D_
}_x000D_
_x000D_
/* for visual purposes */_x000D_
#column-content {_x000D_
  border: 1px solid red;_x000D_
  position: relative;_x000D_
}
_x000D_
<div id="column-content">_x000D_
_x000D_
  <img src="http://i.imgur.com/WxW4B.png">_x000D_
  <span><strong>1234</strong>_x000D_
    yet another text content that should be centered vertically</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

JSFiddle

How to programmatically close a JFrame

Exiting from Java running process is very easy, basically you need to do just two simple things:

  1. Call java method System.exit(...) at at application's quit point. For example, if your application is frame based, you can add listener WindowAdapter and and call System.exit(...) inside its method windowClosing(WindowEvent e).

Note: you must call System.exit(...) otherwise your program is error involved.

  1. Avoiding unexpected java exceptions to make sure the exit method can be called always. If you add System.exit(...) at right point, but It does not mean that the method can be called always, because unexpected java exceptions may prevent the method from been called.

This is strongly related to your programming skills.

** Following is a simplest sample (JFrame based) which shows you how to call exit method

import java.awt.event.*;
import javax.swing.*;

public class ExitApp extends JFrame
{
   public ExitApp()
   {
      addWindowListener(new WindowAdapter()
      {
         public void windowClosing(WindowEvent e)
         {
           dispose();
           System.exit(0); //calling the method is a must
         }
      });
   }

   public static void main(String[] args)
   {
      ExitApp app=new ExitApp();
      app.setBounds(133,100,532,400);
      app.setVisible(true);
   }
}

Set div height to fit to the browser using CSS

I think the fastest way is to use grid system with fractions. So your container have 100vw, which is 100% of the window width and 100vh which is 100% of the window height.

Using fractions or 'fr' you can choose the width you like. the sum of the fractions equals to 100%, in this example 4fr. So the first part will be 1fr (25%) and the seconf is 3fr (75%)

More about fr units here.

_x000D_
_x000D_
.container{
  width: 100vw;
  height:100vh; 
  display: grid;
  grid-template-columns: 1fr 3fr;
}

/*You don't need this*/
.div1{
  background-color: yellow;
}

.div2{
  background-color: red;
}
_x000D_
<div class='container'>
  <div class='div1'>This is div 1</div>
  <div class='div2'>This is div 2</div>
</div>
_x000D_
_x000D_
_x000D_

Unresolved external symbol in object files

I had the same link errors, but from a test project which was referencing another dll. Found out that after adding _declspec(dllexport) in front of each function which was specified in the error message, the link was working well.

H2 in-memory database. Table not found

I have tried adding ;DATABASE_TO_UPPER=false parameter, which it did work a single test, but what did the trick for me was ;CASE_INSENSITIVE_IDENTIFIERS=TRUE.

At the I had: jdbc:h2:mem:testdb;CASE_INSENSITIVE_IDENTIFIERS=TRUE

Moreover, the problem for me was when I upgraded to Spring Boot 2.4.1.

PHP header() redirect with POST variables

It would be beneficial to verify the form's data before sending it via POST. You should create a JavaScript function to check the form for errors and then send the form. This would prevent the data from being sent over and over again, possibly slowing the browser and using transfer volume on the server.

Edit:

If security is a concern, performing an AJAX request to verify the data would be the best way. The response from the AJAX request would determine whether the form should be submitted.

Determine version of Entity Framework I am using?

If you open the references folder and locate system.data.entity, click the item, then check the runtime version number in the Properties explorer, you will see the sub version as well. Mine for instance shows v4.0.30319 with the Version property showing 4.0.0.0.

How do I change the text of a span element using JavaScript?

Like in other answer, innerHTML and innerText are not recommended, it's better use textContent. This attribute is well supported, you can check it this: http://caniuse.com/#search=textContent

How to get Top 5 records in SqLite?

select price from mobile_sales_details order by price desc limit 5

Note: i have mobile_sales_details table

syntax

select column_name from table_name order by column_name desc limit size.  

if you need top low price just remove the keyword desc from order by

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

This is likely because you haven't set your compileSdkVersion to 21 in your build.gradle file. You also probably want to change your targetSdkVersion to 21.

android {
    //...
    compileSdkVersion 21

    defaultConfig {
        targetSdkVersion 21
    }
    //...
}

This requires you to have downloaded the latest SDK updates to begin with.

Android Studio SDK Manager

Once you've downloaded all the updates (don't forget to also update the Android Support Library/Repository, too!) and updated your compileSdkVersion, re-sync your Gradle project.

Edit: For Eclipse or general IntelliJ users

See reVerse's answer. He has a very thorough walk through!

set column width of a gridview in asp.net

<asp:GridView ID="GridView1" runat="server">
    <HeaderStyle Width="10%" />
    <RowStyle Width="10%" />
    <FooterStyle Width="10%" />
    <Columns>
        <asp:BoundField HeaderText="Name" DataField="LastName" 
            HeaderStyle-Width="10%" ItemStyle-Width="10%"
            FooterStyle-Width="10%" />
    </Columns>
</asp:GridView>

lambda expression for exists within list

var query = list.Where(r => listofIds.Any(id => id == r.Id));

Another approach, useful if the listOfIds array is large:

HashSet<int> hash = new HashSet<int>(listofIds);
var query = list.Where(r => hash.Contains(r.Id));

How to convert entire dataframe to numeric while preserving decimals?

Using dplyr (a bit like sapply..)

df2 <- mutate_all(df1, function(x) as.numeric(as.character(x)))

which gives:

glimpse(df2)
Observations: 4
Variables: 2
$ a <dbl> 0.01, 0.02, 0.03, 0.04
$ b <dbl> 2, 4, 5, 7

from your df1 which was:

glimpse(df1)
Observations: 4
Variables: 2
$ a <fctr> 0.01, 0.02, 0.03, 0.04
$ b <dbl> 2, 4, 5, 7

vuejs update parent data from child component

Another way is to pass a reference of your setter from the parent as a prop to the child component, similar to how they do it in React. Say, you have a method updateValue on the parent to update the value, you could instantiate the child component like so: <child :updateValue="updateValue"></child>. Then on the child you will have a corresponding prop: props: {updateValue: Function}, and in the template call the method when the input changes: <input @input="updateValue($event.target.value)">.

correct way of comparing string jquery operator =

NO, when you are using only one "=" you are assigning the variable.

You must use "==" : You must use "===" :

if (somevar === '836e3ef9-53d4-414b-a401-6eef16ac01d6'){
 $("#code").text(data.DATA[0].ID);
}

You could use fonction like .toLowerCase() to avoid case problem if you want

How can I check whether a radio button is selected with JavaScript?

HTML:

<label class="block"><input type="radio" name="calculation" value="add">+</label>
<label class="block"><input type="radio" name="calculation" value="sub">-</label>
<label class="block"><input type="radio" name="calculation" value="mul">*</label>
<label class="block"><input type="radio" name="calculation" value="div">/</label>

<p id="result"></p>

JAVAScript:

var options = document.getElementsByName("calculation");

for (var i = 0; i < options.length; i++) {
    if (options[i].checked) {
        // do whatever you want with the checked radio
        var calc = options[i].value;
        }
    }
    if(typeof calc == "undefined"){
        document.getElementById("result").innerHTML = " select the operation you want to perform";
        return false;
}

iOS 8 Snapshotting a view that has not been rendered results in an empty snapshot

Alternatively, consider using drawViewHierarchyInRect:

Swift:

extension UIImage{

    class func renderUIViewToImage(viewToBeRendered: UIView) -> UIImage
    {
        UIGraphicsBeginImageContextWithOptions(viewToBeRendered.bounds.size, true, 0.0)
        viewToBeRendered.drawViewHierarchyInRect(viewToBeRendered.bounds, afterScreenUpdates: true)
        viewToBeRendered.layer.renderInContext(UIGraphicsGetCurrentContext()!)

        let finalImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return finalImage
    }
}

Objective-C:

- (UIImage *)snapshot:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

Also see:

Squash the first two commits in Git?

You can use git filter-branch for that. e.g.

git filter-branch --parent-filter \
'if test $GIT_COMMIT != <sha1ofB>; then cat; fi'

This results in AB-C throwing away the commit log of A.

Excel VBA Macro: User Defined Type Not Defined

Sub DeleteEmptyRows()  

    Worksheets("YourSheetName").Activate
    On Error Resume Next
    Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

End Sub

The following code will delete all rows on a sheet(YourSheetName) where the content of Column A is blank.

EDIT: User Defined Type Not Defined is caused by "oTable As Table" and "oRow As Row". Replace Table and Row with Object to resolve the error and make it compile.

Returning value from Thread

If you want the value from the calling method, then it should wait for the thread to finish, which makes using threads a bit pointless.

To directly answer you question, the value can be stored in any mutable object both the calling method and the thread both have a reference to. You could use the outer this, but that isn't going to be particularly useful other than for trivial examples.

A little note on the code in the question: Extending Thread is usually poor style. Indeed extending classes unnecessarily is a bad idea. I notice you run method is synchronised for some reason. Now as the object in this case is the Thread you may interfere with whatever Thread uses its lock for (in the reference implementation, something to do with join, IIRC).

org.hibernate.PersistentObjectException: detached entity passed to persist

Here you have used native and assigning value to the primary key, in native primary key is auto generated.

Hence the issue is coming.

Using PropertyInfo to find out the property type

Use PropertyInfo.PropertyType to get the type of the property.

public bool ValidateData(object data)
{
    foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
    {
        if (propertyInfo.PropertyType == typeof(string))
        {
            string value = propertyInfo.GetValue(data, null);

            if value is not OK
            {
                return false;
            }
        }
    }            

    return true;
}

How to convert a double to long without casting?

The preferred approach should be:

Double.valueOf(d).longValue()

From the Double (Java Platform SE 7) documentation:

Double.valueOf(d)

Returns a Double instance representing the specified double value. If a new Double instance is not required, this method should generally be used in preference to the constructor Double(double), as this method is likely to yield significantly better space and time performance by caching frequently requested values.

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

How can I search an array in VB.NET?

It's not exactly clear how you want to search the array. Here are some alternatives:

Find all items containing the exact string "Ra" (returns items 2 and 3):

Dim result As String() = Array.FindAll(arr, Function(s) s.Contains("Ra"))

Find all items starting with the exact string "Ra" (returns items 2 and 3):

Dim result As String() = Array.FindAll(arr, Function(s) s.StartsWith("Ra"))

Find all items containing any case version of "ra" (returns items 0, 2 and 3):

Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().Contains("ra"))

Find all items starting with any case version of "ra" (retuns items 0, 2 and 3):

Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))

-

If you are not using VB 9+ then you don't have anonymous functions, so you have to create a named function.

Example:

Function ContainsRa(s As String) As Boolean
   Return s.Contains("Ra")
End Function

Usage:

Dim result As String() = Array.FindAll(arr, ContainsRa)

Having a function that only can compare to a specific string isn't always very useful, so to be able to specify a string to compare to you would have to put it in a class to have somewhere to store the string:

Public Class ArrayComparer

   Private _compareTo As String

   Public Sub New(compareTo As String)
      _compareTo = compareTo
   End Sub

   Function Contains(s As String) As Boolean
      Return s.Contains(_compareTo)
   End Function

   Function StartsWith(s As String) As Boolean
      Return s.StartsWith(_compareTo)
   End Function

End Class

Usage:

Dim result As String() = Array.FindAll(arr, New ArrayComparer("Ra").Contains)

Trying to make bootstrap modal wider

If you need this solution for only few types of modals just use style="width:90%" attribute.

example:

div class="modal-dialog modal-lg" style="width:90%"

note: this will change only this particular modal

How to temporarily exit Vim and go back

Assuming terminal Vim on a flavor of *nix:

To suspend your running Vim

Ctrl + Z

will suspend the process and get back to your shell

fg

will resume (bring to foreground) your suspended Vim.

To start a new shell

Start a subshell using:

:sh

(as configured by)

:set shell?

or

:!bash

followed by:

Ctrl+D (or exit, but why type so much?)

to kill the shell and return to Vim.

How to call a PHP file from HTML or Javascript


How to make a button call PHP?

I don't care if the page reloads or displays the results immediately;

Good!

Note: If you don't want to refresh the page see "Ok... but how do I Use Ajax anyway?" below.

I just want to have a button on my website make a PHP file run.

That can be done with a form with a single button:

<form action="">
  <input type="submit" value="my button"/>
</form>

That's it.

Pretty much. Also note that there are cases where ajax is really the way to go.

That depends on what you want. In general terms you only need ajax when you want to avoid realoading the page. Still you have said that you don't care about that.


Why I cannot call PHP directly from JavaScript?

If I can write the code inside HTML just fine, why can't I just reference the file for it in there or make a simple call for it in Javascript?

Because the PHP code is not in the HTML just fine. That's an illusion created by the way most server side scripting languages works (including PHP, JSP, and ASP). That code only exists on the server, and it is no reachable form the client (the browser) without a remote call of some sort.

You can see evidence of this if you ask your browser to show the source code of the page. There you will not see the PHP code, that is because the PHP code is not send to the client, therefore it cannot be executed from the client. That's why you need to do a remote call to be able to have the client trigger the execution of PHP code.

If you don't use a form (as shown above) you can do that remote call from JavaScript with a little thing called Ajax. You may also want to consider if what you want to do in PHP can be done directly in JavaScript.


How to call another PHP file?

Use a form to do the call. You can have it to direct the user to a particlar file:

<form action="myphpfile.php">
  <input type="submit" value="click on me!">
</form>

The user will end up in the page myphpfile.php. To make it work for the current page, set action to an empty string (which is what I did in the example I gave you early).

I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.

You want to make an operation on the server, you should make your form have the fields you need (even if type="hidden" and use POST):

<form action="" method="POST">
  <input type="text" value="default value, you can edit it" name="myfield">
  <input type="submit" value = "post">
</form>

What do I need to know about it to call a PHP file that will create a text file on a button press?

see: How to write into a file in PHP.


How do you recieve the data from the POST in the server?

I'm glad you ask... Since you are a newb begginer, I'll give you a little template you can follow:

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        //Ok we got a POST, probably from a FORM, read from $_POST.
        var_dump($_PSOT); //Use this to see what info we got!
    }
    else
    {
       //You could assume you got a GET
       var_dump($_GET); //Use this to see what info we got!
    }
 ?>
 <!DOCTYPE html>
 <html lang="en">
   <head>
     <meta char-set="utf-8">
     <title>Page title</title>
   </head>
   <body>
     <form action="" method="POST">
       <input type="text" value="default value, you can edit it" name="myfield">
       <input type="submit" value = "post">
     </form>
   </body>
 </html>

Note: you can remove var_dump, it is just for debugging purposes.


How do I...

I know the next stage, you will be asking how to:

  1. how to pass variables form a PHP file to another?
  2. how to remember the user / make a login?
  3. how to avoid that anoying message the appears when you reload the page?

There is a single answer for that: Sessions.

I'll give a more extensive template for Post-Redirect-Get

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        var_dump($_PSOT);
        //Do stuff...
        //Write results to session
        session_start();
        $_SESSION['stuff'] = $something;
        //You can store stuff such as the user ID, so you can remeember him.
        //redirect:
        header('Location: ', true, 303);
        //The redirection will cause the browser to request with GET
        //The results of the operation are in the session variable
        //It has empty location because we are redirecting to the same page
        //Otherwise use `header('Location: anotherpage.php', true, 303);`
        exit();
    }
    else
    {
        //You could assume you got a GET
        var_dump($_GET); //Use this to see what info we got!
        //Get stuff from session
        session_start();
        if (array_key_exists('stuff', $_SESSION))
        {
           $something = $_SESSION['stuff'];
           //we got stuff
           //later use present the results of the operation to the user.
        }
        //clear stuff from session:
        unset($_SESSION['stuff']);
        //set headers
        header('Content-Type: text/html; charset=utf-8');
        //This header is telling the browser what are we sending.
        //And it says we are sending HTML in UTF-8 encoding
    }
 ?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta char-set="utf-8">
    <title>Page title</title>
  </head>
  <body>
    <?php if (isset($something)){ echo '<span>'.$something.'</span>'}?>;
    <form action="" method="POST">
      <input type="text" value="default value, you can edit it" name="myfield">
      <input type="submit" value = "post">
    </form>
  </body>
</html>

Please look at php.net for any function call you don't recognize. Also - if you don't have already - get a good tutorial on HTML5.

Also, use UTF-8 because UTF-8!


Notes:

I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately.

If are you using a CMS (Codepress, Joomla, Drupal... etc)? That make put some contraints on how you got to do things.

Also, if you are using a framework, you should look at their documentation or ask at their forum/mailing list/discussion page/contact or try to ask the authors.


Ok... but how do I Use Ajax anyway?

Well... Ajax is made easy by some JavaScript libraries. Since you are a begginer, I'll recomend jQuery.

So, let's send something to the server via Ajax with jQuery, I'll use $.post instead of $.ajax for this example.

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        var_dump($_PSOT);
        header('Location: ', true, 303);
        exit();
    }
    else
    {
        var_dump($_GET);
        header('Content-Type: text/html; charset=utf-8');
    }
 ?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta char-set="utf-8">
    <title>Page title</title>
    <script>
        function ajaxmagic()
        {
            $.post(                             //call the server
                "test.php",                     //At this url
                {
                    field: "value",
                    name: "John"
                }                               //And send this data to it
            ).done(                             //And when it's done
                function(data)
                {
                    $('#fromAjax').html(data);  //Update here with the response
                }
            );
        }
    </script>
  </head>
  <body>
    <input type="button" value = "use ajax", onclick="ajaxmagic()">
    <span id="fromAjax"></span>
  </body>
</html>

The above code will send a POST request to the page test.php.

Note: You can mix sessions with ajax and stuff if you want.


How do I...

  1. How do I connect to the database?
  2. How do I prevent SQL injection?
  3. Why shouldn't I use Mysql_* functions?

... for these or any other, please make another questions. That's too much for this one.

Does Java have a path joining method?

This is a start, I don't think it works exactly as you intend, but it at least produces a consistent result.

import java.io.File;

public class Main
{
    public static void main(final String[] argv)
        throws Exception
    {
        System.out.println(pathJoin());
        System.out.println(pathJoin(""));
        System.out.println(pathJoin("a"));
        System.out.println(pathJoin("a", "b"));
        System.out.println(pathJoin("a", "b", "c"));
        System.out.println(pathJoin("a", "b", "", "def"));
    }

    public static String pathJoin(final String ... pathElements)
    {
        final String path;

        if(pathElements == null || pathElements.length == 0)
        {
            path = File.separator;
        }
        else
        {
            final StringBuilder builder;

            builder = new StringBuilder();

            for(final String pathElement : pathElements)
            {
                final String sanitizedPathElement;

                // the "\\" is for Windows... you will need to come up with the 
                // appropriate regex for this to be portable
                sanitizedPathElement = pathElement.replaceAll("\\" + File.separator, "");

                if(sanitizedPathElement.length() > 0)
                {
                    builder.append(sanitizedPathElement);
                    builder.append(File.separator);
                }
            }

            path = builder.toString();
        }

        return (path);
    }
}

How to search for a string in text files?

found = False
def check():
datafile = file('example.txt')
for line in datafile:
    if "blabla" in line:
        found = True
        break
return found

if check():
    print "found"
else:
    print "not found"

How can I make my own event in C#?

I have a full discussion of events and delegates in my events article. For the simplest kind of event, you can just declare a public event and the compiler will create both an event and a field to keep track of subscribers:

public event EventHandler Foo;

If you need more complicated subscription/unsubscription logic, you can do that explicitly:

public event EventHandler Foo
{
    add
    {
        // Subscription logic here
    }
    remove
    {
        // Unsubscription logic here
    }
}

What's the difference between a Python module and a Python package?

First, keep in mind that, in its precise definition, a module is an object in the memory of a Python interpreter, often created by reading one or more files from disk. While we may informally call a disk file such as a/b/c.py a "module," it doesn't actually become one until it's combined with information from several other sources (such as sys.path) to create the module object.

(Note, for example, that two modules with different names can be loaded from the same file, depending on sys.path and other settings. This is exactly what happens with python -m my.module followed by an import my.module in the interpreter; there will be two module objects, __main__ and my.module, both created from the same file on disk, my/module.py.)

A package is a module that may have submodules (including subpackages). Not all modules can do this. As an example, create a small module hierarchy:

$ mkdir -p a/b
$ touch a/b/c.py

Ensure that there are no other files under a. Start a Python 3.4 or later interpreter (e.g., with python3 -i) and examine the results of the following statements:

import a
a                ? <module 'a' (namespace)>
a.b              ? AttributeError: module 'a' has no attribute 'b'
import a.b.c
a.b              ? <module 'a.b' (namespace)>
a.b.c            ? <module 'a.b.c' from '/home/cjs/a/b/c.py'>

Modules a and a.b are packages (in fact, a certain kind of package called a "namespace package," though we wont' worry about that here). However, module a.b.c is not a package. We can demonstrate this by adding another file, a/b.py to the directory structure above and starting a fresh interpreter:

import a.b.c
? ImportError: No module named 'a.b.c'; 'a.b' is not a package
import a.b
a                ? <module 'a' (namespace)>
a.__path__       ? _NamespacePath(['/.../a'])
a.b              ? <module 'a.b' from '/home/cjs/tmp/a/b.py'>
a.b.__path__     ? AttributeError: 'module' object has no attribute '__path__'

Python ensures that all parent modules are loaded before a child module is loaded. Above it finds that a/ is a directory, and so creates a namespace package a, and that a/b.py is a Python source file which it loads and uses to create a (non-package) module a.b. At this point you cannot have a module a.b.c because a.b is not a package, and thus cannot have submodules.

You can also see here that the package module a has a __path__ attribute (packages must have this) but the non-package module a.b does not.

Reading content from URL with Node.js

HTTP and HTTPS:

const getScript = (url) => {
    return new Promise((resolve, reject) => {
        const http      = require('http'),
              https     = require('https');

        let client = http;

        if (url.toString().indexOf("https") === 0) {
            client = https;
        }

        client.get(url, (resp) => {
            let data = '';

            // A chunk of data has been recieved.
            resp.on('data', (chunk) => {
                data += chunk;
            });

            // The whole response has been received. Print out the result.
            resp.on('end', () => {
                resolve(data);
            });

        }).on("error", (err) => {
            reject(err);
        });
    });
};

(async (url) => {
    console.log(await getScript(url));
})('https://sidanmor.com/');

Printing Mongo query output to a file while in the mongo shell

Combining several conditions:

  • write mongo query in JS file and send it from terminal
  • switch/define a database programmatically
  • output all found records
  • cut initial output lines
  • save the output into JSON file

myScriptFile.js

// Switch current database to "mydatabase"
db = db.getSiblingDB('mydatabase');

// The mark for cutting initial output off
print("CUT_TO_HERE");

// Main output
// "toArray()" method allows to get all records
printjson( db.getCollection('jobs').find().toArray() );

Sending the query from terminal

-z key of sed allows treat output as a single multi-line string

$> mongo localhost --quiet myScriptFile.js | sed -z 's/^.*CUT_TO_HERE\n//' > output.json

Getting Integer value from a String using javascript/jquery

just do this , you need to remove char other than "numeric" and "." form your string will do work for you

yourString = yourString.replace ( /[^\d.]/g, '' );

your final code will be

  str1 = "test123.00".replace ( /[^\d.]/g, '' );
  str2 = "yes50.00".replace ( /[^\d.]/g, '' );
  total = parseInt(str1, 10) + parseInt(str2, 10);
  alert(total);

Demo

ASP.NET IIS Web.config [Internal Server Error]

Check this in the web.config and change overrideModeDefault from Deny to Allow.

<configSections>
  <sectionGroup name="system.webServer">
    <section name="handlers" overrideModeDefault="Deny" /> 
    <section name="modules" allowDefinition="MachineToApplication" overrideModeDefault="Deny" />

You can also manage sections on web server level in your IIS management console from "Feature Delegation".

Check if a file exists with wildcard in shell script

Update: For bash scripts, the most direct and performant approach is:

if compgen -G "${PROJECT_DIR}/*.png" > /dev/null; then
    echo "pattern exists!"
fi

This will work very speedily even in directories with millions of files and does not involve a new subshell.

Source


The simplest should be to rely on ls return value (it returns non-zero when the files do not exist):

if ls /path/to/your/files* 1> /dev/null 2>&1; then
    echo "files do exist"
else
    echo "files do not exist"
fi

I redirected the ls output to make it completely silent.


EDIT: Since this answer has got a bit of attention (and very useful critic remarks as comments), here is an optimization that also relies on glob expansion, but avoids the use of ls:

for f in /path/to/your/files*; do

    ## Check if the glob gets expanded to existing files.
    ## If not, f here will be exactly the pattern above
    ## and the exists test will evaluate to false.
    [ -e "$f" ] && echo "files do exist" || echo "files do not exist"

    ## This is all we needed to know, so we can break after the first iteration
    break
done

This is very similar to @grok12's answer, but it avoids the unnecessary iteration through the whole list.

Get jQuery version from inspecting the jQuery object

console.log( 'You are running jQuery version: ' + $.fn.jquery );

Invalid attempt to read when no data is present

You have to call DataReader.Read to fetch the result:

SqlDataReader dr = cmd10.ExecuteReader();
if (dr.Read()) 
{
    // read data for first record here
}

DataReader.Read() returns a bool indicating if there are more blocks of data to read, so if you have more than 1 result, you can do:

while (dr.Read()) 
{
    // read data for each record here
}

Problems with jQuery getJSON using local files in Chrome

An additional way to get around the problem is by leveraging Flash Player's Local Only security sandbox and ExternalInterface methods. One can have JavaScript request a Flash application published using the Local Only security sandbox to load the file from the hard drive, and Flash can pass the data back to JavaScript via Flash's ExternalInterface class. I've tested this in Chrome, FF and IE9, and it works well. I'd be happy to share the code if anyone is interested.

EDIT: I've started a google code (ironic?) project for the implementation: http://code.google.com/p/flash-loader/

target input by type and name (selector)

You want a multiple attribute selector

$("input[type='checkbox'][name='ProductCode']").each(function(){ ...

or

$("input:checkbox[name='ProductCode']").each(function(){ ...

It would be better to use a CSS class to identify those that you want to select however as a lot of the modern browsers implement the document.getElementsByClassName method which will be used to select elements and be much faster than selecting by the name attribute

Difference between `npm start` & `node app.js`, when starting app?

The documentation has been updated. My answer has substantial changes vs the accepted answer: I wanted to reflect documentation is up-to-date, and accepted answer has a few broken links.

Also, I didn't understand when the accepted answer said "it defaults to node server.js". I think the documentation clarifies the default behavior:

npm-start

Start a package

Synopsis

npm start [-- <args>]

Description

This runs an arbitrary command specified in the package's "start" property of its "scripts" object. If no "start" property is specified on the "scripts" object, it will run node server.js.

In summary, running npm start could do one of two things:

  1. npm start {command_name}: Run an arbitrary command (i.e. if such command is specified in the start property of package.json's scripts object)
  2. npm start: Else if no start property exists (or no command_name is passed): Run node server.js, (which may not be appropriate, for example the OP doesn't have server.js; the OP runs nodeapp.js )
  3. I said I would list only 2 items, but are other possibilities (i.e. error cases). For example, if there is no package.json in the directory where you run npm start, you may see an error: npm ERR! enoent ENOENT: no such file or directory, open '.\package.json'

Directory.GetFiles: how to get only filename, not full path?

Try,

  string[] files =  new DirectoryInfo(dir).GetFiles().Select(o => o.Name).ToArray();

Above line may throw UnauthorizedAccessException. To handle this check out below link

C# Handle System.UnauthorizedAccessException in LINQ

How can I remove an element from a list?

You can also negatively index from a list using the extract function of the magrittr package to remove a list item.

a <- seq(1,5)
b <- seq(2,6)
c <- seq(3,7)
l <- list(a,b,c)

library(magrittr)

extract(l,-1) #simple one-function method
[[1]]
[1] 2 3 4 5 6

[[2]]
[1] 3 4 5 6 7

Bi-directional Map in Java?

Creating a Guava BiMap and getting its inverted value is not so trivial.

A simple example:

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;

public class BiMapTest {

  public static void main(String[] args) {

    BiMap<String, String> biMap = HashBiMap.create();

    biMap.put("k1", "v1");
    biMap.put("k2", "v2");

    System.out.println("k1 = " + biMap.get("k1"));
    System.out.println("v2 = " + biMap.inverse().get("v2"));
  }
}

Comparing boxed Long values 127 and 128

Comparing non-primitives (aka Objects) in Java with == compares their reference instead of their values. Long is a class and thus Long values are Objects.

The problem is that the Java Developers wanted people to use Long like they used long to provide compatibility, which led to the concept of autoboxing, which is essentially the feature, that long-values will be changed to Long-Objects and vice versa as needed. The behaviour of autoboxing is not exactly predictable all the time though, as it is not completely specified.

So to be safe and to have predictable results always use .equals() to compare objects and do not rely on autoboxing in this case:

Long num1 = 127, num2 = 127;
if(num1.equals(num2)) { iWillBeExecutedAlways(); }

AngularJs .$setPristine to reset form

There is another way to pristine form that is by sending form into the controller. For example:-

In view:-

<form name="myForm" ng-submit="addUser(myForm)" novalidate>
    <input type="text" ng-mode="user.name"/>
     <span style="color:red" ng-show="myForm.name.$dirty && myForm.name.$invalid">
      <span ng-show="myForm.name.$error.required">Name is required.</span>
    </span>

    <button ng-disabled="myForm.$invalid">Add User</button>
</form>

In Controller:-

$scope.addUser = function(myForm) {
       myForm.$setPristine();
};

How to vertically center content with variable height within a div?

You can use margin auto. With flex, the div seems to be centered vertically too.

body,
html {
  height: 100%;
  margin: 0;
}
.site {
  height: 100%;
  display: flex;
}
.site .box {
  background: #0ff;
  max-width: 20vw;
  margin: auto;
}
<div class="site">
  <div class="box">
    <h1>blabla</h1>
    <p>blabla</p>
    <p>blablabla</p>
    <p>lbibdfvkdlvfdks</p>
  </div>
</div>

How to get dictionary values as a generic list

Use this:

List<MyType> items = new List<MyType>()
foreach(var value in myDico.Values)
    items.AddRange(value);

The problem is that every key in your dictionary has a list of instances as value. Your code would work, if each key would have exactly one instance as value, as in the following example:

Dictionary<string, MyType> myDico = GetDictionary();
List<MyType> items = new List<MyType>(myDico.Values);

How do I force Postgres to use a particular index?

Check your random_page_cost

This problem typically happens when the estimated cost of an index scan is too high and doesn't correctly reflect reality. You may need to lower the random_page_cost configuration parameter to fix this. From the Postgres documentation:

Reducing this value [...] will cause the system to prefer index scans; raising it will make index scans look relatively more expensive.

You can do a quick test whether this will actually make Postgres use the index:

EXPLAIN <query>;              # Uses sequential scan
SET random_page_cost = 1;
EXPLAIN <query>;              # May use index scan now

You can restore the default value with SET random_page_cost = DEFAULT; again.

Background

Index scans require non-sequential disk page fetches. Postgres uses random_page_cost to estimate the cost of such non-sequential fetches in relation to sequential fetches. The default value is 4.0, thus assuming an average cost factor of 4 compared to sequential fetches (taking caching effects into account).

The problem however is that this default value is unsuitable in the following important real-life scenarios:

1) Solid-state drives

As per the documentation:

Storage that has a low random read cost relative to sequential, e.g. solid-state drives, might be better modeled with a lower value for random_page_cost, e.g., 1.1.

This slide from a speak at PostgresConf 2018 also says that random_page_cost should be set to something between 1.0 and 2.0 for solid-state drives.

2) Cached data

If the required index data is already cached in RAM, an index scan will always be significantly faster than a sequential scan. The documentation says:

If your data is likely to be completely in cache, [...] decreasing random_page_cost can be appropriate.

The problem is that you of course can't easily know whether the relevant data is already cached. However, if a specific index is frequently used, and if the system has sufficient RAM, then data is likely to be cached eventually, and random_page_cost should be set to a lower value. You'll have to experiment with different values and see what works for you.

You might also want to use the pg_prewarm extension for explicit data caching.


How to set a variable to be "Today's" date in Python/Pandas

import datetime
def today_date():
    '''
    utils:
    get the datetime of today
    '''
    date=datetime.datetime.now().date()
    date=pd.to_datetime(date)
    return date
Df['Date'] = today_date()

this could be safely used in pandas dataframes.

How to show image using ImageView in Android

If you want to display an image file on the phone, you can do this:

private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageViewId);
mImageView.setImageBitmap(BitmapFactory.decodeFile("pathToImageFile"));

If you want to display an image from your drawable resources, do this:

private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageViewId);
mImageView.setImageResource(R.drawable.imageFileId);

You'll find the drawable folder(s) in the project res folder. You can put your image files there.

What is the proper way to re-attach detached objects in Hibernate?

All of these answers miss an important distinction. update() is used to (re)attach your object graph to a Session. The objects you pass it are the ones that are made managed.

merge() is actually not a (re)attachment API. Notice merge() has a return value? That's because it returns you the managed graph, which may not be the graph you passed it. merge() is a JPA API and its behavior is governed by the JPA spec. If the object you pass in to merge() is already managed (already associated with the Session) then that's the graph Hibernate works with; the object passed in is the same object returned from merge(). If, however, the object you pass into merge() is detached, Hibernate creates a new object graph that is managed and it copies the state from your detached graph onto the new managed graph. Again, this is all dictated and governed by the JPA spec.

In terms of a generic strategy for "make sure this entity is managed, or make it managed", it kind of depends on if you want to account for not-yet-inserted data as well. Assuming you do, use something like

if ( session.contains( myEntity ) ) {
    // nothing to do... myEntity is already associated with the session
}
else {
    session.saveOrUpdate( myEntity );
}

Notice I used saveOrUpdate() rather than update(). If you do not want not-yet-inserted data handled here, use update() instead...

Differences between ConstraintLayout and RelativeLayout

Reported by @davidpbr ConstraintLayout performance

I made two similar 7-child layouts, one each with a parent ConstraintLayout and RelativeLayout. Based on Android Studio method tracing tool, it appears the ConstraintLayout spends more time in onMeasure and performs additional work in onFinishInflate.

Library used (support-v4, appcompat-v7…):

com.android.support.constraint:constraint-layout:1.0.0-alpha1

Devices/Android versions reproduced on: Samsung Galaxy S6 (SM-G920A. Sorry, no Nexus atm). Android 5.0.2

Quick method tracing comparison:

1

Sample Github repo: https://github.com/OnlyInAmerica/ConstraintLayoutPerf

Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8?

After a few days of struggle, this works for me, and I hope this also works for you.

add this to your CONFIG.XML, top of your code.

<access origin="*" />
<allow-navigation href="*" />

and this, under the platform android.

<edit-config file="app/src/main/AndroidManifest.xml" 
   mode="merge" target="/manifest/application" 
   xmlns:android="http://schemas.android.com/apk/res/android">
     <application android:usesCleartextTraffic="true" />
     <application android:networkSecurityConfig="@xml/network_security_config" />
 </edit-config>
 <resource-file src="resources/android/xml/network_security_config.xml" 
 target="app/src/main/res/xml/network_security_config.xml" />

add the follow code to this file "resources/android/xml/network_security_config.xml".

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
        <domain includeSubdomains="true">YOUR DOMAIN HERE/IP</domain>
    </domain-config>
</network-security-config>

enter image description here

enter image description here

How to import an excel file in to a MySQL database

There are actually several ways to import an excel file in to a MySQL database with varying degrees of complexity and success.

  1. Excel2MySQL. Hands down, the easiest and fastest way to import Excel data into MySQL. It supports all verions of Excel and doesn't require Office install.

    screenshot of Excel2MySQL

  2. LOAD DATA INFILE: This popular option is perhaps the most technical and requires some understanding of MySQL command execution. You must manually create your table before loading and use appropriately sized VARCHAR field types. Therefore, your field data types are not optimized. LOAD DATA INFILE has trouble importing large files that exceed 'max_allowed_packet' size. Special attention is required to avoid problems importing special characters and foreign unicode characters. Here is a recent example I used to import a csv file named test.csv.

    enter image description here

  3. phpMyAdmin: Select your database first, then select the Import tab. phpMyAdmin will automatically create your table and size your VARCHAR fields, but it won't optimize the field types. phpMyAdmin has trouble importing large files that exceed 'max_allowed_packet' size.

    enter image description here

  4. MySQL for Excel: This is a free Excel Add-in from Oracle. This option is a bit tedious because it uses a wizard and the import is slow and buggy with large files, but this may be a good option for small files with VARCHAR data. Fields are not optimized.

    enter image description here

Change Project Namespace in Visual Studio

"Default Namespace textbox in project properties is disabled" Same with me (VS 2010). I edited the project file ("xxx.csproj") and tweaked the item. That changed the default namespace.

@Resource vs @Autowired

The primary difference is, @Autowired is a spring annotation. Whereas @Resource is specified by the JSR-250, as you pointed out yourself. So the latter is part of Java whereas the former is Spring specific.

Hence, you are right in suggesting that, in a sense. I found folks use @Autowired with @Qualifier because it is more powerful. Moving from some framework to some other is considered very unlikely, if not myth, especially in the case of Spring.

SQL Server command line backup statement

I am using SQL Server 2005 Express, and I had to enable Named Pipes connection to be able to backup from the Windows Command. My final script is this:

@echo off
set DB_NAME=Your_DB_Name
set BK_FILE=D:\DB_Backups\%DB_NAME%.bak
set DB_HOSTNAME=Your_DB_Hostname
echo.
echo.
echo Backing up %DB_NAME% to %BK_FILE%...
echo.
echo.
sqlcmd -E -S np:\\%DB_HOSTNAME%\pipe\MSSQL$SQLEXPRESS\sql\query -d master -Q "BACKUP DATABASE [%DB_NAME%] TO DISK = N'%BK_FILE%' WITH INIT , NOUNLOAD , NAME = N'%DB_NAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.
echo Done!
echo.

It's working just fine here!!