Programs & Examples On #Merge conflict resolution

When merging branches in a version control system, a merge conflict might arise. This tag is for questions about how such conflicts can be resolved.

INSERT IF NOT EXISTS ELSE UPDATE?

Upsert is what you want. UPSERT syntax was added to SQLite with version 3.24.0 (2018-06-04).

CREATE TABLE phonebook2(
  name TEXT PRIMARY KEY,
  phonenumber TEXT,
  validDate DATE
);

INSERT INTO phonebook2(name,phonenumber,validDate)
  VALUES('Alice','704-555-1212','2018-05-08')
  ON CONFLICT(name) DO UPDATE SET
    phonenumber=excluded.phonenumber,
    validDate=excluded.validDate
  WHERE excluded.validDate>phonebook2.validDate;

Be warned that at this point the actual word "UPSERT" is not part of the upsert syntax.

The correct syntax is

INSERT INTO ... ON CONFLICT(...) DO UPDATE SET...

and if you are doing INSERT INTO SELECT ... your select needs at least WHERE true to solve parser ambiguity about the token ON with the join syntax.

Be warned that INSERT OR REPLACE... will delete the record before inserting a new one if it has to replace, which could be bad if you have foreign key cascades or other delete triggers.

How to resolve merge conflicts in Git repository?

If you do not use a tool to merge, first copy your code outside:

- `checkout master`
- `git pull` / get new commit
- `git checkout` to your branch
- `git rebase master`

It resolve conflict and you can copy your code.

Why does git say "Pull is not possible because you have unmerged files"?

What is currently happening is, that you have a certain set of files, which you have tried merging earlier, but they threw up merge conflicts. Ideally, if one gets a merge conflict, he should resolve them manually, and commit the changes using git add file.name && git commit -m "removed merge conflicts". Now, another user has updated the files in question on his repository, and has pushed his changes to the common upstream repo.

It so happens, that your merge conflicts from (probably) the last commit were not not resolved, so your files are not merged all right, and hence the U(unmerged) flag for the files. So now, when you do a git pull, git is throwing up the error, because you have some version of the file, which is not correctly resolved.

To resolve this, you will have to resolve the merge conflicts in question, and add and commit the changes, before you can do a git pull.

Sample reproduction and resolution of the issue:

# Note: commands below in format `CUURENT_WORKING_DIRECTORY $ command params`
Desktop $ cd test

First, let us create the repository structure

test $ mkdir repo && cd repo && git init && touch file && git add file && git commit -m "msg"
repo $ cd .. && git clone repo repo_clone && cd repo_clone
repo_clone $ echo "text2" >> file && git add file && git commit -m "msg" && cd ../repo
repo $ echo "text1" >> file && git add file && git commit -m "msg" && cd ../repo_clone

Now we are in repo_clone, and if you do a git pull, it will throw up conflicts

repo_clone $ git pull origin master
remote: Counting objects: 5, done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
From /home/anshulgoyal/Desktop/test/test/repo
 * branch            master     -> FETCH_HEAD
   24d5b2e..1a1aa70  master     -> origin/master
Auto-merging file
CONFLICT (content): Merge conflict in file
Automatic merge failed; fix conflicts and then commit the result.

If we ignore the conflicts in the clone, and make more commits in the original repo now,

repo_clone $ cd ../repo
repo $ echo "text1" >> file && git add file && git commit -m "msg" && cd ../repo_clone

And then we do a git pull, we get

repo_clone $ git pull
U   file
Pull is not possible because you have unmerged files.
Please, fix them up in the work tree, and then use 'git add/rm <file>'
as appropriate to mark resolution, or use 'git commit -a'.

Note that the file now is in an unmerged state and if we do a git status, we can clearly see the same:

repo_clone $ git status
On branch master
Your branch and 'origin/master' have diverged,
and have 1 and 1 different commit each, respectively.
  (use "git pull" to merge the remote branch into yours)

You have unmerged paths.
  (fix conflicts and run "git commit")

Unmerged paths:
  (use "git add <file>..." to mark resolution)

        both modified:      file

So, to resolve this, we first need to resolve the merge conflict we ignored earlier

repo_clone $ vi file

and set its contents to

text2
text1
text1

and then add it and commit the changes

repo_clone $ git add file && git commit -m "resolved merge conflicts"
[master 39c3ba1] resolved merge conflicts

How to interactively (visually) resolve conflicts in SourceTree / git

I'm using SourceTree along with TortoiseMerge/Diff, which is very easy and convinient diff/merge tool.

If you'd like to use it as well, then:

  1. Get standalone version of TortoiseMerge/Diff (quite old, since it doesn't ship standalone since version 1.6.7 of TortosieSVN, that is since July 2011). Links and details in this answer.

  2. Unzip TortoiseIDiff.exe and TortoiseMerge.exe to any folder (c:\Program Files (x86)\Atlassian\SourceTree\extras\ in my case).

  3. In SourceTree open Tools > Options > Diff > External Diff / Merge. Select TortoiseMerge in both dropdown lists.

  4. Hit OK and point SourceTree to your location of TortoiseIDiff.exe and TortoiseMerge.exe.

After that, you can select Resolve Conflicts > Launch External Merge Tool from context menu on each conflicted file in your local repository. This will open up TortoiseMerge, where you can easily deal with all the conflicts, you have. Once finished, simply close TortoiseMerge (you don't even need to save changes, this will probably be done automatically) and after few seconds SourceTree should handle that gracefully.

The only problem is, that it automatically creates backup copy, even though proper option is unchecked.

How do I fix a merge conflict due to removal of a file in a branch?

The conflict message:

CONFLICT (delete/modify): res/layout/dialog_item.xml deleted in dialog and modified in HEAD

means that res/layout/dialog_item.xml was deleted in the 'dialog' branch you are merging, but was modified in HEAD (in the branch you are merging to).

So you have to decide whether

  • remove file using "git rm res/layout/dialog_item.xml"

or

  • accept version from HEAD (perhaps after editing it) with "git add res/layout/dialog_item.xml"

Then you finalize merge with "git commit".

Note that git will warn you that you are creating a merge commit, in the (rare) case where it is something you don't want. Probably remains from the days where said case was less rare.

Cannot checkout, file is unmerged

If you want to discard modifications you made to the file, you can do:

git reset first_Name.txt
git checkout first_Name.txt

Git resolve conflict using --ours/--theirs for all files

function gitcheckoutall() {
    git diff --name-only --diff-filter=U | sed 's/^/"/;s/$/"/' | xargs git checkout --$1
}

I've added this function in .zshrc file.

Use them this way: gitcheckoutall theirs or gitcheckoutall ours

Resolving a Git conflict with binary files

I came across a similar problem (wanting to pull a commit that included some binary files which caused conflicts when merged), but came across a different solution that can be done entirely using git (i.e. not having to manually copy files over). I figured I'd include it here so at the very least I can remember it the next time I need it. :) The steps look like this:

% git fetch

This fetches the latest commit(s) from the remote repository (you may need to specify a remote branch name, depending on your setup), but doesn't try to merge them. It records the the commit in FETCH_HEAD

% git checkout FETCH_HEAD stuff/to/update

This takes the copy of the binary files I want and overwrites what's in the working tree with the version fetched from the remote branch. git doesn't try to do any merging, so you just end up with an exact copy of the binary file from the remote branch. Once that's done, you can add/commit the new copy just like normal.

How to uninstall Python 2.7 on a Mac OS X 10.6.4?

If you're thinking about manually removing Apple's default Python 2.7, I'd suggest you hang-fire and do-noting: Looks like Apple will very shortly do it for you:

Python 2.7 Deprecated in OSX 10.15 Catalina

Python 2.7- as well as Ruby & Perl- are deprecated in Catalina: (skip to section "Scripting Language Runtimes" > "Deprecations")

https://developer.apple.com/documentation/macos_release_notes/macos_catalina_10_15_release_notes

Apple To Remove Python 2.7 in OSX 10.16

Indeed, if you do nothing at all, according to The Mac Observer, by OSX version 10.16, Python 2.7 will disappear from your system:

https://www.macobserver.com/analysis/macos-catalina-deprecates-unix-scripting-languages/

Given this revelation, I'd suggest the best course of action is do nothing and wait for Apple to wipe it for you. As Apple is imminently about to remove it for you, doesn't seem worth the risk of tinkering with your Python environment.

NOTE: I see the question relates specifically to OSX v 10.6.4, but it appears this question has become a pivot-point for all OSX folks interested in removing Python 2.7 from their systems, whatever version they're running.

Resolve promises one after another (i.e. in sequence)?

Nicest solution that I was able to figure out was with bluebird promises. You can just do Promise.resolve(files).each(fs.readFileAsync); which guarantees that promises are resolved sequentially in order.

how to permit an array with strong parameters

If you have a hash structure like this:

Parameters: {"link"=>{"title"=>"Something", "time_span"=>[{"start"=>"2017-05-06T16:00:00.000Z", "end"=>"2017-05-06T17:00:00.000Z"}]}}

Then this is how I got it to work:

params.require(:link).permit(:title, time_span: [[:start, :end]])

Get visible items in RecyclerView

Every answer above is correct and I would like to add also a snapshot from my working codes.

recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
           //some code when initially scrollState changes
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            //Some code while the list is scrolling
            LinearLayoutManager lManager = (LinearLayoutManager) recycler.getLayoutManager();
            int firstElementPosition = lManager.findFirstVisibleItemPosition();
            
        }
    });

height: 100% for <div> inside <div> with display: table-cell

Make the the table-cell position relative, then make the inner div position absolute, with top/right/bottom/left all set to 0px.

.table-cell {
  display: table-cell;
  position: relative;
}

.inner-div {
  position: absolute;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
}

hide/show a image in jquery

I know this is an older post but it may be useful for those who are looking to show a .NET server side image using jQuery.

You have to use a slightly different logic.

So, $("#<%=myServerimg.ClientID%>").show() will not work if you hid the image using myServerimg.visible = false.

Instead, use the following on server side:

myServerimg.Style.Add("display", "none")

'Connect-MsolService' is not recognized as the name of a cmdlet

I had to do this in that order:

Install-Module MSOnline
Install-Module AzureAD
Import-Module AzureAD

Angular - ui-router get previous state

I am stuck with same issue and find the easiest way to do this...

//Html
<button type="button" onclick="history.back()">Back</button>

OR

//Html
<button type="button" ng-click="goBack()">Back</button>

//JS
$scope.goBack = function() {
  window.history.back();
};

(If you want it to be more testable, inject the $window service into your controller and use $window.history.back()).

.gitignore is ignored by Git

This might sound silly, but what solved my problem was realizing that .gitignore is working correctly, even if it says deleted: yourfile on git status.

I was going to ignore an error log file, to ignore any errors I caused, but save the ones caused by other developers in case they came in handy one day while debugging an odd problem. However, git does not let you "ignore" and also keep a file at the same time.

I wanted it to be "frozen in time", but git says it either gets tracked, or it is not allowed to be there at all.

Update multiple rows in same query using PostgreSQL

Based on the solution of @Roman, you can set multiple values:

update users as u set -- postgres FTW
  email = u2.email,
  first_name = u2.first_name,
  last_name = u2.last_name
from (values
  (1, '[email protected]', 'Hollis', 'O\'Connell'),
  (2, '[email protected]', 'Robert', 'Duncan')
) as u2(id, email, first_name, last_name)
where u2.id = u.id;

Reset identity seed after deleting records in SQL Server

Although most answers are suggesting RESEED to 0, many times we need to just reseed to next Id available

declare @max int
select @max=max([Id]) from [TestTable]
if @max IS NULL   --check when max is returned as null
  SET @max = 0
DBCC CHECKIDENT ('[TestTable]', RESEED, @max)

This will check the table and reset to the next ID.

MVC 4 Razor File Upload

The Upload method's HttpPostedFileBase parameter must have the same name as the the file input.

So just change the input to this:

<input type="file" name="file" />

Also, you could find the files in Request.Files:

[HttpPost]
public ActionResult Upload()
{
     if (Request.Files.Count > 0)
     {
         var file = Request.Files[0];

         if (file != null && file.ContentLength > 0)
         {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
            file.SaveAs(path);
         }
     }

     return RedirectToAction("UploadDocument");
 }

Writing/outputting HTML strings unescaped

Supposing your content is inside a string named mystring...

You can use:

@Html.Raw(mystring)

Alternatively you can convert your string to HtmlString or any other type that implements IHtmlString in model or directly inline and use regular @:

@{ var myHtmlString = new HtmlString(mystring);}
@myHtmlString

Java serialization - java.io.InvalidClassException local class incompatible

For me, I forgot to add the default serial id.

private static final long serialVersionUID = 1L;

How do I find an element position in std::vector?

Take a look at the answers provided for this question: Invalid value for size_t?. Also you can use std::find_if with std::distance to get the index.

std::vector<type>::iterator iter = std::find_if(vec.begin(), vec.end(), comparisonFunc);
size_t index = std::distance(vec.begin(), iter);
if(index == vec.size()) 
{
    //invalid
}

Maven project version inheritance - do I have to specify the parent version?

Since Maven 3.5.0 you can use the ${revision} placeholder for that. The use is documented here: Maven CI Friendly Versions.

In short the parent pom looks like this (quoted from the Apache documentation):

<project>
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache</groupId>
    <artifactId>apache</artifactId>
    <version>18</version>
  </parent>
  <groupId>org.apache.maven.ci</groupId>
  <artifactId>ci-parent</artifactId>
  <name>First CI Friendly</name>
  <version>${revision}</version>
  ...
  <properties>
    <revision>1.0.0-SNAPSHOT</revision>
  </properties>
  <modules>
    <module>child1</module>
    ..
  </modules>
</project>

and the child pom like this

<project>
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache.maven.ci</groupId>
    <artifactId>ci-parent</artifactId>
    <version>${revision}</version>
  </parent>
  <groupId>org.apache.maven.ci</groupId>
  <artifactId>ci-child</artifactId>
   ...
</project>

You also have to use the Flatten Maven Plugin to generate pom documents with the dedicated version number included for deployment. The HowTo is documented in the linked documentation.

Also @khmarbaise wrote a nice blob post about this feature: Maven: POM Files Without a Version in It?

Can you use @Autowired with static fields?

You can use ApplicationContextAware

@Component
public class AppContext implements ApplicationContextAware{
    public static ApplicationContext applicationContext;

    public AppBeans(){
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

then

static ABean bean = AppContext.applicationContext.getBean("aBean",ABean.class);

Decoding a Base64 string in Java

Modify the package you're using:

import org.apache.commons.codec.binary.Base64;

And then use it like this:

byte[] decoded = Base64.decodeBase64("YWJjZGVmZw==");
System.out.println(new String(decoded, "UTF-8") + "\n");

[Ljava.lang.Object; cannot be cast to

Your query execution will return list of Object[].

List result_source = LoadSource.list();
for(Object[] objA : result_source) {
    // read it all
}

How do I share a global variable between c files?

Use extern keyword in another .c file.

How do I declare class-level properties in Objective-C?

Here's a thread safe way of doing it:

// Foo.h
@interface Foo {
}

+(NSDictionary*) dictionary;

// Foo.m
+(NSDictionary*) dictionary
{
  static NSDictionary* fooDict = nil;

  static dispatch_once_t oncePredicate;

  dispatch_once(&oncePredicate, ^{
        // create dict
    });

  return fooDict;
}

These edits ensure that fooDict is only created once.

From Apple documentation: "dispatch_once - Executes a block object once and only once for the lifetime of an application."

ConcurrentHashMap vs Synchronized HashMap

Synchronized HashMap:

  1. Each method is synchronized using an object level lock. So the get and put methods on synchMap acquire a lock.

  2. Locking the entire collection is a performance overhead. While one thread holds on to the lock, no other thread can use the collection.

ConcurrentHashMap was introduced in JDK 5.

  1. There is no locking at the object level,The locking is at a much finer granularity. For a ConcurrentHashMap, the locks may be at a hashmap bucket level.

  2. The effect of lower level locking is that you can have concurrent readers and writers which is not possible for synchronized collections. This leads to much more scalability.

  3. ConcurrentHashMap does not throw a ConcurrentModificationException if one thread tries to modify it while another is iterating over it.

This article Java 7: HashMap vs ConcurrentHashMap is a very good read. Highly recommended.

Typescript: difference between String and string

For quick readers:

Don’t ever use the types Number, String, Boolean, Symbol, or Object These types refer to non-primitive boxed objects that are almost never used appropriately in JavaScript code.

source: https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html

Classes residing in App_Code is not accessible

Right click on the .cs file in the App_Code folder and check its properties.

Make sure the "Build Action" is set to "Compile".

Negation in Python

Python prefers English keywords to punctuation. Use not x, i.e. not os.path.exists(...). The same thing goes for && and || which are and and or in Python.

Convert Object to JSON string

Also useful is Object.toSource() for debugging purposes, where you want to show the object and its properties for debugging purposes. This is a generic Javascript (not jQuery) function, however it only works in "modern" browsers.

Change label text using JavaScript

Have you tried .innerText or .value instead of .innerHTML?

How do I replace part of a string in PHP?

Just do:

$text = str_replace(' ', '_', $text)

javascript onclick increment number

I know this is an old post but its relevant to what I'm working on currently.

What I'm aiming to do is create next/previous page buttons at the top of a html page, and say I'm on 'book.html', with the current 'display' ID content being 'page-1.html' through ajax, if i click the 'next' button it will load 'page-2.html' through ajax, WITHOUT reloading the page.

How would I go about doing this through AJAX as I have seen many examples but most of them are completely different, and most examples of using AJAX are for WordPress forms and stuff.

Currently using the below line will open the entire page, I want to know the best way to go about using AJAX instead if possible :) window.location(url);

I'm incorportating the below code as an example:

var i = 1;
var url = "pages/page-" + i + ".html";

    function incPage() {
    if (i < 10) {
        i++;
        window.location = url; 
        //load next page in body using AJAX request

    } else if (i = 10) {
        i = 0;
    }
    document.getElementById("display").innerHTML = i;
}

function decPage() {
    if (i > 0) {
        --i;
        window.location = url; 
        //load previous page in body using AJAX request
    } else if (i = 0) {
        i = 10;
    }
    document.getElementById("display").innerHTML = i;
}

Delete a single record from Entity Framework?

Here's a safe way:

using (var transitron = ctx.Database.BeginTransaction())
{
  try
  {
    var employer = new Employ { Id = 1 };
    ctx.Entry(employer).State = EntityState.Deleted;
    ctx.SaveChanges();
    transitron.Commit();
  }
  catch (Exception ex)
  {
    transitron.Rollback();
    //capture exception like: entity does not exist, Id property does not exist, etc...
  }
}

Here you can pile up all the changes you want, so you can do a series of deletion before the SaveChanges and Commit, so they will be applied only if they are all successful.

How do I deal with special characters like \^$.?*|+()[{ in my regex?

Escape with a double backslash

R treats backslashes as escape values for character constants. (... and so do regular expressions. Hence the need for two backslashes when supplying a character argument for a pattern. The first one isn't actually a character, but rather it makes the second one into a character.) You can see how they are processed using cat.

y <- "double quote: \", tab: \t, newline: \n, unicode point: \u20AC"
print(y)
## [1] "double quote: \", tab: \t, newline: \n, unicode point: €"
cat(y)
## double quote: ", tab:    , newline: 
## , unicode point: €

Further reading: Escaping a backslash with a backslash in R produces 2 backslashes in a string, not 1

To use special characters in a regular expression the simplest method is usually to escape them with a backslash, but as noted above, the backslash itself needs to be escaped.

grepl("\\[", "a[b")
## [1] TRUE

To match backslashes, you need to double escape, resulting in four backslashes.

grepl("\\\\", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

The rebus package contains constants for each of the special characters to save you mistyping slashes.

library(rebus)
OPEN_BRACKET
## [1] "\\["
BACKSLASH
## [1] "\\\\"

For more examples see:

?SpecialCharacters

Your problem can be solved this way:

library(rebus)
grepl(OPEN_BRACKET, "a[b")

Form a character class

You can also wrap the special characters in square brackets to form a character class.

grepl("[?]", "a?b")
## [1] TRUE

Two of the special characters have special meaning inside character classes: \ and ^.

Backslash still needs to be escaped even if it is inside a character class.

grepl("[\\\\]", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

Caret only needs to be escaped if it is directly after the opening square bracket.

grepl("[ ^]", "a^b")  # matches spaces as well.
## [1] TRUE
grepl("[\\^]", "a^b") 
## [1] TRUE

rebus also lets you form a character class.

char_class("?")
## <regex> [?]

Use a pre-existing character class

If you want to match all punctuation, you can use the [:punct:] character class.

grepl("[[:punct:]]", c("//", "[", "(", "{", "?", "^", "$"))
## [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE

stringi maps this to the Unicode General Category for punctuation, so its behaviour is slightly different.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "[[:punct:]]")
## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE

You can also use the cross-platform syntax for accessing a UGC.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "\\p{P}")
## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE

Use \Q \E escapes

Placing characters between \\Q and \\E makes the regular expression engine treat them literally rather than as regular expressions.

grepl("\\Q.\\E", "a.b")
## [1] TRUE

rebus lets you write literal blocks of regular expressions.

literal(".")
## <regex> \Q.\E

Don't use regular expressions

Regular expressions are not always the answer. If you want to match a fixed string then you can do, for example:

grepl("[", "a[b", fixed = TRUE)
stringr::str_detect("a[b", fixed("["))
stringi::stri_detect_fixed("a[b", "[")

Rails find_or_create_by more than one attribute?

You can do:

User.find_or_create_by(first_name: 'Penélope', last_name: 'Lopez')
User.where(first_name: 'Penélope', last_name: 'Lopez').first_or_create

Or to just initialize:

User.find_or_initialize_by(first_name: 'Penélope', last_name: 'Lopez')
User.where(first_name: 'Penélope', last_name: 'Lopez').first_or_initialize

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

In case someone stumbled upon this problem when working on Grails (or pure Spring) web application, here is the post that helped me:

http://forum.spring.io/forum/spring-projects/web/2491-solved-character-encoding-and-multipart-forms

To set default encoding to UTF-8 (instead of the ISO-8859-1) for multipart requests, I added the following code in resources.groovy (Spring DSL):

multipartResolver(ContentLengthAwareCommonsMultipartResolver) {
    defaultEncoding = 'UTF-8'
}

How to list branches that contain a given commit?

The answer for git branch -r --contains <commit> works well for normal remote branches, but if the commit is only in the hidden head namespace that GitHub creates for PRs, you'll need a few more steps.

Say, if PR #42 was from deleted branch and that PR thread has the only reference to the commit on the repo, git branch -r doesn't know about PR #42 because refs like refs/pull/42/head aren't listed as a remote branch by default.

In .git/config for the [remote "origin"] section add a new line:

fetch = +refs/pull/*/head:refs/remotes/origin/pr/*

(This gist has more context.)

Then when you git fetch you'll get all the PR branches, and when you run git branch -r --contains <commit> you'll see origin/pr/42 contains the commit.

How to set Java environment path in Ubuntu

Installation of Oracle Java:

  1. Donwload the tarball(.tar file) from Oracle website
  2. unzip it by sudo tar -xvpzf fileName -C /installation_folder_name
  3. change the files permission and ownership
  4. add the following two lines in /etc/profile

export JAVA_HOME=/home/abu/Java/jdk1.8.0_45/ export PATH=$JAVA_HOME/bin:$PATH

  1. restart the machine and check by java -version and javac -version

Checking letter case (Upper/Lower) within a string in Java

That's what I got:

    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter a nickname!");
    while (!scanner.hasNext("[a-zA-Z]{3,8}+")) {
        System.out.println("Nickname should contain only Alphabetic letters! At least 3 and max 8 letters");
        scanner.next();
    }
    String nickname = scanner.next();
    System.out.println("Thank you! Got " + nickname);

Read about regex Pattern here: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

How can I center <ul> <li> into div

Here is the solution I could find:

#wrapper {
  float:right;
  position:relative;
  left:-50%;
  text-align:left;
}
#wrapper ul {
  list-style:none;
  position:relative;
  left:50%;
}

#wrapper li{
  float:left;
  position:relative;
}

Better way to cast object to int

You can first cast object to string and then cast the string to int; for example:

string str_myobject = myobject.ToString();
int int_myobject = int.Parse(str_myobject);

this worked for me.

Remove menubar from Electron app

setMenu(null); is the best answer, autohidemenu will display on the start of the application


    function createWindow(){
        const win = new BrowserWindow({
            width: 1500,
            height: 800,
            webPreferences:{
                nodeIntergration: true
            }
        });
        win.setMenu(null);
    win.loadFile("index.html");
    }
    app.whenReady().then(createWindow);

no default constructor exists for class

You declared the constructor blowfish as this:

Blowfish(BlowfishAlgorithm algorithm);

So this line cannot exist (without further initialization later):

Blowfish _blowfish;

since you passed no parameter. It does not understand how to handle a parameter-less declaration of object "BlowFish" - you need to create another constructor for that.

:first-child not working as expected

:first-child selects the first h1 if and only if it is the first child of its parent element. In your example, the ul is the first child of the div.

The name of the pseudo-class is somewhat misleading, but it's explained pretty clearly here in the spec.

jQuery's :first selector gives you what you're looking for. You can do this:

$('.detail_container h1:first').css("color", "blue");

Find and kill a process in one line using bash and regex

Try using

ps aux | grep 'python csp_build.py' | head -1 | cut -d " " -f 2 | xargs kill

Rails 3.1 and Image Assets

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

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

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

Iterate over each line in a string in PHP

If you need to handle newlines in diferent systems you can simply use the PHP predefined constant PHP_EOL (http://php.net/manual/en/reserved.constants.php) and simply use explode to avoid the overhead of the regular expression engine.

$lines = explode(PHP_EOL, $subject);

Spring JPA and persistence.xml

I have a test application set up using JPA/Hibernate & Spring, and my configuration mirrors yours with the exception that I create a datasource and inject it into the EntityManagerFactory, and moved the datasource specific properties out of the persistenceUnit and into the datasource. With these two small changes, my EM gets injected properly.

Force HTML5 youtube video

Inline tag is used to add another src of document to the current html element.

In your case an video of a youtube and we need to specify the html type(4 or 5) to the browser externally to the link

so add ?html=5 to the end of the link.. :)

How to implement the Java comparable interface?

Possible alternative from the source code of Integer.compare method which requires API Version 19 is :

public int compareTo(Animal other) { return Integer.valueOf(this.year_discovered).compareTo(other.year_discovered); }

This alternative does not require you to use API version 19.

How to call an action after click() in Jquery?

setTimeout may help out here

$("#message_link").click(function(){
   setTimeout(function() {
       if (some_conditions...){
           $("#header").append("<div><img alt=\"Loader\"src=\"/images/ajax-loader.gif\"  /></div>");
       }
   }, 100);
});

That will cause the div to be appended ~100ms after the click event occurs, if some_conditions are met.

Number of lines in a file in Java

If you don't have any index structures, you'll not get around the reading of the complete file. But you can optimize it by avoiding to read it line by line and use a regex to match all line terminators.

Angular 2: How to call a function after get a response from subscribe http.post

You can code as a lambda expression as the third parameter(on complete) to the subscribe method. Here I re-set the departmentModel variable to the default values.

saveData(data:DepartmentModel){
  return this.ds.sendDepartmentOnSubmit(data).
  subscribe(response=>this.status=response,
   ()=>{},
   ()=>this.departmentModel={DepartmentId:0});
}

How to mark a build unstable in Jenkins when running shell scripts

One easy way to set a build as unstable, is in your "execute shell" block, run exit 13

Converting strings to floats in a DataFrame

you have to replace empty strings ('') with np.nan before converting to float. ie:

df['a']=df.a.replace('',np.nan).astype(float)

How to lay out Views in RelativeLayout programmatically?

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);

        final RelativeLayout relativeLayout = new RelativeLayout(this);
        final TextView tv1 = new TextView(this);
        tv1.setText("tv1 is here");
        // Setting an ID is mandatory.
        tv1.setId(View.generateViewId());
        relativeLayout.addView(tv1);


        final TextView tv2 = new TextView(this);
        tv2.setText("tv2 is here");

        // We are defining layout params for tv2 which will be added to its  parent relativelayout.
        // The type of the LayoutParams depends on the parent type.
        RelativeLayout.LayoutParams tv2LayoutParams = new  RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);

        //Also, we want tv2 to appear below tv1, so we are adding rule to tv2LayoutParams.
        tv2LayoutParams.addRule(RelativeLayout.BELOW, tv1.getId());

        //Now, adding the child view tv2 to relativelayout, and setting tv2LayoutParams to be set on view tv2.
        relativeLayout.addView(tv2);
        tv2.setLayoutParams(tv2LayoutParams);
        //Or we can combined the above two steps in one line of code
        //relativeLayout.addView(tv2, tv2LayoutParams);

        this.setContentView(relativeLayout);
    }

}

Regular expression for 10 digit number without any special characters

An example of how to implement it:

public bool ValidateSocialSecNumber(string socialSecNumber)
{
    //Accepts only 10 digits, no more no less. (Like Mike's answer)
    Regex pattern = new Regex(@"(?<!\d)\d{10}(?!\d)");

    if(pattern.isMatch(socialSecNumber))
    {
        //Do something
        return true;
    }
    else
    {
        return false;
    }
}

You could've also done it in another way by e.g. using Match and then wrapping a try-catch block around the pattern matching. However, if a wrong input is given quite often, it's quite expensive to throw an exception. Thus, I prefer the above way, in simple cases at least.

What does %5B and %5D in POST requests stand for?

They represent [ and ]. The encoding is called "URL encoding".

html tables & inline styles

This should do the trick:

<table width="400" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="50" height="40" valign="top" rowspan="3">
      <img alt="" src="" width="40" height="40" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
    <td width="350" height="40" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">LAST FIRST</a><br>
REALTOR | P 123.456.789
    </td>
  </tr>
  <tr>
    <td width="350" height="70" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="" src="" width="200" height="60" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
  </tr>
  <tr>
    <td width="350" height="20" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
    </td>
  </tr>
</table>

UPDATE: Adjusted code per the comments:

After viewing your jsFiddle, an important thing to note about tables is that table cell widths in each additional row all have to be the same width as the first, and all cells must add to the total width of your table.

Here is an example that will NOT WORK:

<table width="600" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="200" bgcolor="#252525">&nbsp;
    </td>
    <td width="400" bgcolor="#454545">&nbsp;
    </td>
  </tr>
  <tr>
    <td width="300" bgcolor="#252525">&nbsp;
    </td>
    <td width="300" bgcolor="#454545">&nbsp;
    </td>
  </tr>
</table>

Although the 2nd row does add up to 600, it (and any additional rows) must have the same 200-400 split as the first row, unless you are using colspans. If you use a colspan, you could have one row, but it needs to have the same width as the cells it is spanning, so this works:

<table width="600" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="200" bgcolor="#252525">&nbsp;
    </td>
    <td width="400" bgcolor="#454545">&nbsp;
    </td>
  </tr>
  <tr>
    <td width="600" colspan="2" bgcolor="#353535">&nbsp;
    </td>
  </tr>
</table>

Not a full tutorial, but I hope that helps steer you in the right direction in the future.

Here is the code you are after:

<table width="900" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="57" height="43" valign="top" rowspan="2">
      <img alt="Rashel Adragna" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_head.png" width="47" height="43" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
    <td width="843" height="43" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">RASHEL ADRAGNA</a><br>
REALTOR | P 855.900.24KW
    </td>
  </tr>
  <tr>
    <td width="843" height="64" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="Zopa Realty Group logo" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_logo.png" width="177" height="54" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
  </tr>
  <tr>
    <td width="843" colspan="2" height="20" valign="bottom" align="center" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
    </td>
  </tr>
</table>

You'll note that I've added an extra 10px to some of your table cells. This in combination with align/valigns act as padding between your cells. It is a clever way to aviod actually having to add padding, margins or empty padding cells.

batch file Copy files with certain extensions from multiple directories into one directory

Brandon, short and sweet. Also flexible.

set dSource=C:\Main directory\sub directory
set dTarget=D:\Documents
set fType=*.doc
for /f "delims=" %%f in ('dir /a-d /b /s "%dSource%\%fType%"') do (
    copy /V "%%f" "%dTarget%\" 2>nul
)

Hope this helps.

I would add some checks after the copy (using '||') but i'm not sure how "copy /v" reacts when it encounters an error.

you may want to try this:

copy /V "%%f" "%dTarget%\" 2>nul|| echo En error occured copying "%%F".&& exit /b 1

As the copy line. let me know if you get something out of it (in no position to test a copy failure atm..)

What are Covering Indexes and Covered Queries in SQL Server?

A covering query is on where all the predicates can be matched using the indices on the underlying tables.

This is the first step towards improving the performance of the sql under consideration.

Iterating over dictionaries using 'for' loops

When you iterate through dictionaries using the for .. in ..-syntax, it always iterates over the keys (the values are accessible using dictionary[key]).

To iterate over key-value pairs, in Python 2 use for k,v in s.iteritems(), and in Python 3 for k,v in s.items().

How to position a Bootstrap popover?

Simply add an attribute to your popover! See my JSFiddle if you're in a hurry.

We want to add an ID or a class to a particular popover so that we may customize it the way we want via CSS.

Please note that we don't want to customize all popovers! This is terrible idea.

Here is a simple example - display the popover like this:

enter image description here

_x000D_
_x000D_
// We add the id 'my-popover'_x000D_
$("#my-button").popover({_x000D_
    html : true,_x000D_
    placement: 'bottom'_x000D_
}).data('bs.popover').tip().attr('id', 'my-popover');
_x000D_
#my-popover {_x000D_
    left: -169px!important;_x000D_
}_x000D_
#my-popover .arrow {_x000D_
    left: 90%_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
<button id="my-button" data-toggle="popover">My Button</button>
_x000D_
_x000D_
_x000D_

How to check Django version

Simply type python -m django --version or type pip freeze to see all the versions of installed modules including Django.

Getting JavaScript object key list

If you decide to use Underscore.js you better do

var obj = {
    key1: 'value1',
    key2: 'value2',
    key3: 'value3',
    key4: 'value4'
}

var keys = [];
_.each( obj, function( val, key ) {
    keys.push(key);
});
console.log(keys.lenth, keys);

FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)

Encountered this issue and changing the debug port helped. For some reason, the debug port had to be greater than the app port.

How Can I Truncate A String In jQuery?

Instead of using jQuery, use css property text-overflow:ellipsis. It will automatically truncate the string.

.truncated { display:inline-block; 
             max-width:100px; 
             overflow:hidden; 
             text-overflow:ellipsis; 
             white-space:nowrap; 
           }

How can I set the default timezone in node.js?

Here's an answer for those deploying a Node.js application to Amazon AWS Elastic Beanstalk. I haven't seen this documented anywhere else:

Under Configuration -> Software -> Environment Properties, simply set the key value pair TZ and your time zone e.g. America/Los Angeles, and Apply the change.

You can verify the effect by outputting new Date().toString() in your Node app and paying attention to the time zone suffix.

How to show data in a table by using psql command line interface?

Newer versions: (from 8.4 - mentioned in release notes)

TABLE mytablename;

Longer but works on all versions:

SELECT * FROM mytablename;

You may wish to use \x first if it's a wide table, for readability.

For long data:

SELECT * FROM mytable LIMIT 10;

or similar.

For wide data (big rows), in the psql command line client, it's useful to use \x to show the rows in key/value form instead of tabulated, e.g.

 \x
SELECT * FROM mytable LIMIT 10;

Note that in all cases the semicolon at the end is important.

Removing duplicates from a SQL query (not just "use distinct")

You need to tell the query what value to pick for the other columns, MIN or MAX seem like suitable choices.

 SELECT
   U.NAME, MIN(P.PIC_ID)
 FROM
   USERS U,
   PICTURES P,
   POSTINGS P1
 WHERE
   U.EMAIL_ID = P1.EMAIL_ID AND
   P1.PIC_ID = P.PIC_ID AND
   P.CAPTION LIKE '%car%'
 GROUP BY
   U.NAME;

ORA-12505, TNS:listener does not currently know of SID given in connect descriptor

My issue is resolved when I use the below code:

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@IPAddress:1521/servicename","userName","Password");

Is there a way to perform "if" in python's lambda

This snippet should help you:

x = lambda age: 'Older' if age > 30 else 'Younger'

print(x(40))

Make Iframe to fit 100% of container's remaining height

I think the best way to achieve this scenario using css position. set position relative to your parent div and position:absolute to your iframe.

_x000D_
_x000D_
.container{_x000D_
  width:100%;_x000D_
  position:relative;_x000D_
  height:500px;_x000D_
}_x000D_
_x000D_
iframe{_x000D_
  position:absolute;_x000D_
  width:100%;_x000D_
  height:100%;_x000D_
}
_x000D_
<div class="container">_x000D_
  <iframe src="http://www.w3schools.com">_x000D_
  <p>Your browser does not support iframes.</p>_x000D_
 </iframe>_x000D_
</div>
_x000D_
_x000D_
_x000D_

for other padding and margin issue now a days css3 calc() is very advanced and mostly compatible to all browser as well.

check calc()

What is the difference between a heuristic and an algorithm?

I think Heuristic is more of a constraint used in Learning Based Model in Artificial Intelligent since the future solution states are difficult to predict.

But then my doubt after reading above answers is "How would Heuristic can be successfully applied using Stochastic Optimization Techniques? or can they function as full fledged algorithms when used with Stochastic Optimization?"

http://en.wikipedia.org/wiki/Stochastic_optimization

Calculating Distance between two Latitude and Longitude GeoCoordinates

Based on Elliot Wood's function, and if anyone is interested in a C function, this one is working...

#define SIM_Degree_to_Radian(x) ((float)x * 0.017453292F)
#define SIM_PI_VALUE                         (3.14159265359)

float GPS_Distance(float lat1, float lon1, float lat2, float lon2)
{
   float theta;
   float dist;

   theta = lon1 - lon2;

   lat1 = SIM_Degree_to_Radian(lat1);
   lat2 = SIM_Degree_to_Radian(lat2);
   theta = SIM_Degree_to_Radian(theta);

   dist = (sin(lat1) * sin(lat2)) + (cos(lat1) * cos(lat2) * cos(theta));
   dist = acos(dist);

//   dist = dist * 180.0 / SIM_PI_VALUE;
//   dist = dist * 60.0 * 1.1515;
//   /* Convert to km */
//   dist = dist * 1.609344;

   dist *= 6370.693486F;

   return (dist);
}

You may change it to double. It returns the value in km.

Make DateTimePicker work as TimePicker only in WinForms

Add below event to DateTimePicker

Private Sub DateTimePicker1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles DateTimePicker1.KeyPress
    e.Handled = True
End Sub

package R does not exist

If this error appeared after resolving merge conflicts, simple Build -> Clean project could help.

WPF MVVM: How to close a window

The solution to close a window in wpf that that worked for me is not answered here so i thought i would add my solution too.

        private static Window GetWindow(DependencyObject sender)
        {
            Window window = null;
            if (sender is Window)
                window = (Window)sender;
            if (window == null)
                window = Window.GetWindow(sender);
            return window;
        }
        private void CloseWindow(object sender, RoutedEventArgs e)
        {
            var button = (Button)sender as DependencyObject;

            Window window = GetWindow(button);
                if (window != null)
                    window.Close();
                   // window.Visibility = Visibility.Hidden; 
           // choose between window.close or set window.visibility to close or hide the window.

            //            }
        }

Add CloseWindow event to the button in you window as following.

<Button Content="Cancel" Click="CloseWindow" >

Upgrade to python 3.8 using conda

Open Anaconda Prompt (base):

  1. Update conda:
conda update -n base -c defaults conda
  1. Create new environment with Python 3.8:
conda create -n python38 python=3.8
  1. Activate your new Python 3.8 environment:
conda activate python38
  1. Start Python 3.8:
python

Hide div if screen is smaller than a certain width

The problem I was having is my css media queries and my IF statement in Jquery clashing. They were both set to 700px but one would think it's hit 700px before the other.

To get around this I created a empty Div right at the top of my HTML(outside my main container)

<div id="max-width"></div>

In css I set this div to display none

 #max-width {
        display: none;
    }

In my JS created a function

var hasSwitched = function () {
    var maxWidth = parseInt($('#max-width').css('max-width'), 10);
    return !isNaN(maxWidth);
};

So in my IF statement instead of saying if (hasSwitched<700) perform the following code, I did the following

if (!hasSwitched()) { Your code

}

else{ your code

}

By doing this CSS tells Jquery when it's hit 700px. So css and jquery are both synchronized... rather than having a couple of pixels difference. Do give this a try peeps it shall definitely not disappoint.

To get this same logic working for IE8 I used the Respond.js plugin(which also definitely works) It lets you use media queries for IE8. Only thing that wasn't supported was the viewport width and viewport height... hence my reason to try get my css and JS working together. Hope this helps you guys

How to add the JDBC mysql driver to an Eclipse project?

you haven't loaded driver into memory. use this following in init()

Class.forName("com.mysql.jdbc.Driver");

Also, you missed a colon (:) in url, use this

String mySqlUrl = "jdbc:mysql://localhost:3306/mysql";

Detect page change on DataTable

This working good

$('#id-of-table').on('draw.dt', function() {
    // do action here
});

inverting image in Python with OpenCV

You almost did it. You were tricked by the fact that abs(imagem-255) will give a wrong result since your dtype is an unsigned integer. You have to do (255-imagem) in order to keep the integers unsigned:

def inverte(imagem, name):
    imagem = (255-imagem)
    cv2.imwrite(name, imagem)

You can also invert the image using the bitwise_not function of OpenCV:

imagem = cv2.bitwise_not(imagem)

Lock, mutex, semaphore... what's the difference?

There are a lot of misconceptions regarding these words.

This is from a previous post (https://stackoverflow.com/a/24582076/3163691) which fits superb here:

1) Critical Section= User object used for allowing the execution of just one active thread from many others within one process. The other non selected threads (@ acquiring this object) are put to sleep.

[No interprocess capability, very primitive object].

2) Mutex Semaphore (aka Mutex)= Kernel object used for allowing the execution of just one active thread from many others, among different processes. The other non selected threads (@ acquiring this object) are put to sleep. This object supports thread ownership, thread termination notification, recursion (multiple 'acquire' calls from same thread) and 'priority inversion avoidance'.

[Interprocess capability, very safe to use, a kind of 'high level' synchronization object].

3) Counting Semaphore (aka Semaphore)= Kernel object used for allowing the execution of a group of active threads from many others. The other non selected threads (@ acquiring this object) are put to sleep.

[Interprocess capability however not very safe to use because it lacks following 'mutex' attributes: thread termination notification, recursion?, 'priority inversion avoidance'?, etc].

4) And now, talking about 'spinlocks', first some definitions:

Critical Region= A region of memory shared by 2 or more processes.

Lock= A variable whose value allows or denies the entrance to a 'critical region'. (It could be implemented as a simple 'boolean flag').

Busy waiting= Continuosly testing of a variable until some value appears.

Finally:

Spin-lock (aka Spinlock)= A lock which uses busy waiting. (The acquiring of the lock is made by xchg or similar atomic operations).

[No thread sleeping, mostly used at kernel level only. Ineffcient for User level code].

As a last comment, I am not sure but I can bet you some big bucks that the above first 3 synchronizing objects (#1, #2 and #3) make use of this simple beast (#4) as part of their implementation.

Have a good day!.

References:

-Real-Time Concepts for Embedded Systems by Qing Li with Caroline Yao (CMP Books).

-Modern Operating Systems (3rd) by Andrew Tanenbaum (Pearson Education International).

-Programming Applications for Microsoft Windows (4th) by Jeffrey Richter (Microsoft Programming Series).

Also, you can take a look at look at: https://stackoverflow.com/a/24586803/3163691

How to align flexbox columns left and right?

I came up with 4 methods to achieve the results. Here is demo

Method 1:

#a {
    margin-right: auto;
}

Method 2:

#a {
    flex-grow: 1;
}

Method 3:

#b {
    margin-left: auto;
}

Method 4:

#container {
    justify-content: space-between;
}

SQL Server Management Studio – tips for improving the TSQL coding process

I have a scheduled task that each night writes each object (table, sproc, etc.) to a file. I have full-text search indexing set on the output directory, so when I'm looking for a certain string (e.g., a constant) that is buried somewhere in the DB I can very quickly find it.

Within Management Studio you can use the Tasks > Generate Scrips... command to see how to perform this.

JavaScript - document.getElementByID with onClick

Perhaps you might want to use "addEventListener"

document.getElementById("test").addEventListener('click',function ()
{
    foo2();
   }  ); 

Hope it's still useful for you

How to restart a single container with docker-compose

Simple 'docker' command knows nothing about 'worker' container. Use command like this

docker-compose -f docker-compose.yml restart worker

Display html text in uitextview

For Swift 4, Swift 4.2: and Swift 5

let htmlString = """
    <html>
        <head>
            <style>
                body {
                    background-color : rgb(230, 230, 230);
                    font-family      : 'Arial';
                    text-decoration  : none;
                }
            </style>
        </head>
        <body>
            <h1>A title</h1>
            <p>A paragraph</p>
            <b>bold text</b>
        </body>
    </html>
    """

let htmlData = NSString(string: htmlString).data(using: String.Encoding.unicode.rawValue)

let options = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html]

let attributedString = try! NSAttributedString(data: htmlData!, options: options, documentAttributes: nil)

textView.attributedText = attributedString

For Swift 3:

let htmlString = """
    <html>
        <head>
            <style>
                body {
                    background-color : rgb(230, 230, 230);
                    font-family      : 'Arial';
                    text-decoration  : none;
                }
            </style>
        </head>
        <body>
            <h1>A title</h1>
            <p>A paragraph</p>
            <b>bold text</b>
        </body>
    </html>
    """

let htmlData = NSString(string: htmlString).data(using: String.Encoding.unicode.rawValue)

let attributedString = try! NSAttributedString(data: htmlData!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)

textView.attributedText = attributedString

Using Postman to access OAuth 2.0 Google APIs

This is an old question, but it has no chosen answer, and I just solved this problem myself. Here's my solution:

  1. Make sure you are set up to work with your Google API in the first place. See Google's list of prerequisites. I was working with Google My Business, so I also went through it's Get Started process.

  2. In the OAuth 2.0 playground, Step 1 requires you to select which API you want to authenticate. Select or input as applicable for your case (in my case for Google My Business, I had to input https://www.googleapis.com/auth/plus.business.manage into the "Input your own scopes" input field). Note: this is the same as what's described in step 6 of the "Make a simple HTTP request" section of the Get Started guide.

  3. Assuming successful authentication, you should get an "Access token" returned in the "Step 1's result" step in the OAuth playground. Copy this token to your clipboard.

  4. Open Postman and open whichever collection you want as necessary.

  5. In Postman, make sure "GET" is selected as the request type, and click on the "Authorization" tab below the request type drop-down.

  6. In the Authorization "TYPE" dropdown menu, select "Bearer Token"

  7. Paste your previously copied "Access Token" which you copied from the OAuth playground into the "Token" field which displays in Postman.

  8. Almost there! To test if things work, put https://mybusiness.googleapis.com/v4/accounts/ into the main URL input bar in Postman and click the send button. You should get a JSON list of accounts back in the response that looks something like the following:

    
    {
        "accounts": [
            {
                "name": "accounts/REDACTED",
                "accountName": "REDACTED",
                "type": "PERSONAL",
                "state": {
                    "status": "UNVERIFIED"
                }
            },
            {
                "name": "accounts/REDACTED",
                "accountName": "REDACTED",
                "type": "LOCATION_GROUP",
                "role": "OWNER",
                "state": {
                    "status": "UNVERIFIED"
                },
                "permissionLevel": "OWNER_LEVEL"
            }
        ]
    }
    

How to find and replace with regex in excel

If you want a formula to do it then:

=IF(ISNUMBER(SEARCH("*texts are *",A1)),LEFT(A1,FIND("texts are ",A1) + 9) & "WORD",A1)

This will do it. Change `"WORD" To the word you want.

How does the modulus operator work?

Basically modulus Operator gives you remainder simple Example in maths what's left over/remainder of 11 divided by 3? answer is 2

for same thing C++ has modulus operator ('%')

Basic code for explanation

#include <iostream>
using namespace std;


int main()
{
    int num = 11;
    cout << "remainder is " << (num % 3) << endl;

    return 0;
}

Which will display

remainder is 2

Could not load file or assembly 'System.Web.Mvc'

If your NOT using a hosting provider, and you have access to the server to install ... Then install the MVC 3 update tools, do that... it will save you hours of problems on a windows 2003 server / IIS6 machine. , I commented on this page here Nuget.Core.dll version number mismatch

PHP post_max_size overrides upload_max_filesize

Your server configuration settings allows users to upload files upto 16MB (because you have set upload_max_filesize = 16Mb) but the post_max_size accepts post data upto 8MB only. This is why it throws an error.

Quoted from the official PHP site:

  1. To upload large files, post_max_size value must be larger than upload_max_filesize.

  2. memory_limit should be larger than post_max_size

You should always set your post_max_size value greater than the upload_max_filesize value.

What does the 'export' command do?

In simple terms, environment variables are set when you open a new shell session. At any time if you change any of the variable values, the shell has no way of picking that change. that means the changes you made become effective in new shell sessions. The export command, on the other hand, provides the ability to update the current shell session about the change you made to the exported variable. You don't have to wait until new shell session to use the value of the variable you changed.

Android: adb: Permission Denied

data partition not accessible for non root user, if you want to access it you must root your phone.

adb root not work for all product and depend in phone build type.

in new version on android studio you can explore /data/data path for debuggable apps.

How to convert JSON data into a Python object

Check out the section titled Specializing JSON object decoding in the json module documentation. You can use that to decode a JSON object into a specific Python type.

Here's an example:

class User(object):
    def __init__(self, name, username):
        self.name = name
        self.username = username

import json
def object_decoder(obj):
    if '__type__' in obj and obj['__type__'] == 'User':
        return User(obj['name'], obj['username'])
    return obj

json.loads('{"__type__": "User", "name": "John Smith", "username": "jsmith"}',
           object_hook=object_decoder)

print type(User)  # -> <type 'type'>

Update

If you want to access data in a dictionary via the json module do this:

user = json.loads('{"__type__": "User", "name": "John Smith", "username": "jsmith"}')
print user['name']
print user['username']

Just like a regular dictionary.

HttpContext.Current.Request.Url.Host what it returns?

Yes, as long as the url you type into the browser www.someshopping.com and you aren't using url rewriting then

string currentURL = HttpContext.Current.Request.Url.Host;

will return www.someshopping.com

Note the difference between a local debugging environment and a production environment

How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#?

This was in response to your other question, that looks like it's been deleted....the point still stands.

Looks like a classic Unicode to ASCII issue. The trick would be to find where it's happening.

.NET works fine with Unicode, assuming it's told it's Unicode to begin with (or left at the default).

My guess is that your receiving app can't handle it. So, I'd probably use the ASCIIEncoder with an EncoderReplacementFallback with String.Empty:

using System.Text;

string inputString = GetInput();
var encoder = ASCIIEncoding.GetEncoder();
encoder.Fallback = new EncoderReplacementFallback(string.Empty);

byte[] bAsciiString = encoder.GetBytes(inputString);

// Do something with bytes...
// can write to a file as is
File.WriteAllBytes(FILE_NAME, bAsciiString);
// or turn back into a "clean" string
string cleanString = ASCIIEncoding.GetString(bAsciiString); 
// since the offending bytes have been removed, can use default encoding as well
Assert.AreEqual(cleanString, Default.GetString(bAsciiString));

Of course, in the old days, we'd just loop though and remove any chars greater than 127...well, those of us in the US at least. ;)

recursion versus iteration

Is it correct to say that everywhere recursion is used a for loop could be used?

Yes, because recursion in most CPUs is modeled with loops and a stack data structure.

And if recursion is usually slower what is the technical reason for using it?

It is not "usually slower": it's recursion that is applied incorrectly that's slower. On top of that, modern compilers are good at converting some recursions to loops without even asking.

And if it is always possible to convert an recursion into a for loop is there a rule of thumb way to do it?

Write iterative programs for algorithms best understood when explained iteratively; write recursive programs for algorithms best explained recursively.

For example, searching binary trees, running quicksort, and parsing expressions in many programming languages is often explained recursively. These are best coded recursively as well. On the other hand, computing factorials and calculating Fibonacci numbers are much easier to explain in terms of iterations. Using recursion for them is like swatting flies with a sledgehammer: it is not a good idea, even when the sledgehammer does a really good job at it+.


+ I borrowed the sledgehammer analogy from Dijkstra's "Discipline of Programming".

final keyword in method parameters

Java is only pass-by-value. (or better - pass-reference-by-value)

So the passed argument and the argument within the method are two different handlers pointing to the same object (value).

Therefore if you change the state of the object, it is reflected to every other variable that's referencing it. But if you re-assign a new object (value) to the argument, then other variables pointing to this object (value) do not get re-assigned.

How to parse date string to Date?

I had this issue, and I set the Locale to US, then it work.

static DateFormat visitTimeFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy",Locale.US);

for String "Sun Jul 08 00:06:30 UTC 2012"

Using setDate in PreparedStatement

The problem you're having is that you're passing incompatible formats from a formatted java.util.Date to construct an instance of java.sql.Date, which don't behave in the same way when using valueOf() since they use different formats.

I also can see that you're aiming to persist hours and minutes, and I think that you'd better change the data type to java.sql.Timestamp, which supports hours and minutes, along with changing your database field to DATETIME or similar (depending on your database vendor).

Anyways, if you want to change from java.util.Date to java.sql.Date, I suggest to use

java.util.Date date = Calendar.getInstance().getTime();
java.sql.Date sqlDate = new java.sql.Date(date.getTime()); 
// ... more code here
prs.setDate(sqlDate);

How to delete images from a private docker registry?

I've faced same problem with my registry then i tried the solution listed below from a blog page. It works.

Step 1: Listing catalogs

You can list your catalogs by calling this url:

http://YourPrivateRegistyIP:5000/v2/_catalog

Response will be in the following format:

{
  "repositories": [
    <name>,
    ...
  ]
}

Step 2: Listing tags for related catalog

You can list tags of your catalog by calling this url:

http://YourPrivateRegistyIP:5000/v2/<name>/tags/list

Response will be in the following format:

{
"name": <name>,
"tags": [
    <tag>,
    ...
]

}

Step 3: List manifest value for related tag

You can run this command in docker registry container:

curl -v --silent -H "Accept: application/vnd.docker.distribution.manifest.v2+json" -X GET http://localhost:5000/v2/<name>/manifests/<tag> 2>&1 | grep Docker-Content-Digest | awk '{print ($3)}'

Response will be in the following format:

sha256:6de813fb93debd551ea6781e90b02f1f93efab9d882a6cd06bbd96a07188b073

Run the command given below with manifest value:

curl -v --silent -H "Accept: application/vnd.docker.distribution.manifest.v2+json" -X DELETE http://127.0.0.1:5000/v2/<name>/manifests/sha256:6de813fb93debd551ea6781e90b02f1f93efab9d882a6cd06bbd96a07188b073

Step 4: Delete marked manifests

Run this command in your docker registy container:

bin/registry garbage-collect  /etc/docker/registry/config.yml  

Here is my config.yml

root@c695814325f4:/etc# cat /etc/docker/registry/config.yml
version: 0.1
log:
  fields:
  service: registry
storage:
    cache:
        blobdescriptor: inmemory
    filesystem:
        rootdirectory: /var/lib/registry
    delete:
        enabled: true
http:
    addr: :5000
    headers:
        X-Content-Type-Options: [nosniff]
health:
  storagedriver:
    enabled: true
    interval: 10s
    threshold: 3

Working with dictionaries/lists in R

You do not even need lists if your "number" values are all of the same mode. If I take Dirk Eddelbuettel's example:

> foo <- c(12, 22, 33)
> names(foo) <- c("tic", "tac", "toe")
> foo
tic tac toe
 12  22  33
> names(foo)
[1] "tic" "tac" "toe"

Lists are only required if your values are either of mixed mode (for example characters and numbers) or vectors.

For both lists and vectors, an individual element can be subsetted by name:

> foo["tac"]
tac 
 22 

Or for a list:

> foo[["tac"]]
[1] 22

Disabling same-origin policy in Safari

goto,

Safari -> Preferences -> Advanced

then at the bottom tick Show Develop Menu in menu bar

then in the Develop Menu tick Disable Cross-Origin Restrictions

How to deal with SQL column names that look like SQL keywords?

The following will work perfectly:

SELECT DISTINCT table.from AS a FROM table

How to make inactive content inside a div?

div[disabled]
{
  pointer-events: none;
  opacity: 0.7;
}

The above code makes the contents of the div disabled. You can make div disabled by adding disabled attribute.

<div disabled>
  /* Contents */
</div>

How to use template module with different set of variables?

I did it in this way.

In tasks/main.yml

- name: template test
  template: 
        src=myTemplateFile.j2
        dest={{item}}
   with_dict: some_dict

and in vars/main.yml

some_dict:
  /path/to/dest1:
    var1: 1
    var2: 2
  /path/to/dest2:
    var1: 3
    var2: 4

and in templates/myTemplateFile.j2

some_var = {{ item.value.var1 }}
some_other_var = {{ item.value.var2 }}

Hope this solves your problem.

How to make primary key as autoincrement for Room Persistence lib

This works for me:

@Entity(tableName = "note_table")
data class Note(
    @ColumnInfo(name="title") var title: String,
    @ColumnInfo(name="description") var description: String = "",
    @ColumnInfo(name="priority") var priority: Int,
    @PrimaryKey(autoGenerate = true) var id: Int = 0//last so that we don't have to pass an ID value or named arguments
)

Note that the id is last to avoid having to use named arguments when creating the entity, before inserting it into Room. Once it's been added to room, use the id when updating the entity.

Pivoting rows into columns dynamically in Oracle

Oracle 11g provides a PIVOT operation that does what you want.

Oracle 11g solution

select * from
(select id, k, v from _kv) 
pivot(max(v) for k in ('name', 'age', 'gender', 'status')

(Note: I do not have a copy of 11g to test this on so I have not verified its functionality)

I obtained this solution from: http://orafaq.com/wiki/PIVOT

EDIT -- pivot xml option (also Oracle 11g)
Apparently there is also a pivot xml option for when you do not know all the possible column headings that you may need. (see the XML TYPE section near the bottom of the page located at http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html)

select * from
(select id, k, v from _kv) 
pivot xml (max(v)
for k in (any) )

(Note: As before I do not have a copy of 11g to test this on so I have not verified its functionality)

Edit2: Changed v in the pivot and pivot xml statements to max(v) since it is supposed to be aggregated as mentioned in one of the comments. I also added the in clause which is not optional for pivot. Of course, having to specify the values in the in clause defeats the goal of having a completely dynamic pivot/crosstab query as was the desire of this question's poster.

How to retrieve form values from HTTPPOST, dictionary or?

The answers are very good but there is another way in the latest release of MVC and .NET that I really like to use, instead of the "old school" FormCollection and Request keys.


Consider a HTML snippet contained within a form tag that either does an AJAX or FORM POST.

<input type="hidden"   name="TrackingID" 
<input type="text"     name="FirstName"  id="firstnametext" />
<input type="checkbox" name="IsLegal"  value="Do you accept terms and conditions?" />

Your controller will actually parse the form data and try to deliver it to you as parameters of the defined type. I included checkbox because it is a tricky one. It returns text "on" if checked and null if not checked. The requirement though is that these defined variables MUST exists (unless nullable(remember though that string is nullable)) otherwise the AJAX or POST back will fail.

[HttpPost]
public ActionResult PostBack(int TrackingID, string FirstName, string IsLegal){
    MyData.SaveRequest(TrackingID,FirstName, IsLegal == null ? false : true);
}

You can also post back a model without using any razor helpers. I have come across that this is needed some times.

public Class HomeModel
{
  public int HouseNumber { get; set; }
  public string StreetAddress { get; set; }
}

The HTML markup will simply be ...

<input type="text" name="variableName.HouseNumber" id="whateverid" >

and your controller(Razor Engine) will intercept the Form Variable "variableName" (name is as you like but keep it consistent) and try to build it up and cast it to MyModel.

[HttpPost]
public ActionResult PostBack(HomeModel variableName){
    postBack.HouseNumber; //The value user entered
    postBack.StreetAddress; //the default value of NULL.
}

When a controller is expecting a Model (in this case HomeModel) you do not have to define ALL the fields as the parser will just leave them at default, usually NULL. The nice thing is you can mix and match various models on the Mark-up and the post back parse will populate as much as possible. You do not need to define a model on the page or use any helpers.

TIP: The name of the parameter in the controller is the name defined in the HTML mark-up "name=" not the name of the Model but the name of the expected variable in the !


Using List<> is bit more complex in its mark-up.

<input type="text" name="variableNameHere[0].HouseNumber" id="id"           value="0">
<input type="text" name="variableNameHere[1].HouseNumber" id="whateverid-x" value="1">
<input type="text" name="variableNameHere[2].HouseNumber"                   value="2">
<input type="text" name="variableNameHere[3].HouseNumber" id="whateverid22" value="3">

Index on List<> MUST always be zero based and sequential. 0,1,2,3.

[HttpPost]
public ActionResult PostBack(List<HomeModel> variableNameHere){
     int counter = MyHomes.Count()
     foreach(var home in MyHomes)
     { ... }
}

Using IEnumerable<> for non zero based and non sequential indices post back. We need to add an extra hidden input to help the binder.

<input type="hidden" name="variableNameHere.Index" value="278">
<input type="text" name="variableNameHere[278].HouseNumber" id="id"      value="3">

<input type="hidden" name="variableNameHere.Index" value="99976">
<input type="text" name="variableNameHere[99976].HouseNumber" id="id3"   value="4">

<input type="hidden" name="variableNameHere.Index" value="777">
<input type="text" name="variableNameHere[777].HouseNumber" id="id23"    value="5">

And the code just needs to use IEnumerable and call ToList()

[HttpPost]
public ActionResult PostBack(IEnumerable<MyModel> variableNameHere){
     int counter = variableNameHere.ToList().Count()
     foreach(var home in variableNameHere)
     { ... }
}

It is recommended to use a single Model or a ViewModel (Model contianing other models to create a complex 'View' Model) per page. Mixing and matching as proposed could be considered bad practice, but as long as it works and is readable its not BAD. It does however, demonstrate the power and flexiblity of the Razor engine.

So if you need to drop in something arbitrary or override another value from a Razor helper, or just do not feel like making your own helpers, for a single form that uses some unusual combination of data, you can quickly use these methods to accept extra data.

How to render a PDF file in Android

I used the below code to open and print the PDF using Wi-Fi. I am sending my whole code, and I hope it is helpful.

public class MainActivity extends Activity {

    int Result_code = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button mButton = (Button)findViewById(R.id.button1);

        mButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                 PrintManager printManager = (PrintManager)getSystemService(Context.PRINT_SERVICE);
                String jobName =  " Document";
                printManager.print(jobName, pda, null);
            }
        });
    }


    public void openDocument(String name) {

        Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
        File file = new File(name);
        String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
        String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        if (extension.equalsIgnoreCase("") || mimetype == null) {
            // if there is no extension or there is no definite mimetype, still try to open the file
            intent.setDataAndType(Uri.fromFile(file), "text/*");
        }
        else {
            intent.setDataAndType(Uri.fromFile(file), mimetype);
        }

        // custom message for the intent
        startActivityForResult((Intent.createChooser(intent, "Choose an Application:")), Result_code);
        //startActivityForResult(intent, Result_code);
        //Toast.makeText(getApplicationContext(),"There are no email clients installed.", Toast.LENGTH_SHORT).show();
    }


    @SuppressLint("NewApi")
    PrintDocumentAdapter pda = new PrintDocumentAdapter(){

        @Override
        public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback){
            InputStream input = null;
            OutputStream output = null;

            try {
                String filename = Environment.getExternalStorageDirectory()    + "/" + "Holiday.pdf";
                File file = new File(filename);
                input = new FileInputStream(file);
                output = new FileOutputStream(destination.getFileDescriptor());

                byte[] buf = new byte[1024];
                int bytesRead;

                while ((bytesRead = input.read(buf)) > 0) {
                     output.write(buf, 0, bytesRead);
                }

                callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});
            }
            catch (FileNotFoundException ee){
                //Catch exception
            }
            catch (Exception e) {
                //Catch exception
            }
            finally {
                try {
                    input.close();
                    output.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras){

            if (cancellationSignal.isCanceled()) {
                callback.onLayoutCancelled();
                return;
            }

           // int pages = computePageCount(newAttributes);

            PrintDocumentInfo pdi = new PrintDocumentInfo.Builder("Name of file").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build();

            callback.onLayoutFinished(pdi, true);
        }
    };
}

How to update Ruby with Homebrew?

Adding to the selected answer (as I haven't enough rep to add comment), one way to see the list of available versions (from ref) try:

$ rbenv install -l

How do I update a Mongo document after inserting it?

According to the latest documentation about PyMongo titled Insert a Document (insert is deprecated) and following defensive approach, you should insert and update as follows:

result = mycollection.insert_one(post)
post = mycollection.find_one({'_id': result.inserted_id})

if post is not None:
    post['newfield'] = "abc"
    mycollection.save(post)

jQuery Show-Hide DIV based on Checkbox Value

Try this

$('.yourchkboxes').change(function(){
    $('.yourbutton').toggle($('.yourchkboxes:checked').length > 0);
});

So it will check for at least one checkbox is checked or not.

Building executable jar with maven?

If you don't want execute assembly goal on package, you can use next command:

mvn package assembly:single

Here package is keyword.

finding multiples of a number in Python

def multiples(n,m,starting_from=1,increment_by=1):
    """
    # Where n is the number 10 and m is the number 2 from your example. 
    # In case you want to print the multiples starting from some other number other than 1 then you could use the starting_from parameter
    # In case you want to print every 2nd multiple or every 3rd multiple you could change the increment_by 
    """
    print [ n*x for x in range(starting_from,m+1,increment_by) ] 

Limit file format when using <input type="file">?

You can use the change event to monitor what the user selects and notify them at that point that the file is not acceptable. It does not limit the actual list of files displayed, but it is the closest you can do client-side, besides the poorly supported accept attribute.

_x000D_
_x000D_
var file = document.getElementById('someId');_x000D_
_x000D_
file.onchange = function(e) {_x000D_
  var ext = this.value.match(/\.([^\.]+)$/)[1];_x000D_
  switch (ext) {_x000D_
    case 'jpg':_x000D_
    case 'bmp':_x000D_
    case 'png':_x000D_
    case 'tif':_x000D_
      alert('Allowed');_x000D_
      break;_x000D_
    default:_x000D_
      alert('Not allowed');_x000D_
      this.value = '';_x000D_
  }_x000D_
};
_x000D_
<input type="file" id="someId" />
_x000D_
_x000D_
_x000D_

JSFiddle

Installing Node.js (and npm) on Windows 10

I had the same problem, what helped we was turning of my anti virus protection for like 10 minutes while node installed and it worked like a charm.

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

There is a way to accomplish this. The magic is to create a combined jacoco.exec file. And with maven 3.3.1 there is an easy way to get this. Here my profile:

<profile>
    <id>runSonar</id>
    <activation>
        <property>
            <name>runSonar</name>
            <value>true</value>
        </property>
    </activation>
    <properties>
        <sonar.language>java</sonar.language>
        <sonar.host.url>http://sonar.url</sonar.host.url>
        <sonar.login>tokenX</sonar.login>
        <sonar.jacoco.reportMissing.force.zero>true</sonar.jacoco.reportMissing.force.zero>
        <sonar.jacoco.reportPath>${jacoco.destFile}</sonar.jacoco.reportPath>
        <jacoco.destFile>${maven.multiModuleProjectDirectory}/target/jacoco_analysis/jacoco.exec</jacoco.destFile>
    </properties>
    <build>
        <plugins>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>default-prepare-agent</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                        <configuration>
                            <append>true</append>
                            <destFile>${jacoco.destFile}</destFile>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.sonarsource.scanner.maven</groupId>
                    <artifactId>sonar-maven-plugin</artifactId>
                    <version>3.2</version>
                </plugin>
                <plugin>
                    <groupId>org.jacoco</groupId>
                    <artifactId>jacoco-maven-plugin</artifactId>
                    <version>0.7.8</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</profile>

If you add this profile to your parent pom and call mvn clean install sonar:sonar -DrunSonar you get the complete coverage.

The magic here is maven.multiModuleProjectDirectory. This folder is always the folder where you started your maven build.

SQL Insert into table only if record doesn't exist

Although the answer I originally marked as chosen is correct and achieves what I asked there is a better way of doing this (which others acknowledged but didn't go into). A composite unique index should be created on the table consisting of fund_id and date.

ALTER TABLE funds ADD UNIQUE KEY `fund_date` (`fund_id`, `date`);

Then when inserting a record add the condition when a conflict is encountered:

INSERT INTO funds (`fund_id`, `date`, `price`)
    VALUES (23, DATE('2013-02-12'), 22.5)
        ON DUPLICATE KEY UPDATE `price` = `price`; --this keeps the price what it was (no change to the table) or:

INSERT INTO funds (`fund_id`, `date`, `price`)
    VALUES (23, DATE('2013-02-12'), 22.5)
        ON DUPLICATE KEY UPDATE `price` = 22.5; --this updates the price to the new value

This will provide much better performance to a sub-query and the structure of the table is superior. It comes with the caveat that you can't have NULL values in your unique key columns as they are still treated as values by MySQL.

Detecting an undefined object property

The usual way to check if the value of a property is the special value undefined, is:

if(o.myProperty === undefined) {
  alert("myProperty value is the special value `undefined`");
}

To check if an object does not actually have such a property, and will therefore return undefined by default when you try and access it:

if(!o.hasOwnProperty('myProperty')) {
  alert("myProperty does not exist");
}

To check if the value associated with an identifier is the special value undefined, or if that identifier has not been declared. Note: this method is the only way of referring to an undeclared (note: different from having a value of undefined) identifier without an early error:

if(typeof myVariable === 'undefined') {
  alert('myVariable is either the special value `undefined`, or it has not been declared');
}

In versions of JavaScript prior to ECMAScript 5, the property named "undefined" on the global object was writeable, and therefore a simple check foo === undefined might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.

However, in modern JavaScript, "undefined" is not a keyword, and so variables inside functions can be named "undefined" and shadow the global property.

If you are worried about this (unlikely) edge case, you can use the void operator to get at the special undefined value itself:

if(myVariable === void 0) {
  alert("myVariable is the special value `undefined`");
}

Android Preventing Double Click On A Button

The Best and simple solution i found is 
1. to create a boolean and set as false (default) like
private boolean itemClicked = false;

/* for a safer side you can also declare boolean false in onCreate() also. */
and at onclick() method check 
2. if(!itemClicked)
{
itemClicked = true;
// rest of your coding functionality goes here of onClick method.
}
3. last step is to set boolean false in onResume()
@override
onResume()
{
super.onResume(0);
itemClicked = false;
}

How to truncate float values?

If you mean when printing, then the following should work:

print '%.3f' % number

How do I compare two strings in Perl?

In addtion to Sinan Ünür comprehensive listing of string comparison operators, Perl 5.10 adds the smart match operator.

The smart match operator compares two items based on their type. See the chart below for the 5.10 behavior (I believe this behavior is changing slightly in 5.10.1):

perldoc perlsyn "Smart matching in detail":

The behaviour of a smart match depends on what type of thing its arguments are. It is always commutative, i.e. $a ~~ $b behaves the same as $b ~~ $a . The behaviour is determined by the following table: the first row that applies, in either order, determines the match behaviour.

  $a      $b        Type of Match Implied    Matching Code
  ======  =====     =====================    =============
  (overloading trumps everything)

  Code[+] Code[+]   referential equality     $a == $b   
  Any     Code[+]   scalar sub truth         $b->($a)   

  Hash    Hash      hash keys identical      [sort keys %$a]~~[sort keys %$b]
  Hash    Array     hash slice existence     grep {exists $a->{$_}} @$b
  Hash    Regex     hash key grep            grep /$b/, keys %$a
  Hash    Any       hash entry existence     exists $a->{$b}

  Array   Array     arrays are identical[*]
  Array   Regex     array grep               grep /$b/, @$a
  Array   Num       array contains number    grep $_ == $b, @$a 
  Array   Any       array contains string    grep $_ eq $b, @$a 

  Any     undef     undefined                !defined $a
  Any     Regex     pattern match            $a =~ /$b/ 
  Code()  Code()    results are equal        $a->() eq $b->()
  Any     Code()    simple closure truth     $b->() # ignoring $a
  Num     numish[!] numeric equality         $a == $b   
  Any     Str       string equality          $a eq $b   
  Any     Num       numeric equality         $a == $b   

  Any     Any       string equality          $a eq $b   

+ - this must be a code reference whose prototype (if present) is not ""
(subs with a "" prototype are dealt with by the 'Code()' entry lower down) 
* - that is, each element matches the element of same index in the other
array. If a circular reference is found, we fall back to referential 
equality.   
! - either a real number, or a string that looks like a number

The "matching code" doesn't represent the real matching code, of course: it's just there to explain the intended meaning. Unlike grep, the smart match operator will short-circuit whenever it can.

Custom matching via overloading You can change the way that an object is matched by overloading the ~~ operator. This trumps the usual smart match semantics. See overload.

Receiving JSON data back from HTTP request

I think the shortest way is:

var client = new HttpClient();
string reqUrl = $"http://myhost.mydomain.com/api/products/{ProdId}";
var prodResp = await client.GetAsync(reqUrl);
if (!prodResp.IsSuccessStatusCode){
    FailRequirement();
}
var prods = await prodResp.Content.ReadAsAsync<Products>();

Invalidating JSON Web Tokens

I would keep a record of the jwt version number on the user model. New jwt tokens would set their version to this.

When you validate the jwt, simply check that it has a version number equal to the users current jwt version.

Any time you want to invalidate old jwts, just bump the users jwt version number.

LINQ select in C# dictionary

If you are searching by the fieldname1 value, try this:

var r = exitDictionary
   .Select(i => i.Value).Cast<Dictionary<string, object>>()
   .Where(d => d.ContainsKey("fieldname1"))
   .Select(d => d["fieldname1"]).Cast<List<Dictionary<string, string>>>()
   .SelectMany(d1 => 
       d1
        .Where(d => d.ContainsKey("valueTitle"))
        .Select(d => d["valueTitle"])
        .Where(v => v != null)).ToList();

If you are looking by the type of the value in the subDictionary (Dictionary<string, object> explicitly), you may do this:

var r = exitDictionary
   .Select(i => i.Value).Cast<Dictionary<string, object>>()
   .SelectMany(d=>d.Values)
   .OfType<List<Dictionary<string, string>>>()
   .SelectMany(d1 => 
       d1
        .Where(d => d.ContainsKey("valueTitle"))
        .Select(d => d["valueTitle"])
        .Where(v => v != null)).ToList();

Both alternatives will return:

title1
title2
title3
title1
title2
title3

How to right align widget in horizontal linear layout Android?

just add android:gravity="right" in your Liner Layout.

How can I force input to uppercase in an ASP.NET textbox?

I just did something similar today. Here is the modified version:

<asp:TextBox ID="txtInput" runat="server"></asp:TextBox>
<script type="text/javascript">
    function setFormat() {
        var inp = document.getElementById('ctl00_MainContent_txtInput');
        var x = inp.value;
        inp.value = x.toUpperCase();
    }

    var inp = document.getElementById('ctl00_MainContent_txtInput');
    inp.onblur = function(evt) {
        setFormat();
    };
</script>

Basically, the script attaches an event that fires when the text box loses focus.

How to check if any Checkbox is checked in Angular

I've a sample for multiple data with their subnode 3 list , each list has attribute and child attribute:

var list1 = {
    name: "Role A",
    name_selected: false,
    subs: [{
        sub: "Read",
        id: 1,
        selected: false
    }, {
        sub: "Write",
        id: 2,
        selected: false
    }, {
        sub: "Update",
        id: 3,
        selected: false
    }],
};
var list2 = {
    name: "Role B",
    name_selected: false,
    subs: [{
        sub: "Read",
        id: 1,
        selected: false
    }, {
        sub: "Write",
        id: 2,
        selected: false
    }],
};
var list3 = {
    name: "Role B",
    name_selected: false,
    subs: [{
        sub: "Read",
        id: 1,
        selected: false
    }, {
        sub: "Update",
        id: 3,
        selected: false
    }],
};

Add these to Array :

newArr.push(list1);
newArr.push(list2);
newArr.push(list3);
$scope.itemDisplayed = newArr;

Show them in html:

<li ng-repeat="item in itemDisplayed" class="ng-scope has-pretty-child">
    <div>
        <ul>
            <input type="checkbox" class="checkall" ng-model="item.name_selected" ng-click="toggleAll(item)" />
            <span>{{item.name}}</span>
            <div>
                <li ng-repeat="sub in item.subs" class="ng-scope has-pretty-child">
                    <input type="checkbox" kv-pretty-check="" ng-model="sub.selected" ng-change="optionToggled(item,item.subs)"><span>{{sub.sub}}</span>
                </li>
            </div>
        </ul>
    </div>
</li>

And here is the solution to check them:

$scope.toggleAll = function(item) {
    var toogleStatus = !item.name_selected;
    console.log(toogleStatus);
    angular.forEach(item, function() {
        angular.forEach(item.subs, function(sub) {
            sub.selected = toogleStatus;
        });
    });
};

$scope.optionToggled = function(item, subs) {
    item.name_selected = subs.every(function(itm) {
        return itm.selected;
    })
}

jsfiddle demo

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

How to group time by hour or by 10 minutes

I know I am late to the show with this one, but I used this - pretty simple approach. This allows you to get the 60 minute slices without any rounding issues.

Select 
   CONCAT( 
            Format(endtime,'yyyy-MM-dd_HH:'),  
            LEFT(Format(endtime,'mm'),1),
            '0' 
          ) as [Time-Slice]

Getting json body in aws Lambda via API gateway

I think there are a few things to understand when working with API Gateway integration with Lambda.

Lambda Integration vs Lambda Proxy Integration

There used to be only Lambda Integration which requires mapping templates. I suppose this is why still seeing many examples using it.

As of September 2017, you no longer have to configure mappings to access the request body.

Lambda Proxy Integration, If you enable it, API Gateway will map every request to JSON and pass it to Lambda as the event object. In the Lambda function you’ll be able to retrieve query string parameters, headers, stage variables, path parameters, request context, and the body from it.

Without enabling Lambda Proxy Integration, you’ll have to create a mapping template in the Integration Request section of API Gateway and decide how to map the HTTP request to JSON yourself. And you’d likely have to create an Integration Response mapping if you were to pass information back to the client.

Before Lambda Proxy Integration was added, users were forced to map requests and responses manually, which was a source of consternation, especially with more complex mappings.

Words need to navigate the thinking. To get the terminologies straight.

  • Lambda Proxy Integration = Pass through
    Simply pass the HTTP request through to lambda.

  • Lambda Integration = Template transformation
    Go through a transformation process using the Apache Velocity template and you need to write the template by yourself.

body is escaped string, not JSON

Using Lambda Proxy Integration, the body in the event of lambda is a string escaped with backslash, not a JSON.

"body": "{\"foo\":\"bar\"}" 

If tested in a JSON formatter.

Parse error on line 1:
{\"foo\":\"bar\"}
-^
Expecting 'STRING', '}', got 'undefined'

The document below is about response but it should apply to request.

The body field, if you are returning JSON, must be converted to a string or it will cause further problems with the response. You can use JSON.stringify to handle this in Node.js functions; other runtimes will require different solutions, but the concept is the same.

For JavaScript to access it as a JSON object, need to convert it back into JSON object with json.parse in JapaScript, json.dumps in Python.

Strings are useful for transporting but you’ll want to be able to convert them back to a JSON object on the client and/or the server side.

The AWS documentation shows what to do.

if (event.body !== null && event.body !== undefined) {
    let body = JSON.parse(event.body)
    if (body.time) 
        time = body.time;
}
...
var response = {
    statusCode: responseCode,
    headers: {
        "x-custom-header" : "my custom header value"
    },
    body: JSON.stringify(responseBody)
};
console.log("response: " + JSON.stringify(response))
callback(null, response);

How to make a flex item not fill the height of the flex container?

The align-items, or respectively align-content attribute controls this behaviour.

align-items defines the items' positioning perpendicularly to flex-direction.

The default flex-direction is row, therfore vertical placement can be controlled with align-items.

There is also the align-self attribute to control the alignment on a per item basis.

_x000D_
_x000D_
#a {_x000D_
  display:flex;_x000D_
_x000D_
  align-items:flex-start;_x000D_
  align-content:flex-start;_x000D_
  }_x000D_
_x000D_
#a > div {_x000D_
  _x000D_
  background-color:red;_x000D_
  padding:5px;_x000D_
  margin:2px;_x000D_
  }_x000D_
 #a > #c {_x000D_
  align-self:stretch;_x000D_
 }
_x000D_
<div id="a">_x000D_
  _x000D_
  <div id="b">left</div>_x000D_
  <div id="c">middle</div>_x000D_
  <div>right<br>right<br>right<br>right<br>right<br></div>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

css-tricks has an excellent article on the topic. I recommend reading it a couple of times.

org.json.simple cannot be resolved

The jar file is missing. You can download the jar file and add it as external libraries in your project . You can download this from

http://www.findjar.com/jar/com/googlecode/json-simple/json-simple/1.1/json-simple-1.1.jar.html

R - Markdown avoiding package loading messages

```{r results='hide', message=FALSE, warning=FALSE}
library(RJSONIO)
library(AnotherPackage)
```

see Chunk Options in the Knitr docs

Define a struct inside a class in C++

Something like:

class Tree {

 struct node {
   int data;
   node *llink;
   node *rlink;
 };
 .....
 .....
 .....
};

Scheduled run of stored procedure on SQL server

Yes, if you use the SQL Server Agent.

Open your Enterprise Manager, and go to the Management folder under the SQL Server instance you are interested in. There you will see the SQL Server Agent, and underneath that you will see a Jobs section.

Here you can create a new job and you will see a list of steps you will need to create. When you create a new step, you can specify the step to actually run a stored procedure (type TSQL Script). Choose the database, and then for the command section put in something like:

exec MyStoredProcedure

That's the overview, post back here if you need any further advice.

[I actually thought I might get in first on this one, boy was I wrong :)]

Add custom header in HttpWebRequest

A simple method of creating the service, adding headers and reading the JSON response,

private static void WebRequest()
    {
        const string WEBSERVICE_URL = "<<Web service URL>>";
        try
        {
            var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
            if (webRequest != null)
            {
                webRequest.Method = "GET";
                webRequest.Timeout = 12000;
                webRequest.ContentType = "application/json";
                webRequest.Headers.Add("Authorization", "Basic dchZ2VudDM6cGFdGVzC5zc3dvmQ=");

                using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                    {
                        var jsonResponse = sr.ReadToEnd();
                        Console.WriteLine(String.Format("Response: {0}", jsonResponse));
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

How to include Javascript file in Asp.Net page

If your page is deeply pathed or might move around and your JS script is at "~/JS/Registration.js" of your web folder, you can try the following:

<script src='<%=ResolveClientUrl("~/JS/Registration.js") %>' 
type="text/javascript"></script>

How to display HTML <FORM> as inline element?

<form> cannot go inside <p>, no. The browser is going to abruptly close your <p> element when it hits the opening <form> tag as it tries to handle what it thinks is an unclosed paragraph element:

<p>Read this sentence 
 </p><form style='display:inline;'>

How can I pass a parameter to a t-sql script?

SQL*Plus uses &1, &2... &n to access the parameters.

Suppose you have the following script test.sql:

SET SERVEROUTPUT ON
SPOOL test.log
EXEC dbms_output.put_line('&1 &2');
SPOOL off

you could call this script like this for example:

$ sqlplus login/pw @test Hello World!

Edit:

In a UNIX script you would usually call a SQL script like this:

sqlplus /nolog << EOF
connect user/password@db
@test.sql Hello World!
exit
EOF

so that your login/password won't be visible with another session's ps

How to set the UITableView Section title programmatically (iPhone/iPad)?

If you are writing code in Swift it would look as an example like this

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
    switch section
    {
        case 0:
            return "Apple Devices"
        case 1:
            return "Samsung Devices"
        default:
            return "Other Devices"
    }
}

An App ID with Identifier '' is not available. Please enter a different string

If you've updated your profiles, and none of the other good answers are working for you, try selecting "Use local signing assets" when it asks you to "select a Development Team to use for provisioning:". I'd made sure everything else was in order, but it still wasn't working. Using local signing assets worked perfectly.

Edit: It looks like Xcode 7.3.1 fixes this issue. "- Fixed an issue that could prevent the export of an ad-hoc build from an archive"

HTML image not showing in Gmail

My issue was similar. This is what my experience has been on testing the IMG tag on gmail (assuming most of the organization's would have a dev qa and prod server.)

I had to send emails to customers on their personal email id's and we could see that gmail would add something of its own like following to src attribute of img tag. Now when we were sending these images from our dev environment they would never render on gmail and we were always curious why?

https://ci7.googleusercontent.com/proxy/AEF54znasdUhUYhuHuHuhHkHfT7u2w5zsOnWJ7k1MwrKe8pP69hY9W9eo8_n6-tW0KdSIaG4qaBEbcXue74nbVBysdfqweAsNNmmmJyTB-JQzcgn1j=s0-d-e2-ft#https://www.prodserver.com/Folder1/Images/OurImage.PNG

so an image sent to my gmail id as following never worked for me

<img src="https://ci7.googleuser....Blah.Blah..https://devserver.com/Folder1/Images/OurImage.PNG">

and our dev server we can't render this image by hitting following URL on Chrome(or any browser).

https://www.devserver.com/folder1/folder2/myactualimage.jpg

now as long as the src has www on it worked all the time and we didnt had to add any other attributes.

<img src="https://www.**prodserver**.com/folder1/folder2/myactualimage.jpg">

Get current index from foreach loop

IEnumerable list = DataGridDetail.ItemsSource as IEnumerable;
List<string> lstFile = new List<string>();

int i = 0;
foreach (var row in list)
{
bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row)).IsChecked;
if (IsChecked)
{
  MessageBox.show(i);
--Here i want to get the index or current row from the list                   

}
 ++i;
}

Is it ok to run docker from inside docker?

It's OK to run Docker-in-Docker (DinD) and in fact Docker (the company) has an official DinD image for this.

The caveat however is that it requires a privileged container, which depending on your security needs may not be a viable alternative.

The alternative solution of running Docker using sibling containers (aka Docker-out-of-Docker or DooD) does not require a privileged container, but has a few drawbacks that stem from the fact that you are launching the container from within a context that is different from that one in which it's running (i.e., you launch the container from within a container, yet it's running at the host's level, not inside the container).

I wrote a blog describing the pros/cons of DinD vs DooD here.

Having said this, Nestybox (a startup I just founded) is working on a solution that runs true Docker-in-Docker securely (without using privileged containers). You can check it out at www.nestybox.com.

Easiest way to toggle 2 classes in jQuery

Your onClick request:

<span class="A" onclick="var state = this.className.indexOf('A') > -1; $(this).toggleClass('A', !state).toggleClass('B', state);">Click Me</span>

Try it: https://jsfiddle.net/v15q6b5y/


Just the JS à la jQuery:

$('.selector').toggleClass('A', !state).toggleClass('B', state);

node: command not found

The problem is that your PATH does not include the location of the node executable.

You can likely run node as "/usr/local/bin/node".

You can add that location to your path by running the following command to add a single line to your bashrc file:

echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc

How to list records with date from the last 10 days?

you can use between too:

SELECT Table.date
  FROM Table 
  WHERE date between current_date and current_date - interval '10 day';

How many bytes in a JavaScript string?

I'm working with an embedded version of the V8 Engine. I've tested a single string. Pushing each step 1000 characters. UTF-8.

First test with single byte (8bit, ANSI) Character "A" (hex: 41). Second test with two byte character (16bit) "O" (hex: CE A9) and the third test with three byte character (24bit) "?" (hex: E2 98 BA).

In all three cases the device prints out of memory at 888 000 characters and using ca. 26 348 kb in RAM.

Result: The characters are not dynamically stored. And not with only 16bit. - Ok, perhaps only for my case (Embedded 128 MB RAM Device, V8 Engine C++/QT) - The character encoding has nothing to do with the size in ram of the javascript engine. E.g. encodingURI, etc. is only useful for highlevel data transmission and storage.

Embedded or not, fact is that the characters are not only stored in 16bit. Unfortunally I've no 100% answer, what Javascript do at low level area. Btw. I've tested the same (first test above) with an array of character "A". Pushed 1000 items every step. (Exactly the same test. Just replaced string to array) And the system bringt out of memory (wanted) after 10 416 KB using and array length of 1 337 000. So, the javascript engine is not simple restricted. It's a kind more complex.

How to make a div with a circular shape?

You can do following

FIDDLE

<div id="circle"></div>

CSS

#circle {
    width: 100px;
    height: 100px;
    background: red;
    -moz-border-radius: 50px;
    -webkit-border-radius: 50px;
    border-radius: 50px;
}

Other shape SOURCE

Find object by id in an array of JavaScript objects

Shortest,

var theAnswerObj = _.findWhere(array, {id : 42});

sprintf like functionality in Python

I'm not completely certain that I understand your goal, but you can use a StringIO instance as a buffer:

>>> import StringIO 
>>> buf = StringIO.StringIO()
>>> buf.write("A = %d, B = %s\n" % (3, "bar"))
>>> buf.write("C=%d\n" % 5)
>>> print(buf.getvalue())
A = 3, B = bar
C=5

Unlike sprintf, you just pass a string to buf.write, formatting it with the % operator or the format method of strings.

You could of course define a function to get the sprintf interface you're hoping for:

def sprintf(buf, fmt, *args):
    buf.write(fmt % args)

which would be used like this:

>>> buf = StringIO.StringIO()
>>> sprintf(buf, "A = %d, B = %s\n", 3, "foo")
>>> sprintf(buf, "C = %d\n", 5)
>>> print(buf.getvalue())
A = 3, B = foo
C = 5

How to use ConcurrentLinkedQueue?

No, the methods don't need to be synchronized, and you don't need to define any methods; they are already in ConcurrentLinkedQueue, just use them. ConcurrentLinkedQueue does all the locking and other operations you need internally; your producer(s) adds data into the queue, and your consumers poll for it.

First, create your queue:

Queue<YourObject> queue = new ConcurrentLinkedQueue<YourObject>();

Now, wherever you are creating your producer/consumer objects, pass in the queue so they have somewhere to put their objects (you could use a setter for this, instead, but I prefer to do this kind of thing in a constructor):

YourProducer producer = new YourProducer(queue);

and:

YourConsumer consumer = new YourConsumer(queue);

and add stuff to it in your producer:

queue.offer(myObject);

and take stuff out in your consumer (if the queue is empty, poll() will return null, so check it):

YourObject myObject = queue.poll();

For more info see the Javadoc

EDIT:

If you need to block waiting for the queue to not be empty, you probably want to use a LinkedBlockingQueue, and use the take() method. However, LinkedBlockingQueue has a maximum capacity (defaults to Integer.MAX_VALUE, which is over two billion) and thus may or may not be appropriate depending on your circumstances.

If you only have one thread putting stuff into the queue, and another thread taking stuff out of the queue, ConcurrentLinkedQueue is probably overkill. It's more for when you may have hundreds or even thousands of threads accessing the queue at the same time. Your needs will probably be met by using:

Queue<YourObject> queue = Collections.synchronizedList(new LinkedList<YourObject>());

A plus of this is that it locks on the instance (queue), so you can synchronize on queue to ensure atomicity of composite operations (as explained by Jared). You CANNOT do this with a ConcurrentLinkedQueue, as all operations are done WITHOUT locking on the instance (using java.util.concurrent.atomic variables). You will NOT need to do this if you want to block while the queue is empty, because poll() will simply return null while the queue is empty, and poll() is atomic. Check to see if poll() returns null. If it does, wait(), then try again. No need to lock.

Finally:

Honestly, I'd just use a LinkedBlockingQueue. It is still overkill for your application, but odds are it will work fine. If it isn't performant enough (PROFILE!), you can always try something else, and it means you don't have to deal with ANY synchronized stuff:

BlockingQueue<YourObject> queue = new LinkedBlockingQueue<YourObject>();

queue.put(myObject); // Blocks until queue isn't full.

YourObject myObject = queue.take(); // Blocks until queue isn't empty.

Everything else is the same. Put probably won't block, because you aren't likely to put two billion objects into the queue.

System not declared in scope?

Chances are that you've not included the header file that declares system().

In order to be able to compile C++ code that uses functions which you don't (manually) declare yourself, you have to pull in the declarations. These declarations are normally stored in so-called header files that you pull into the current translation unit using the #include preprocessor directive. As the code does not #include the header file in which system() is declared, the compilation fails.

To fix this issue, find out which header file provides you with the declaration of system() and include that. As mentioned in several other answers, you most likely want to add #include <cstdlib>

error MSB6006: "cmd.exe" exited with code 1

Simple and better solution : %WINDIR%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe MyProject.sln I make a bat file like this %WINDIR%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe D:\GESTION-SOMECOPA\GestionCommercial\GestionCommercial.sln pause

Then I can see all errors and correct them. Because when you change the folder name (without spaces as seen above) you will have another problems. Visual Studio 2015 works fine after this.

Viewing local storage contents on IE

Edge (as opposed to IE11) has a better UI for Local storage / Session storage and cookies:

  • Open Dev tools (F12)
  • Go to Debugger tab
  • Click the folder icon to show a list of resources - opens in a separate tab

Dev tools screenshot

Chosen Jquery Plugin - getting selected values

I believe the problem occurs when targeting by ID, because Chosen will copy the ID from the original select onto it's newly created div, leaving you with 2 elements of the same (now not-unique) ID on the current page.

When targeting Chosen by ID, use a selector specific to the select:

$( 'select#yourID' ).on( 'change', function() {
    console.log( $( this ).val() );
} );

...instead of...

$( '#yourID' ).on( 'change', function() {
    console.log( $( this ).val() );
} );

This works because Chosen mirrors its selected items back to the original (now hidden) select element, even in multi-mode.

(It also continues to work with or without Chosen, say... if you decide to go a different direction in your application.)

How do I auto-resize an image to fit a 'div' container?

I see that many people have suggested object-fit which is a good option. But if you want it to work in older browsers as well, there is another way of doing it easily.

Its quite simple. The approach I took was to position the image inside the container with absolute and then place it right at the centre using the combination:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

Once it is in the centre, I give to the image,

// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;

// For Horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;

This makes the image get the effect of Object-fit:cover.


Here is a demonstration of the above logic.

https://jsfiddle.net/furqan_694/s3xLe1gp/

This logic works in all browsers.

String compare in Perl with "eq" vs "=="

Maybe the condition you are using is incorrect:

$str1 == "taste" && $str2 == "waste"

The program will enter into THEN part only when both of the stated conditions are true.

You can try with $str1 == "taste" || $str2 == "waste". This will execute the THEN part if anyone of the above conditions are true.

How to pass command line argument to gnuplot?

You can pass arguments to a gnuplot script since version 5.0, with the flag -c. These arguments are accessed through the variables ARG0 to ARG9, ARG0 being the script, and ARG1 to ARG9 string variables. The number of arguments is given by ARGC.

For example, the following script ("script.gp")

#!/usr/local/bin/gnuplot --persist

THIRD=ARG3
print "script name        : ", ARG0
print "first argument     : ", ARG1
print "third argument     : ", THIRD 
print "number of arguments: ", ARGC 

can be called as:

$ gnuplot -c script.gp one two three four five
script name        : script.gp
first argument     : one
third argument     : three
number of arguments: 5

or within gnuplot as

gnuplot> call 'script.gp' one two three four five
script name        : script.gp
first argument     : one
third argument     : three
number of arguments: 5

In gnuplot 4.6.6 and earlier, there exists a call mechanism with a different (now deprecated) syntax. The arguments are accessed through $#, $0,...,$9. For example, the same script above looks like:

#!/usr/bin/gnuplot --persist

THIRD="$2"
print "first argument     : ", "$0"
print "second argument    : ", "$1"
print "third argument     : ", THIRD
print "number of arguments: ", "$#"

and it is called within gnuplot as (remember, version <4.6.6)

gnuplot> call 'script4.gp' one two three four five
first argument     : one
second argument    : two
third argument     : three
number of arguments: 5

Notice there is no variable for the script name, so $0 is the first argument, and the variables are called within quotes. There is no way to use this directly from the command line, only through tricks as the one suggested by @con-fu-se.

Replace a newline in TSQL

If you have have open procedure with using sp_helptext then just copy all text in new sql query and press ctrl+h button use regular expression to replace and put ^\n in find field replace with blank . for more detail check image.enter image description here

fetch in git doesn't get all branches

I had this issue today on a repo.

It wasn't the +refs/heads/*:refs/remotes/origin/* issue as per top solution.

Symptom was simply that git fetch origin or git fetch just didn't appear to do anything, although there were remote branches to fetch.

After trying lots of things, I removed the origin remote, and recreated it. That seems to have fixed it. Don't know why.

remove with: git remote rm origin

and recreate with: git remote add origin <git uri>

Reading JSON from a file?

Here is a copy of code which works fine for me

import json

with open("test.json") as json_file:
    json_data = json.load(json_file)
    print(json_data)

with the data

{
    "a": [1,3,"asdf",true],
    "b": {
        "Hello": "world"
    }
}

you may want to wrap your json.load line with a try catch because invalid JSON will cause a stacktrace error message.

IF EXISTS condition not working with PLSQL

Unfortunately PL/SQL doesn't have IF EXISTS operator like SQL Server. But you can do something like this:

begin
  for x in ( select count(*) cnt
               from dual 
              where exists (
                select 1 from courseoffering co
                  join co_enrolment ce on ce.co_id = co.co_id
                 where ce.s_regno = 403 
                   and ce.coe_completionstatus = 'C' 
                   and co.c_id = 803 ) )
  loop
        if ( x.cnt = 1 ) 
        then
           dbms_output.put_line('exists');
        else 
           dbms_output.put_line('does not exist');
        end if;
  end loop;
end;
/

How do you post to the wall on a facebook page (not profile)

Harish has the answer here - except you need to request manage_pages permission when authenticating and then using the page-id instead of me when posting....

$result = $facebook->api('page-id/feed/','post',$attachment);

Get date from input form within PHP

Validate the INPUT.

$time = strtotime($_POST['dateFrom']);
if ($time) {
  $new_date = date('Y-m-d', $time);
  echo $new_date;
} else {
   echo 'Invalid Date: ' . $_POST['dateFrom'];
  // fix it.
}

MySQL Creating tables with Foreign Keys giving errno: 150

MySQL Workbench 6.3 for Mac OS.

Problem: errno 150 on table X when trying to do Forward Engineering on a DB diagram, 20 out of 21 succeeded, 1 failed. If FKs on table X were deleted, the error moved to a different table that wasn't failing before.

Changed all tables engine to myISAM and it worked just fine.

enter image description here

Parse an URL in JavaScript

This should fix a few edge-cases in kobe's answer:

function getQueryParam(url, key) {
  var queryStartPos = url.indexOf('?');
  if (queryStartPos === -1) {
    return;
  }
  var params = url.substring(queryStartPos + 1).split('&');
  for (var i = 0; i < params.length; i++) {
    var pairs = params[i].split('=');
    if (decodeURIComponent(pairs.shift()) == key) {
      return decodeURIComponent(pairs.join('='));
    }
  }
}

getQueryParam('http://example.com/form_image_edit.php?img_id=33', 'img_id');
// outputs "33"

How to get changes from another branch

  1. go to the master branch our-team

    • git checkout our-team
  2. pull all the new changes from our-team branch

    • git pull
  3. go to your branch featurex

    • git checkout featurex
  4. merge the changes of our-team branch into featurex branch

    • git merge our-team
    • or git cherry-pick {commit-hash} if you want to merge specific commits
  5. push your changes with the changes of our-team branch

    • git push

Note: probably you will have to fix conflicts after merging our-team branch into featurex branch before pushing

How exactly does __attribute__((constructor)) work?

  1. It runs when a shared library is loaded, typically during program startup.
  2. That's how all GCC attributes are; presumably to distinguish them from function calls.
  3. GCC-specific syntax.
  4. Yes, this works in C and C++.
  5. No, the function does not need to be static.
  6. The destructor runs when the shared library is unloaded, typically at program exit.

So, the way the constructors and destructors work is that the shared object file contains special sections (.ctors and .dtors on ELF) which contain references to the functions marked with the constructor and destructor attributes, respectively. When the library is loaded/unloaded the dynamic loader program (ld.so or somesuch) checks whether such sections exist, and if so, calls the functions referenced therein.

Come to think of it, there is probably some similar magic in the normal static linker so that the same code is run on startup/shutdown regardless if the user chooses static or dynamic linking.

How Does Modulus Divison Work

Lets say you have 17 mod 6.

what total of 6 will get you the closest to 17, it will be 12 because if you go over 12 you will have 18 which is more that the question of 17 mod 6. You will then take 12 and minus from 17 which will give you your answer, in this case 5.

17 mod 6=5

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

In my case the answer is pretty simple. Please check carefully the hardcoded url port: it is 8080. For some reason the value has changed to: for example 3030.

Just refresh the port in your ajax url string to the appropriate one.

conn = new WebSocket('ws://localhost:3030'); //should solve the issue

How do I install imagemagick with homebrew?

brew install imagemagick

Don't forget to install also gs which is a dependency if you want to convert pdf to images for example :

brew install ghostscript

Angular2 RC6: '<component> is not a known element'

HUMAN ERROR - DON'T BE MISLED BY THE ERROR MESSAGE.

Why I got misled: The component I wanted to consume (ComponentA) was correctly declared in it's module (ModuleA). It was correctly exported there, too. The module (ModuleB) of the component (ComponentB) I am working in, had the import for ModuleA correctly specified. However, because of the error message being < component-a-selector > is not a known element', my entire focus was in thinking that it was a problem with ModuleA/ComponentA as that is what the error message contained; I didn't think to look at the component I was trying to consume it from. I followed every single post in every threat about this, but was ultimately missing one vital step:

What fixed it for me: frot.io's answer prompted me to check my app.module.ts import list and the component I was working in (ComponentB) was not included!

How to convert a datetime to string in T-SQL

In addition to the CAST and CONVERT functions in the previous answers, if you are using SQL Server 2012 and above you use the FORMAT function to convert a DATETIME based type to a string.

To convert back, use the opposite PARSE or TRYPARSE functions.

The formatting styles are based on .NET (similar to the string formatting options of the ToString() method) and has the advantage of being culture aware. eg.

DECLARE @DateTime DATETIME2 = SYSDATETIME();
DECLARE @StringResult1 NVARCHAR(100) = FORMAT(@DateTime, 'g') --without culture
DECLARE @StringResult2 NVARCHAR(100) = FORMAT(@DateTime, 'g', 'en-gb') 
SELECT @DateTime
SELECT @StringResult1, @StringResult2
SELECT PARSE(@StringResult1 AS DATETIME2)
SELECT PARSE(@StringResult2 AS DATETIME2 USING 'en-gb')

Results:

2015-06-17 06:20:09.1320951
6/17/2015 6:20 AM
17/06/2015 06:20
2015-06-17 06:20:00.0000000
2015-06-17 06:20:00.0000000

Read only file system on Android

Got this off an Android forum where I asked the same question. Hope this helps somebody else.

On a terminal emulator on the phone:

mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system

Then on the cmd prompt, do the adb push

How do I access (read, write) Google Sheets spreadsheets with Python?

Take a look at gspread port for api v4 - pygsheets. It should be very easy to use rather than the google client.

Sample example

import pygsheets

gc = pygsheets.authorize()

# Open spreadsheet and then workseet
sh = gc.open('my new ssheet')
wks = sh.sheet1

# Update a cell with value (just to let him know values is updated ;) )
wks.update_cell('A1', "Hey yank this numpy array")

# update the sheet with array
wks.update_cells('A2', my_nparray.to_list())

# share the sheet with your friend
sh.share("[email protected]")

See the docs here.

Author here.

Creating/writing into a new file in Qt

#include <QFile>
#include <QCoreApplication>
#include <QTextStream>

int main(int argc, char *argv[])
{
    // Create a new file     
    QFile file("out.txt");
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&file);
    out << "This file is generated by Qt\n";

    // optional, as QFile destructor will already do it:
    file.close(); 

    //this would normally start the event loop, but is not needed for this
    //minimal example:
    //return app.exec();

    return 0;
}

how to fix Cannot call sendRedirect() after the response has been committed?

The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.

It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.

JAVA 7 OFFICIAL LINK

ADDITIONAL INFO

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

Being aware of the transaction (autocommit, explicit and implicit) handling for your database can save you from having to restore data from a backup.

Transactions control data manipulation statement(s) to ensure they are atomic. Being "atomic" means the transaction either occurs, or it does not. The only way to signal the completion of the transaction to database is by using either a COMMIT or ROLLBACK statement (per ANSI-92, which sadly did not include syntax for creating/beginning a transaction so it is vendor specific). COMMIT applies the changes (if any) made within the transaction. ROLLBACK disregards whatever actions took place within the transaction - highly desirable when an UPDATE/DELETE statement does something unintended.

Typically individual DML (Insert, Update, Delete) statements are performed in an autocommit transaction - they are committed as soon as the statement successfully completes. Which means there's no opportunity to roll back the database to the state prior to the statement having been run in cases like yours. When something goes wrong, the only restoration option available is to reconstruct the data from a backup (providing one exists). In MySQL, autocommit is on by default for InnoDB - MyISAM doesn't support transactions. It can be disabled by using:

SET autocommit = 0

An explicit transaction is when statement(s) are wrapped within an explicitly defined transaction code block - for MySQL, that's START TRANSACTION. It also requires an explicitly made COMMIT or ROLLBACK statement at the end of the transaction. Nested transactions is beyond the scope of this topic.

Implicit transactions are slightly different from explicit ones. Implicit transactions do not require explicity defining a transaction. However, like explicit transactions they require a COMMIT or ROLLBACK statement to be supplied.

Conclusion

Explicit transactions are the most ideal solution - they require a statement, COMMIT or ROLLBACK, to finalize the transaction, and what is happening is clearly stated for others to read should there be a need. Implicit transactions are OK if working with the database interactively, but COMMIT statements should only be specified once results have been tested & thoroughly determined to be valid.

That means you should use:

SET autocommit = 0;

START TRANSACTION;
  UPDATE ...;

...and only use COMMIT; when the results are correct.

That said, UPDATE and DELETE statements typically only return the number of rows affected, not specific details. Convert such statements into SELECT statements & review the results to ensure correctness prior to attempting the UPDATE/DELETE statement.

Addendum

DDL (Data Definition Language) statements are automatically committed - they do not require a COMMIT statement. IE: Table, index, stored procedure, database, and view creation or alteration statements.

jQuery or JavaScript auto click

You are trying to make a popup work maybe? I don't know how to emulate click, maybe you can try to fire click event somehow, but I don't know if it is possible. More than likely such functionality is not implemented, because of security and privacy concerns.

You can use div with position:absolute to emulate popup at the same page. If you insist creating another page, I cannot help you. Maybe somebody else with more experience will add his 15 cents.

How to drop a table if it exists?

A better visual and easy way, if you are using Visual Studio, just open from menu bar,

View -> SQL Server Object Explorer

it should open like shown here

enter image description here

Select and Right Click the Table you wish to delete, then delete. Such a screen should be displayed. Click Update Database to confirm.

enter image description here

This method is very safe as it gives you the feedback and will warn of any relations of the deleted table with other tables.

What is the official name for a credit card's 3 digit code?

It's got a number of names. Most likely you've heard it as either Card Security Code (CSC) or Card Verification Value (CVV).

Card Security Code

Infinite Recursion with Jackson JSON and Hibernate JPA issue

I have the same problem after doing more analysis i came to know that, we can get mapped entity also by just keeping @JsonBackReference at OneToMany annotation

@Entity
@Table(name = "ta_trainee", uniqueConstraints = {@UniqueConstraint(columnNames = {"id"})})
public class Trainee extends BusinessObject {

@Id
@GeneratedValue(strategy = GenerationType.TABLE)
@Column(name = "id", nullable = false)
private Integer id;

@Column(name = "name", nullable = true)
private String name;

@Column(name = "surname", nullable = true)
private String surname;

@OneToMany(mappedBy = "trainee", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@Column(nullable = true)
@JsonBackReference
private Set<BodyStat> bodyStats;

What's the difference between the 'ref' and 'out' keywords?

If you want to pass your parameter as a ref then you should initialize it before passing parameter to the function else compiler itself will show the error.But in case of out parameter you don't need to initialize the object parameter before passing it to the method.You can initialize the object in the calling method itself.

How to randomize Excel rows

Here's a macro that allows you to shuffle selected cells in a column:

Option Explicit

Sub ShuffleSelectedCells()
  'Do nothing if selecting only one cell
  If Selection.Cells.Count = 1 Then Exit Sub
  'Save selected cells to array
  Dim CellData() As Variant
  CellData = Selection.Value
  'Shuffle the array
  ShuffleArrayInPlace CellData
  'Output array to spreadsheet
  Selection.Value = CellData
End Sub

Sub ShuffleArrayInPlace(InArray() As Variant)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ShuffleArrayInPlace
' This shuffles InArray to random order, randomized in place.
' Source: http://www.cpearson.com/excel/ShuffleArray.aspx
' Modified by Tom Doan to work with Selection.Value two-dimensional arrays.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
  Dim J As Long, _
    N As Long, _
    Temp As Variant
  'Randomize
  For N = LBound(InArray) To UBound(InArray)
    J = CLng(((UBound(InArray) - N) * Rnd) + N)
    If J <> N Then
      Temp = InArray(N, 1)
      InArray(N, 1) = InArray(J, 1)
      InArray(J, 1) = Temp
    End If
  Next N
End Sub

You can read the comments to see what the macro is doing. Here's how to install the macro:

  1. Open the VBA editor (Alt + F11).
  2. Right-click on "ThisWorkbook" under your currently open spreadsheet (listed in parentheses after "VBAProject") and select Insert / Module.
  3. Paste the code above and save the spreadsheet.

Now you can assign the "ShuffleSelectedCells" macro to an icon or hotkey to quickly randomize your selected rows (keep in mind that you can only select one column of rows).

Python: Making a beep noise

I have made a package for that purpose.

You can use it like this:

from pybeep.pybeep import PyVibrate, PyBeep
PyVibrate().beep()
PyVibrate().beepn(3)
PyBeep().beep()
PyBeep().beepn(3)

It depends on sox and only supports python3.

Execute a PHP script from another PHP script

You can invoke a PHP script manually from the command line

hello.php
<?php
 echo 'hello world!';
?>

Command line:
php hello.php

Output:
hello world!

See the documentation: http://php.net/manual/en/features.commandline.php


EDIT OP edited the question to add a critical detail: the script is to be executed by another script.

There are a couple of approaches. First and easiest, you could simply include the file. When you include a file, the code within is "executed" (actually, interpreted). Any code that is not within a function or class body will be processed immediately. Take a look at the documentation for include (docs) and/or require (docs) (note: include_once and require_once are related, but different in an important way. Check out the documents to understand the difference) Your code would look like this:

 include('hello.php');
 /* output
 hello world!
 */

Second and slightly more complex is to use shell_exec (docs). With shell_exec, you will call the php binary and pass the desired script as the argument. Your code would look like this:

$output = shell_exec('php hello.php');
echo "<pre>$output</pre>";
/* output
hello world!
*/

Finally, and most complex, you could use the CURL library to call the file as though it were requested via a browser. Check out the CURL library documentation here: http://us2.php.net/manual/en/ref.curl.php

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.myDomain.com/hello.php");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)

$output = curl_exec($ch);
curl_close($ch);
echo "<pre>$output</pre>";
/* output
hello world!
*/

Documentation for functions used

How can I write a heredoc to a file in Bash script?

For future people who may have this issue the following format worked:

(cat <<- _EOF_
        LogFile /var/log/clamd.log
        LogTime yes
        DatabaseDirectory /var/lib/clamav
        LocalSocket /tmp/clamd.socket
        TCPAddr 127.0.0.1
        SelfCheck 1020
        ScanPDF yes
        _EOF_
) > /etc/clamd.conf

Verifying that a string contains only letters in C#

Only letters:

Regex.IsMatch(input, @"^[a-zA-Z]+$");

Only letters and numbers:

Regex.IsMatch(input, @"^[a-zA-Z0-9]+$");

Only letters, numbers and underscore:

Regex.IsMatch(input, @"^[a-zA-Z0-9_]+$");

How can I make an svg scale with its parent container?

You'll want to do a transform as such:

with JavaScript:

document.getElementById(yourtarget).setAttribute("transform", "scale(2.0)");

With CSS:

#yourtarget {
  transform:scale(2.0);
  -webkit-transform:scale(2.0);
}

Wrap your SVG Page in a Group tag as such and target it to manipulate the whole page:

<svg>
  <g id="yourtarget">
    your svg page
  </g>
</svg>

Note: Scale 1.0 is 100%

Adjusting the Xcode iPhone simulator scale and size

You can't have 1:1 ratio.

However you can scale it from the iOS Simulator > Window > Scale menu.

EditText onClickListener in Android

I had this same problem. The code is fine but make sure you change the focusable value of the EditText to false.

<EditText
android:id="@+id/date"
android:focusable="false"/>

I hope this helps anyone who has had a similar problem!

Why is NULL undeclared?

Do use NULL. It is just #defined as 0 anyway and it is very useful to semantically distinguish it from the integer 0.

There are problems with using 0 (and hence NULL). For example:

void f(int);
void f(void*);

f(0); // Ambiguous. Calls f(int).

The next version of C++ (C++0x) includes nullptr to fix this.

f(nullptr); // Calls f(void*).

Uploading file using POST request in Node.js

An undocumented feature of the formData field that request implements is the ability to pass options to the form-data module it uses:

request({
  url: 'http://example.com',
  method: 'POST',
  formData: {
    'regularField': 'someValue',
    'regularFile': someFileStream,
    'customBufferFile': {
      value: fileBufferData,
      options: {
        filename: 'myfile.bin'
      }
    }
  }
}, handleResponse);

This is useful if you need to avoid calling requestObj.form() but need to upload a buffer as a file. The form-data module also accepts contentType (the MIME type) and knownLength options.

This change was added in October 2014 (so 2 months after this question was asked), so it should be safe to use now (in 2017+). This equates to version v2.46.0 or above of request.

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

Every service that is bound in activity must be unbind on app close.

So try using

 onPause(){
   unbindService(YOUR_SERVICE);
   super.onPause();
 }